text:
Q: Android sending data to php and receiving issue nullpointerexception Im new to android developement and I am not sure what I missing to allow the code to work. Trying to create log in application. Could there  be a problem with the way I am receiving the data or sending the data using dataoutputstream? of is there a better way that is not deprecated and complicated. Looking for the most minimalistic understandable solution.
Do in background code
@Override
protected Boolean doInBackground(String... params) {

    DataOutputStream printout;
    HttpURLConnection urlConn;
    BufferedReader reader;
    URL url;
    String json;
    JSONObject jObj;

    //send POST login details to server
    try {
        url = new URL(SERVER_ADDRESS + "login.php");
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Accept-Charset", "UTF-8");
        urlConn.setReadTimeout(10000);
        urlConn.setConnectTimeout(15000);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("username", params[0]);
        map.put("password", params[1]);

        StringBuilder sb = new StringBuilder();
        for(HashMap.Entry<String, String> e : map.entrySet()){
            if(sb.length() > 0){
                sb.append("&");
            }
            sb.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
        }

        String loginDetails = sb.toString();

        printout = new DataOutputStream(urlConn.getOutputStream());
        printout.writeBytes(loginDetails);
        printout.flush();
        printout.close();

        reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        StringBuilder sb2 = new StringBuilder();
        String result = null;
        while((result=reader.readLine())!=null) {
            sb2.append(result + '\n');
            Log.d("Results", sb2.toString());
        };

        json = result.toString();

        jObj = new JSONObject(json);

        JSONLogin = jObj.getBoolean(TAG_LOGINSTATUS);
        Log.d("LoginStatus!!!!", JSONLogin.toString());

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.d("JsonConvertion", "FAILED TO CONVERT JSON");
    }

    return JSONLogin;
}

Stack error
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: Process: com.httpkhronolog.khronolog, PID: 2459
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime: java.lang.RuntimeException: An error occurred while executing doInBackground()
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:309)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:137)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at com.httpkhronolog.khronolog.Login_Activity$checkUserDetails.doInBackground(Login_Activity.java:79)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
10-18 22:43:34.169 2459-2523/? E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)

login.php
<?php

    if($_SERVER["REQUEST_METHOD"] == "POST"){
       // Establishing Connection with Server by passing server_name, user_id and password as a parameter
       $connection = mysql_connect("localhost", "someusername", "Password");
       // Selecting Database
       $db = mysql_select_db("khronolo_systemdb", $connection);

       $username = $_POST["username"];
       $password =  $_POST["password"];

       $query = "SELECT * FROM user_table WHERE password='$password' AND email='$username';";
       $result = mysql_query($query, $connection) or die (mysql_error($connection));
       $rows = mysql_num_rows($result);
       if ($rows == 1) {
          $returnValue[] = array("loginStatus"=> "true");
          echo json_encode($returnValue);
       }
       else {
          $returnValue[] = array("loginStatus"=> "false");
          echo json_encode($returnValue);
       }

       mysql_close($connection);
    }
    ?>

A: Use Volley a Network Library from Google. Follow this tutorial for the same. To know more about Volley refer this link
There are also other Networking libraries like okHttp.
And as of now your code is considered :
replace json = result.toString(); with json = sb2.toString(); at line 137

A: Instead of
json = result.toString();

You should do
json = sb2.toString();

Explanation
Your while loop when exits, the result will be null, so doing result.toString() would lead to nullpointerexception.
Any other library
You can use GSON library to help you get/set the response values without any hurdle.
GSON error


text:
Q: how to import multiple folders in bloomrpc I am using grpc for my project. I need to import proto files from multiple folders. If I import directly it is not working. How can I import them all at the same time?
I would appreciate your response.

A: Actually it is very simple. I found a way here:
I've tried your example protos my self and i've got the same error.
Although i then noticed that you have something wrong in your protos/exampleService.proto.
If both of the protos lives within the same folder then your import should be only import "exampleModel.proto"; without the protos prefix`. If you try to load it like this it works.
The reason why your protoc works is because you probably have set an import path resolution.

*

*So if you don't want to change your import, you need to tell bloomrpc the same thing.

*Open the import path option on the sidebar

*Add the absolute path the to folder one step back to the protos folder.

*Try importing again

redpajama_set_name: RedPajamaStackExchange


text:
Q: Code for polyfill requestNextAnimationFrame code I have the following code from Core HTML 5 canvas:
    window.requestNextAnimationFrame = (function() {
    var originalWebkitRequestAnimationFrame = undefined,
    wrapper = undefined,
    callback = undefined,
    geckoVersion = 0,
    userAgent = navigator.userAgent,
    index = 0,
    self = this;

    // Workaround for Chrome 10 bug where Chrome
    // does not pass the time to the animation function

    if (window.webkitRequestAnimationFrame) {
        wrapper = function(time) {

            if (time === undefined) {
                time += new Date();
            }

            self.callback(time);
        };

        // Make the switch

        originalWebkitRequestAnimationFrame = window.webkitRequestAnimationFrame;

        window.webkitRequestAnimationFrame = function(wrapper, element) {
            self.callback = callback;

            // Browser calls the wrapper and wrapper calls the callback

            originalWebkitRequestAnimationFrame(wrapper, element);
        };
    }

    // Workaround for Gecko 2.0, which has a bug in
    // mozRequestAnimationFrame() that restricts animations
    // to 30-40 fps.

    if (window.mozRequestAnimationFrame) {
        // Check the Gecko version. Gecko is used by browsers
        // other than Firefox. Gecko 2.0 corresponds to
        // Firefox 4.0.

        index = userAgent.indexOf('rv:');

        if (userAgent.indexOf('Gecko') != -1) {
            geckoVersion = userAgent.substr(index + 3, 3);

            if (geckoVersion === '2.0') {
                // Forces the return statement to fall through
                // to the setTimeout() function.

                window.mozRequestAnimationFrame = undefined;
            }
        }
    }

    return window.requestAnimationFrame ||
           window.webkitRequestAnimationFrame ||
           window.mozRequestAnimationFrame ||
           window.oRequestAnimationFrame ||
           window.msRequestAnimationFrame ||

         function(callback, element) {
             var start,
                finish;

             window.setTimeout(function() {
                 start = +new Date();
                 callback(start);
                 finish = +new Date();

                 self.timeout = 1000 / 60 - (finish - start);

             }, self.timeout);
         };
})();

When I look in Chrome console, it seems to have window.webkitRequestAnimationFrame as well as window.requestAnimationFrame. Correct me if I'm wrong, but window.requestAnimationFrame is the newer one, and it's the one I should be using.
If that's true, then doesn't this code spent time constructing things for window.requestNextAnimationFrame? Shouldn't it skip that code if the version of Chrome I have also has window.requestAnimationFrame?

A: If window.requestAnimationFrame is defined, a developer should give for granted what it works as the specs. Everything else should be taken case by case. webkit.webkitRequestAnimationFrame should be ignored.
Also, I'd like to add that very old browsers sometimes can live with their broken implementations. In particular, if Firefox 4 is limited to 40 fps, nothing bad will really happen, since we can say that nobody uses Firefox 4 anymore, and if someone does 40 fps is good for most of the cases.
Same thing for Chrome 10 (nobody should even use it anymore): the workaround seems overkill to me. If you really want to fix a bug, you may want to check if the bug is there first, for example:
window.webkitRequestAnimationFrame(function(time) {
    if (time === undefined) {
        // ... Fix!
    }
});

Remember: user agent sniffing is bad.
The less the code you serve, the better. This is my opinion, anyway. You should adapt everything to your case (and user base).


text:
Q: digital signature using pdfbox I am trying to add multiple signatures to my pdf using pdfbox, I am trying with two signatures and second signature always turns to be invalid.Please advice,
Can a be  PDF be signed digitally several times?    Adobe livecycle forums says yes.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.List;

import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.exceptions.SignatureException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSSignedGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SigningTest implements SignatureInterface {

    private static BouncyCastleProvider provider = new BouncyCastleProvider();

    private PrivateKey privKey;

    private Certificate[] cert;

    public SigningTest(KeyStore keystore, char[] pin) {
        try {
            Enumeration<String> aliases = keystore.aliases();
            String alias = null;
            if (aliases.hasMoreElements())
                alias = aliases.nextElement();
            else
                throw new RuntimeException("Could not find Key");
            privKey = (PrivateKey) keystore.getKey(alias, pin);
            cert = keystore.getCertificateChain(alias);
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public byte[] sign(InputStream content) throws SignatureException,
            IOException {
        CMSProcessableInputStream input = new CMSProcessableInputStream(content);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        // CertificateChain
        List<Certificate> certList = Arrays.asList(cert);

        CertStore certStore = null;
        try {
            certStore = CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(certList), provider);
            gen.addSigner(privKey, (X509Certificate) certList.get(0),
                    CMSSignedGenerator.DIGEST_SHA256);
            gen.addCertificatesAndCRLs(certStore);
            CMSSignedData signedData = gen.generate(input, false, provider);
            return signedData.getEncoded();
        } catch (Exception e) {
            // should be handled
            e.printStackTrace();
        }
        throw new RuntimeException("Problem while preparing signature");
    }

    public static void main(String[] args) throws KeyStoreException,
            NoSuchAlgorithmException, CertificateException,
            FileNotFoundException, IOException, COSVisitorException,
            SignatureException, Exception {
        File document = new File("resources/OCD.pdf");
        PDDocument pdDocument = PDDocument.load(document);

        addSignature(pdDocument, "resources/j4l_test.p12", "test");
        addSignature(pdDocument, "resources/my.p12", "123456");

        File outputDocument = new File("resources/signed" + document.getName());
        FileInputStream fis = new FileInputStream(document);
        FileOutputStream fos = new FileOutputStream(outputDocument);
        byte[] buffer = new byte[8 * 1024];
        int c;
        while ((c = fis.read(buffer)) != -1)
        {
          fos.write(buffer, 0, c);
        }
        fis.close();
        fis = new FileInputStream(outputDocument);

        pdDocument.saveIncremental(fis, fos);
        //pdDocument.close();

    }

    static void addSignature(PDDocument  pdDocument,  String filePath,String pwd)  throws Exception{
        File ksFile = new File(filePath);
        KeyStore keystore = KeyStore.getInstance("PKCS12", provider);
        char[] pin = pwd.toCharArray();
        keystore.load(new FileInputStream(ksFile), pin);
        SigningTest signing = new SigningTest(keystore, pin.clone());
        //signing.signPDF(document);

        // create signature dictionary
        PDSignature signature = new PDSignature();
        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // default filter
        // subfilter for basic and PAdES Part 2 signatures
        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
        signature.setName("signer name");
        signature.setLocation("signer location");
        signature.setReason("reason for signature");

        // the signing date, needed for valid signature
        signature.setSignDate(Calendar.getInstance());
//      SignatureOptions signatureOptions= new SignatureOptions();
//      signatureOptions.setVisualSignature();
        // register signature dictionary and sign interface
        pdDocument.addSignature(signature, signing);

    }
}

class CMSProcessableInputStream implements CMSProcessable {

    InputStream in;

    public CMSProcessableInputStream(InputStream is) {
        in = is;
    }

    public Object getContent() {
        return null;
    }

    public void write(OutputStream out) throws IOException, CMSException {
        // read the content only one time
        byte[] buffer = new byte[8 * 1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
    }
}

A:
Can a be PDF be signed digitally several times

Yes, it can, but that has to happen in consecutive incremental updates, not in the same revision.
You do
PDDocument pdDocument = PDDocument.load(document);
addSignature(pdDocument, "resources/j4l_test.p12", "test");
addSignature(pdDocument, "resources/my.p12", "123456");
...
pdDocument.saveIncremental(fis, fos);

But you'd have to do
PDDocument pdDocument = PDDocument.load(document);
addSignature(pdDocument, "resources/j4l_test.p12", "test");
...
pdDocument.saveIncremental(fis, fos); // fos an intermediary file

...

pdDocument = PDDocument.load(intermediaryFile);
addSignature(pdDocument, "resources/my.p12", "123456");
...
pdDocument.saveIncremental(fis, fos); // fos the final file

Some backgrounds can be found in this answer and the links therein.


text:
Q: Possible to force https only on AWS Lightsail? I am using an AWS Lightsail Load Balancer in conjunction with another Lightsail ec2 instance so that I can use the free certificate manager built into the Lightsail Load Balancer. This seems to automatically forward all traffic from my Load Balancer to my ec2 nginx server on port 80 so that the following config also supports https connections:
server {
    listen       80;
    server_name  mountainviewwebtech.ca www.mountainviewwebtech.ca;

    location / {
        proxy_pass              http://localhost:3000;
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;
    }
}

However, when I add the following lines to ensure that http redirects to https, I receive the error ERR_TOO_MANY_REDIRECTS as my ec2-instance is only receiving traffic on port 80 even when using a secure connection so it just keeps redirecting over and over again.
if ($scheme != https) {
    return 301 https://$host$request_uri;
}

Is there anyway to obtain the original $scheme before it was forwarded to my ec2 instance?

A: If you are wanting a 'free' SSL cert, using Let's Encrypt's CertBot will get you there (and save you money). I have had good success with this option.
Using the load balancer as the SSL terminator ends the secure connection at the load balancer. Thus un-encrypted traffic is sent from the balancer to the compute instances (port 80). If you want to forward SSL traffic to the compute instances, see if the load balancer will do port forwarding. This being Lightsail I doubt it will be possible.


text:
Q: How to get Mysql rownum continously over the pagenation Basically, i want to display the number of rows from table along with the data by using @rownum it works just fine for first page but when we go to the next page we it start with row one again.
query code:
$sql = "SELECT @rownum:=@rownum+1 as rownum, t.*FROM (SELECT @rownum:=0) r, (select * from tbl) t
         LIMIT $Page_Start , $Per_Page";

pagenation code:
$objConnect = mysql_connect("localhost","user","pass") or die("Error Connect to Database");
`enter code here`$objDB = mysql_select_db("WEB");
$strSQL = "SELECT * FROM line ";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
$Num_Rows = mysql_num_rows($objQuery);

$Per_Page = 2; // Per Page

$Page = mysql_real_escape_string($_GET["Page"]);
if(!$_GET["Page"])
{
 $Page=1;
 }

 $Prev_Page = $Page-1;
 $Next_Page = $Page+1;

 $Page_Start = (($Per_Page*$Page)-$Per_Page);
  if($Num_Rows<=$Per_Page)
 {
 $Num_Pages =1;
 }
 else if(($Num_Rows % $Per_Page)==0)
 {
 $Num_Pages =($Num_Rows/$Per_Page) ;
 }
 else
 {
  $Num_Pages =($Num_Rows/$Per_Page)+1;
  $Num_Pages = (int)$Num_Pages;
   }

pagenation usage:
if($Prev_Page)
{
echo " Back &nbsp   ";
}

if($Page!=$Num_Pages)
{
echo " Next ";
}

So i want the number of row continuously increase page after pages
example page 1  row 1-5 and page2 should be 6-10 something like that
Thanks a lot

A: You need to wrap the calculation to get row number inside a subquery and limit it on the outer SELECT statement so the row_number won't break, ex,
the column name and table name might be different form your example above but the thought of the query is the same.
SELECT  RowNumber, Student_ID, Student_Name
FROM
        (
            SELECT  @rownum := @rownum + 1 RowNumber,
                    t.*
            FROM    student t, (SELECT @rownum := 0) s
            ORDER   BY t.Student_ID
        ) subQ
// LIMIT    0, 3

*

*SQLFiddle Demo (with LIMIT but continues even in pagenation)


text:
Q: jquery var define only first element I have a problem with jquery var and i'm so confused..
I make a var due to variable "id" but it affect only on the first element:
jQuery:
var butInfo = $(".but > div").attr("id");

$("#" + butInfo).each(function(){
    $(this)
        .mouseenter(function(){
            $(".txt").hide();
            $(".txt."+butInfo).show();})
        .mouseleave(function(){
            $(".txt."+butInfo).hide();});
});

HTML:

A

B

C

A A A A A

B B B B B

C C C C C

http://jsfiddle.net/74FYW/
as you see, only the first div with id="a" is working, while the rest is still not working..
why that happened?!!
UPDATE:
==========
I found finally what I want.
the solution simply is to put the var line after jquery function not before it;
this is what I mean:
$(".but > div").each(function(){
  var butInfo = $(this).attr("id");
  $(this)
    .mouseenter(function(){
      $(".txt").hide();
      $(".txt."+butInfo).show();
    })
    .mouseleave(function(){
      $(".txt."+butInfo).hide();
    });
});

JSFiddle Demo:

A: attr gets an attribute of the first element from the matched collection. Try something like this instead:
var $txt = $(".txt").hide();
$(".but > div").mouseenter(function() {
    $txt.hide().filter('.' + this.id).show();
})
.mouseleave(function () {
    $txt.hide();
});

Demo: http://jsfiddle.net/74FYW/1/

A: you can use this but it is not prefferable way
     $(".but > div").mouseenter(function() {
            var index=$('.but div').index(this);
            $('.txt:eq('+index+')').show();
        }).mouseleave(function () {
    $('.txt').hide();
});

A: thank you guys, but i found finally what I want.
the solution simply is to put the var line inside the jquery function not before it;
this is what I mean:
$(".but > div").each(function(){
  var butInfo = $(this).attr("id");
  $(this)
    .mouseenter(function(){
      $(".txt").hide();
      $(".txt."+butInfo).show();
    })
    .mouseleave(function(){
      $(".txt."+butInfo).hide();
    });
});

JSFiddle Demo:

A: if (this.value > '0') {
var ya1 = $('#' + this.value + 'yap1').val();
$('#yap1').val(ya1);


text:
Q: If-statement in a stream Is it possible to use an if statement conidition in my map below?
public Map<LocalDate, Double> avarageTemperatures(LocalDate dateFrom, LocalDate dateTo) {

    Map<LocalDate, Double> tempAverage = Data.stream()
            .collect(Collectors.groupingBy(Weather::getDateTime,
                    Collectors.averagingDouble(Weather::getTemp)));

    System.out.println("average: " + tempAverage);
    return tempAverage;
}

I want to only return the dates and tempAverage for dates between datefrom and dateTo, which is user input. So I would like to implement an if-statement like
for (Weather weather : Data){
    if(!weather.getDateTime().isAfter(dateTo) && !weather.getDateTime().isBefore(dateFrom)){}
}

where weatherData is an ArrayList containing dates and temperatures. My weather class:
public class Weather {
    private LocalDate dateTime;
    private LocalTime time;
    private double temperature;
    private String tag;
    //setter, getter, constructor
}

The dates are of the form 1946-01-15, and temperature of the form -0.3.

A: You can use filter():
weatherData.stream().filter(weather -> !weather.getDateTime().isAfter(dateTo) &&
                                    !weather.getDateTime().isBefore(dateFrom))...


text:
Q: Элемент из css в js Есть такая штука:
 ul.menu li a, ul.menu li span {
       ...........
         }

Мне нужно взять этот элемент в js, попробовал так:
    "document.getElementById('ul.menu li a').style.display ='none';" +
    "document.getElementById('ul.menu li span').style.display ='none';})()");

Не помогает, затем поробовал так:
"document.getElementsByTagName('ul').getElementById('menu').getElementsByTagName('li').getElementsByTagName('a').style.display ='none';" +
    "document.getElementsByTagName('ul').getElementById('menu').getElementsByTagName('li').getElementsByTagName('span').style.display ='none';})()");

Тоже никак. Так как мне взять этот элемент из css?
A: getElementById('menu') будет искать элемент с id="menu".
У тебя же есть только <ul class="menu"> Работать естественно не будет, т.к. требуемого элемента не находит.
A: Вы писали:

document.querySelector('.ul.menu li
span').style.display ='none';
если так делать, тоже ничего не
происходит

Попробуйте спану присвоить класс. И уберите точку у ul, это же тег у вас, а не класс.


text:
Q: SQL Agent Job runs OK on 2014, but not 2017 I just upgraded from SQL Server 2014 to 2017.  1 agent job that was running fine on 2014 is now throwing "failed to initialize sqlcmd library with error number -2147467259 error 22050".
I've made sure that the user that runs the SQL Agent service has sysadmin role, is a user in the database I'm reading and has datareader permissions on that database, but I'm still getting the error.
Additionally - the job history doesn't reflect the SQL Agent service user, but a computer account (that's not a login, by the way).  I have read that even though the job history reflects the computer account, it's probably being run by the user that's running the agent service.
I am at a loss.  I'm obviously missing some permission somewhere, but I don't know where.
Can anyone give me some guidance on this, please?
Thanks, in advance.


text:
Q: Two users with same name but different passwords Is it possible to create two users with the same name, and let LightDM choose between them at login if one of the passwords is given?
For example, to anyone opening my computer, it would seem like there is only one user.
If he would enter the right password, he would login to the "real" user, if he enters another pre-defined password he would login to the "dummy" account, and any other password would result in an error.
Is it possible?

A: This question provides some detail about the login sequence.
Authentication is handled by PAM (pluggable authentication modules). A brief search doesn't turn up any existing implementation of this idea (or at least, not one that is part of the standard Ubuntu set-up - I wouldn't be surprised if someone, somewhere had done it).
This message implies it would be possible to change the user during the authentication process, and one could presumably therefore write a PAM module which checked multiple passwords and switched the finally logged-in user appropriately. However, you'll need to do some pretty difficult development work yourself.
If your intention is to create a "hidden" user you'll need to do quite a lot more work to hide the existence of the hidden user beyond just playing with the login sequence - changing where their $HOME is stored, what goes in the auth log, hiding the fact that a system check would show the login sequence was modified, etc, etc.


text:
Q: Custom Django Template Tags not being loaded into Templates I have been searching the internet for quite some time for this one, but have not been able to fix my issue. I am trying to concatenate strings in one of my Django templates, and initially was using add as such...
{% with "http://127.0.0.1:8000/post/"|add:p.post_id|add:"/" as post_link %}
... used here ...
{% endwith %}

... but found that to be buggy and bad form. So I tried to create a custom template tag that would concatenate strings with the name addstr...
{% with "http://127.0.0.1:8000/post/"|addstr:p.post_id|addstr:"/" as post_link %}
... used here ...
{% endwith %}

... but am getting an "Error during Template Rendering, Invalid filter: 'addstr'" error when I do.
I created a templatetags directory in the correct spot with an init.py and cloud_extras.py inside of it. The contents of cloud_extras.py are:
from django import template

register = template.Library()

@register.filter
def addstr(arg1, arg2):
    """concatenate arg1 & arg2"""
    return str(arg1) + str(arg2)

I also have the app properly installed in settings.py and am loading the template in the view correctly (I know this is true because I have been working with this for a while now and decided to create links for the titles of posts)
Thank you so much for your time.

A: Do you have a {% load cloud_extras %} in the template before the call?
BTW, it looks like you probably want to look into other examples and the url tag because you probably don't want to use hardcoded links like that in the first place. Instead, try to find a way to generate the correct relative link given a post object.


text:
Q: 3D graphics pipeline That's what I understand about graphic pipeline (Opengl) so far, can someone confirm that?

*

*Object space: Object (geometry) specific coords;

*World space: rotate, translate and scale the object to world space;

*Eye space: Frustum that limits the world view, with a projection matrix that projects 3d
coord in a 2d plane (near plane?), scaling it when necessary and clipping it when its out of frustum/eye space

I've read that eye space reverses the Z axis, so, an original +z vertex turns backward from eye, why?

A: Nope. There are

*

*Local Space

→ Modelview Transform →

*

*Eye Space

→ Projection Transform →

*

*Clip Space

→ Homogenous Coordinate w-normalization →

*

*Normalized Coordinate Space

The modelview and projection transform are usually expressed by a matrix multiplication. There are no special requirements on the matrices used, but you normally want them to be non-singular. But between that anything goes. The usually found transformations are rotation-scalings + translation and shear-scalings + translation.

I've read that eye space reverses the Z axis, so, an original +z vertex turns backward from eye, why?

No, not really. I think you may maean negative z and w elements in the projection matrix. But that's only to get the depth ordering right. You could flip the sign of them just fine and reverse that effect by making certain adjustments to the depth range and depth test function. The negative sign there is just conventional to obtain a right-handed coordinate system with default settings, i.e. positive Z eye space coordinates come out of the screen.


text:
Q: Sumar numeros de un array Tengo el siguiente codigo

let a= [1,2,3,4]
let b= [5,6,7,8]
let c= [9,10,11,12]

let sumar= a+b+c

console.log(sumar)

Y necesito sumarlos todos, por decir:  1+2+3+4+5+6+.. etc. El caso es que pueden ser mas de 3 arrays (Coloque 3 para el ejemplo) por lo cual no me sirve utilizar la funcion concat()
El probado colocar

let sumar = a+b+c

Pero me devuelve 1,2,3,45,6.. tipo Stirng y no puedo usar un foreach o map, porque no me lo devuelve como arreglo. Y si transformo la variable sumar (String) a Arreglo usando let arreglo = [...d] Me agrega las comas.
Como se puede resolver?

A: let a= [1,2,3,4]
let b= [5,6,7,8]
let c= [9,10,11,12]

let todosJuntos = [...a,...b,...c]

todosJuntos.reduce((a,b)=>a+b,0)

Primero uno todos los elementos con spread operator en un único array, luego sumo todos los elementos del array resultante con reduce.
El todosJuntos.reduce podrías depositarlo en una variable para usar el resultado o poner directamente el código donde lo necesites.
Depositar en una variable para usarlo luego me refiero a algo ej:
const resultado = todosJuntos.reduce((a,b)=>a+b,0)

Y luego utilizarlo para mostrar o setear algo, ej:
console.log(resultado)

Agrego otra forma basada en parametros rest..
const sumar = (...args) => {
let todosJuntos = []
for(arg of args){
todosJuntos = [...todosJuntos, ...arg]
}
return todosJuntos.reduce((prev, current)=>prev + current, 0)
}

sumar([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12])

Eliminé el primer reduce que lo único que hace es poner en el current del primer reduce el array que se está recorriendo, luego el segundo hace la suma de cada uno de sus elementos, y este proceso se repite tantas veces como arrays existan en args. En este ejemplo, recorro args con un forof y por cada array voy armando el array todosJuntos con todos los valores de todos los arrays, finalmente retorno el resultado de un único reduce sobre el array todosJuntos.

A: Si bien las respuestas que te han proporcionado funcionan, el tema es que no solucionan uno de los problemas principales, el cuál es que puede ser uno, dos, tres, cuatro, n cantidad de arrays, lo cual con las soluciones ya propuestas tendrías que modificar el código una y otra vez. Para esto puedes apoyarte de los parámetros rest:

La sintaxis de los parámetros rest nos permiten representar un número indefinido de argumentos como un array.

De hecho si miras el ejemplo que muestran para los parámetros rest, podrás darte cuenta de que la solución se aproxima mucho a lo que quieres lograr, con la excepción de que en tu problema, cada elemento no es un número, si no que es otro array. Por lo cual basta con anidar otro .reduce() para realizar la suma, y agregar la inicialización en 0. Con esto sumarás cada elemento de cada array.

const sumar = (...args) => {
  return args.reduce((prev, current) => {
    return prev + current.reduce((prev, current) => {
      return prev + current;
    }, 0);
  }, 0);
}

console.log(sumar([1], [2], [3]));
console.log(sumar([1, 2, 3], [4, 5, 6], [7, 8, 9]));
console.log(sumar([1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]));

Claro, este ejemplo asume el happy path, así que tienes que asegurarte de verificar que los arrays no estén vacíos, contengan elementos válidos, etc.

A: Ésta es otra opción, se deben añadir todos los array en uno sólo y recorrerlos como se muestra.
let a= [1,2,3,4]
let b= [5,6,7,8]
let c= [9,10,11,12]
let todosArrays = [a,b,c];
let total = 0;

todosArrays.forEach(function(el){
el.forEach(function(n){
  total += n;
})
});
console.log(total);

A: Cos mo adición a las respuestas anteriores. Suponiendo que recibas x cantidad de arreglos con x cantidad de valores.

let contenedorDeArreglos = []

//TL;DR
function generardorDeArreglos() {

  let numeroAlAzar = Math.round(Math.random() * 100) + 1
  let numeroDeArreglosAlAzar = Math.round(Math.random() * 20) + 1

  contenedorDeArreglos = [...new Array(numeroDeArreglosAlAzar).keys()]
    .map(x => [...new Array(numeroAlAzar).keys()].map(x => Math.round(Math.random() * 100)))

}

generardorDeArreglos()

//La magia esta en este contenedor de arreglos.
let suma = contenedorDeArreglos.reduce((acumulador, nuevoValor) => {
  //Al valor acumulado, sumamos el total del arreglo actual.
  return acumulador + nuevoValor.reduce((acu, nuevo) => acu + nuevo, 0)
}, 0)

console.log("Arreglos generados: ", contenedorDeArreglos.length)
console.log("Total de suma: ", suma)
console.log("Arreglos:")
contenedorDeArreglos.forEach(x => console.log(x))


text:
Q: How to serialize Color property as ARGB values? I'm working with Windows Forms designer. It serializes properties of type Color as known name whenever possible. I need it to serialize such properties always as RGB, because I need it later for interop with other system, which can deserialize only from RGB values.
Is there a way to serialize Color properties always as RGB values?

A: Here's how I solved a similar problem.  Hope it helps.
  <System.Xml.Serialization.XmlIgnore()> _
  Public Property LineColor() As Color
     Get
        Return mLineColor
     End Get
     Set(ByVal value As Color)
        mLineColor = value
     End Set
  End Property

  Public Property LineColorArgbString() As String
     Get
        Return ColorAsString(mLineColor)
     End Get
     Set(ByVal value As String)
        mLineColor = ParseColorArgbString(value)
     End Set
  End Property


text:
Q: Probability Theory: On weak convergence of distribution functions. On the top of page 97 in Durrett's text on Probability, it says that a sequence of distribution functions $F_n$ converges weakly to some limit function $F$ if it converges to $F$ for all continuity points of $F$.
I am trying to make sense out of Durrett's comment: To see that convergence at continuity points is enough to identify the limit, observe that $F$ is right continuous and by Exercise 1.2.3, the discontinuities of $F$ are at most a countable set.
What is the point of his comment here?  Why is he talking about the set of discontinuities being countable? Why is that relevant? I agree with him that this is true (this is because $F$ is nondecreasing) but who cares?
The only thing I have proven (fairly trivial) is that $F$ must be nondecreasing when restricted to its continuity points. (This follows directly from it being the pointwise limit of nondecreasing functions.)
Can you shed any light on this?

A: Let it be so that $F,F_{1},F_{2},\ldots$ are distribution functions
and denote $C:=\left\{ x\in\mathbb{R}\mid F\text{ continuous at }x\right\} $.
Assume that $F_{n}\left(x\right)$ converges to $F\left(x\right)$
for any $x\in C$. Then $F\left(x\right)$ is determined for every
$x\in C$. However, what we want is that $F\left(x\right)$ is determined
for every $x\in\mathbb{R}$. For every $x\in\mathbb{R}$ we can find
a sequence $\left(x_{k}\right)$ in $C$ with $x_{k}\geq x$ and $\lim_{k\rightarrow\infty}x_{k}=x$.
The fact that such a sequence exists is a consequence of the fact
that $\mathbb{R}-C$ is countable. Since $F$ as a distribution function
is right-continuous we now have $F\left(x\right)=\lim_{k\rightarrow\infty}F\left(x_{k}\right)$.
Here the $F\left(x_{k}\right)$ are determined because $x_{k}\in C$
so automatically the $F\left(x\right)$ is determined. In special
case $x\in C$ you can take $x_{k}=x$ for every $k$.


text:
Q: FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app) when enable web flutter I have using firebase for project flutter of me. but when I want build web not work
step1: I run
flutter config --enable-web

step2: I run
flutter run -d chrome

and after appear error bellow
TypeError: Cannot read property 'app' of undefined
at Object.app$ [as app] (http://localhost:63143/packages/firebase_core_web/src/interop/core.dart.lib.js:48:101)
at new cloud_firestore_web.FirebaseFirestoreWeb.new
(http://localhost:63143/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:873:64)
at Function.registerWith (http://localhost:63143/packages/cloud_firestore_web/src/write_batch_web.dart.lib.js:755:73)
at Object.registerPlugins (http://localhost:63143/packages/doxaspc/generated_plugin_registrant.dart.lib.js:34:46)
at main (http://localhost:63143/web_entrypoint.dart.lib.js:44:35)
at main.next (<anonymous>)
at runBody (http://localhost:63143/dart_sdk.js:39052:34)
at Object._async [as async] (http://localhost:63143/dart_sdk.js:39083:7)
at main$ (http://localhost:63143/web_entrypoint.dart.lib.js:43:18)
at http://localhost:63143/main_module.bootstrap.js:19:10
at Array.forEach (<anonymous>)
at window.$dartRunMain (http://localhost:63143/main_module.bootstrap.js:18:32)
at <anonymous>:1:8
at Object.runMain (http://localhost:63143/dwds/src/injected/client.js:8656:21)
at http://localhost:63143/dwds/src/injected/client.js:22068:19
at _wrapJsFunctionForAsync_closure.$protected (http://localhost:63143/dwds/src/injected/client.js:3830:15)
at _wrapJsFunctionForAsync_closure.call$2 (http://localhost:63143/dwds/src/injected/client.js:10905:12)
at Object._asyncStartSync (http://localhost:63143/dwds/src/injected/client.js:3794:20)
...

file index.html of me
<!DOCTYPE html>
<html>
<head>
<base href="/">
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="A new Flutter project.">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="doxaspc">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="icon" type="image/png" href="favicon.png"/>
<link rel="manifest" href="manifest.json">
</head>
<body>
    <!-- Firebase Setup -->
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.8.0/firebase-firestore.js"></script>
<script>
  var firebaseConfig = {
    apiKey: "AIzaSyD3kioPzFSkD6xXndI9fkguKhj0Qadb304",
    authDomain: "fir-d71eb.firebaseapp.com",
    projectId: "fir-d71eb",
    storageBucket: "fir-d71eb.appspot.com",
    messagingSenderId: "983518157786",
    appId: "1:983518157786:web:b8db1e8f8806292de97ee3",
    measurementId: "G-Z2Q69GT9WB"
  };
  firebase.initializeApp(firebaseConfig);
</script>
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('flutter-first-frame', function () {
      navigator.serviceWorker.register('flutter_service_worker.js');
    });
  }
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>

I want enable web from project app flutter of me but I dont know I miss step?
please show me how ?
please help me

A: If you are using Flutter Web with Firebase make sure you have the SDKs installed in the body tag of your ./web/index.html
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.9/firebase-analytics.js"></script>

Furthermore, make sure you call firebase.initializeApp(...) with the configuration parameters in the index.html as well.
<script>
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    var firebaseConfig = {
      apiKey: "AIz...",
      authDomain: "...",
      databaseURL: "https://<project-name>.firebaseio.com",
      projectId: "...",
      storageBucket: "<project-name>.appspot.com",
      messagingSenderId: "...",
      appId: "...",
      measurementId: "..."
    };
    firebase.initializeApp(firebaseConfig);
    firebase.analytics();
  </script>

At last configure firebase
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}


text:
Q: How can I use the child selectors here? Please refer to the posted image. I want to add a margin-left on the first image and then in the rest of image I don't want them. Can I use the child selectors to achieve this or there is any other way?
Can I make the images, overflow: scroll like we do in case of text? As I don't know jquery/javascript as of now.

* {
 box-sizing: border-box;
}

body {
 background:gray;

 /*border: 2px solid yellow;*/
}

.wrapper {
 width: 93%;
 height: auto;
 margin: auto;
}

.headwrap {

 padding-top: 70px;
}

.logo {
 margin: 0;
 float: left;
}

.socialbuttons {
 float: right;

}

.socialbuttons ul {
 list-style: none;
 float: right;

}

.socialbuttons ul li {
 float: left;
 width:50px;
 height:50px;
 padding:0;
 margin-right: 30px;
 background: #000;
 border-radius:30px;
}
.socialbuttons ul li img{
 margin-left:20px;
 margin-top:20px;
}

.navbar {
 margin-top: 40px;
 width: 100%;
 background: #db3636;
 float: left; /* this and see changes */
}

.navbar ul {
 list-style: none;
 margin: 0;
 padding: 0 5px; /* the 0 helps with making the borders span full height of navbar*/
 /* float producing wrong results */
}

.navbar ul li {
 float: left;  /* height of menu bar increases when float is defined */
 display: inline; /* does it have any use ? */
 padding: 25px 10px;
 border-right: 1px solid black;
 border-left: 1px solid black;
 color: white;
 font-size: 14px;
 font-weight: bold;
 font-family: sans-serif;
 text-align: center;
 width: 15%;
}

.navbar ul li:first-child {
 border-left: none;
}

.navbar ul li:last-child {
 border-right: none;
}

.clearfix {
 *zoom: 1;
}

.clearfix:before,
.clearfix:after {
 display: table;
 content: "";
 line-height: 0;
}

.clearfix:after {
 clear: both;
}

.slider img {
 float:left;
 width:100%;
}
.text{
 color:white;
 margin-top:-35%;
 float:left;
 margin-left: 80px;
 font-weight: bold;
 font-family: Helvetica, Arial, Sans-Serif;
 font-size : 50px;
 line-height: .5;
}

#project {
 background-color: #555653;
 width: 100%;
 margin-top: 10px;
 float: left;
}

.head {
 float: left;
 background-color: #1D1D1C;
 width: 100%;
}

.head h3 {
 color: white;
 font-family: Arial , sans-serif;
 font-weight: lighter;
 margin-left: 20px;
}

.imgContainer img {
 margin-top: 20px;
 padding-left: 40px
}
<!DOCTYPE html>

<title>Industrial Website demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial scale=1.0">
<link href="damion.css" rel="stylesheet" type="text/css">

ABOUT US

GALLERY

EVENTS

BLOG

CONTACTS

<input type="text" style="background:black; height:30px; width:90%;  margin:20px 0 0 20px; border:0;  border-radius:10px;">

WE ARE PROFESSIONAL,
COMPETITIVE AND COMPETENT

FEATURED PROJECTS

A: Use :first-child selector for this:
.imgContainer img:first-child{
       margin-left:10px;
    }

A: You can easily achieve this using this css
.imageContainer img:first-child
 {
   margin-left:20px;
 }

A: You can select the first child with any of the given selectors below:
.imgContainer img:first-of-type
.imgContainer img:first-child
.imgContainer img:nth-child(1)

If you want to set some sort of overflow to your images, you'll need to wrap them in another element, like a generic div and set your overflow rules to this element, standard overflow rules won't apply directly to img elements.
See CSS Tricks - overflow


text:
Q: Photoshop scripting - Magic Eraser Tool I'm trying to make a photoshop (.jsx) script that doeas the following.
Open files from folder
For each file in folder
Take Magic Eraser Tool
Click on the edge of the document (document width -1, document height -1)
Save for web as PNG

I am able to do everything except click on the edge of the document to erase the background.. How do I do that?
I am now able to open an image and select the Magic Eraser Tool but I can't manipulate the mouse click on the edge so it would go transparent.
All images have a white frame so it's ok for me to click on the edge.
Any suggestions?
Thank you for your time!
// EDIT:
How do I set the tolerance on the selected tool?
Andrej

A: There are limitations to scripting tools in PS. In scripting if you set the magic eraser to imagewidth-1, imageheight -1 you'll get an error.
// =======================================================
var id16821 = charIDToTypeID( "Fl  " );
var desc3348 = new ActionDescriptor();
var id16822 = charIDToTypeID( "From" );
var desc3349 = new ActionDescriptor();
var id16823 = charIDToTypeID( "Hrzn" );
var id16824 = charIDToTypeID( "#Pxl" );
desc3349.putUnitDouble( id16823, id16824, 0.0 ); //x
var id16825 = charIDToTypeID( "Vrtc" );
var id16826 = charIDToTypeID( "#Pxl" );
desc3349.putUnitDouble( id16825, id16826, 0.0 ); //y
var id16827 = charIDToTypeID( "Pnt " );
desc3348.putObject( id16822, id16827, desc3349 );
var id16828 = charIDToTypeID( "Tlrn" );
desc3348.putInteger( id16828, 32 ); //tolerance
var id16829 = charIDToTypeID( "AntA" ); //Antialias
desc3348.putBoolean( id16829, true );
var id16830 = charIDToTypeID( "Usng" );
var id16831 = charIDToTypeID( "FlCn" );
var id16832 = charIDToTypeID( "BckC" );
desc3348.putEnumerated( id16830, id16831, id16832 );
var id16833 = charIDToTypeID( "Md  " );
var id16834 = charIDToTypeID( "BlnM" );
var id16835 = charIDToTypeID( "Clar" );
desc3348.putEnumerated( id16833, id16834, id16835 );
//var id16872 = charIDToTypeID( "Cntg" );
//desc3355.putBoolean( id16872, false ); Contiguous set to false
executeAction( id16821, desc3348, DialogModes.NO );

Are you just trying to remove the background layer?


text:
Q: I am trying to count the occurrences of name of actor/actress but not including the current year into a new column star_value Dataframe looks like this:
what dataframe looks like
For example for actor Adam Driver the column will look like this after the function is called.
What I am trying to get- with new star_value column
I am only able to print out list for each row but I don't know how to iterate through each row based on index for name and index on year to count.
star= star_df.loc[:, ['name', 'year_film']]
star_lst = []
count = 0

for i in range(len(star)):
    stars = [star.loc[i, 'name'], star.loc[i, 'year_film']]
    for stars[1] in stars[i]:
        if stars[0] in stars[i]:
            count += 1
        else:
            count == 1
#return count

print(count)

A: for x in df.index:

if stars[0] in stars[x]:
    count += 1
else:
    count == 1

more on index selecting at pandas documentation


text:
Q: Faulty PNP Transistor switch fix...what is causing the noise on the base? I built a ham radio amplifier kit that takes about 5 watts drive and makes 70 watts.  It is called a MiniPA70.
Here is a website someone put together describing its build/use.
http://pa-11019.blogspot.com/2016/11/diy-kits-70w-ssb-linear-hf-power.html
I have been having problems with it and am trying to understand its flaws... there are a few.
Take a look at the switch shown below.  The idea is that when the PTT jumper is grounded, the PNP transistor switch's on and delivers power.  Sometimes this works and sometimes this does not.  I am trying to fix its issues....
Using an oscilloscope, I have looked at the noise present as Peak to Peak variations at various points around the transistor.  I note that either with the PTT switched activated or the PTT switch deactivated, the noise on the Emitter is negligible.  The noise on the base is not.
When the PTT switch is activated (grounded), the noise on the base is minimal.  When the PTT switch is left floating (deactivated), there is substantial noise on the base.  Much more than on the emitter.  It is this noise, that switches on the transistor erroneously.  Why are there different amounts of noise on the emitter and base and why is it a function of of weather the base has a path to ground?
I also looked at the noise on the ground point and it is also minimal.
I am wondering if the transistors I have been using are flawed or the resistors are bad?  What process cause there to be more noise post resistor than pre resistor when the resistor is floating in space and that noise to disappear when it is grounded/forms a divider.
Thanks for any insight. I have to redesign this to make it work properly, but that said, there are a number of kits floating around with this faulty design.


text:
Q: How do I pass resources that were created by Terraform to Kustomize Am using a combination of these tools

*

*Terraform - To deploy the Application specific AWS resources I need
(For instance a secret)

*Skaffold - To help with the inner
development loop, surrounding the deployment of K8s resources to
local and remote cluster

*Kustomize - To help with templating of
different configurations for different environment

My github action steps are as follows

*

*Terraform to create the AWS resources. At this point it creates a AWS
secrets arn.

*Skaffold to deploy the k8s manifests. Skaffold in-turn delegates K8s manifest generation to Kustomize. Within the Kustomize overlay files i need to be able to access the Secrets arn that was created earlier, this arn needs to be injected into the container that is being deployed. How do I achieve this?

Rephrasing the question: How do I pass resources that were created by terraform to be consumed by something like Kustomize (Which is used by skaffold)
(p.s, I really like the choice of my tools thus far as each one excels at one thing. I realize that terraform can possibly do all of it, but that is a choice that I dont want to make unless there are no easier options)

A: Here is what I have learnt:
I don't think there are any industry standards in terms of how to share this data between the tools across different steps within github actions. That being said here are some of the options

*

*Have the Terraform store the secrets arn in a parameter store. Retrieve the arn from the parameter store in later steps. This means that the steps have to share a static key

*Have Terraform update the kustomize files directly (or use kustomize_overlays as datasource)

There could be other similar approaches, but none of these tools have a native way of passing/sharing data


text:
Q: Adding deep learning model at django
ml: django app folder
test: pytorch python code folder --predict.py(model)
And I wanted to use procees function that i made at predcit.py at views.py
process function
def process():
for img_file in os.listdir('C:\\Users\\user\\Desktop\\model\\project\\ml\\test\\images'):

    img_path = os.path.join('images', img_file)

    predition = predict_breed_transfer(model, img_path)
    print(predition)
    print("image_file_name: {0}, \t predition breed: {1}\n\n".format(img_path, predition))

return (predition)

views.py at ml folder
from django.shortcuts import render
from .test.predict import *

def predict(request):
    pred=process()

    return render(request, "predict.html",{'pred':pred})

When i run the server at my local computer, it gets pred as none.
I don't understand why views.py doesn't run 'predict_breed_transfer'function...


text:
Q: Add a value to a pre-existing key in a dictionary? I'm trying to add a third value to existing dictionary keys in Python. I'm sure this is probably easy, but I'm fairly new to coding so each way I've tried has thrown an error. Below is an example of what I tried which resulted in a syntax error. I also tried making the colon an equal sign but I got the message can't assign to a literal which I figure is due to the presence of two different = in the same line of code.
student = [
        { "name": "Kellie", "student_id": 12345},
        { "name": "James", "student_id": 39875},
        { "name": "Katie", "student_id": 24680},
        ]

student[0] = "lastName" : "Vee"
student[1] = "lastName" : "Tee"
student[2] = "lastName" : "Zee"

A: Try to add element like this:
student[0]["grade"] = "1"

It will add here: { "name": "Kellie", "student_id": 12345} new key "grade" and asign the value of 1.


text:
Q: Uncaught SyntaxError Unexpected token ] Estoy intentando crear un bucle que crea un determinado números de objetos, pero no se como hacer para que en cada vuelta var per[i] se ha diferente y me da los errores de abajo he probado y nada, me gustaría saber si se puede crear objetos de una forma parecida con bucles

class estudiante{
    constructor(name,edad,colegio,ciudad){
        this.name = name;
        this.edad = edad;
        this.colegio = colegio;
        this.ciudad = ciudad;
    }
}

var cant = Number(prompt("ingrese la cantidad de estudiantes:"));
for(let i = 0; i < cant; i++){
    var name = prompt("name del estudiante! ");
    var edad = Number(prompt("edad!"));
    var colegio = prompt("colegio! ");
    var ciudad = prompt("ciudad! ");
    var per_[i] = new estudiante(name,edad,colegio,ciudad);
}

// var per_2 = new estudiante(name,edad,colegio,ciudad);
// var per_3 = new estudiante(name,edad,colegio,ciudad);

console.log(`hola ${per_0}`)

Error en la consola de chrome

A: Código propuesto:

    class estudiante{
        constructor(name,edad,colegio,ciudad){
            this.name = name;
            this.edad = edad;
            this.colegio = colegio;
            this.ciudad = ciudad;
        }
    }

    let cant = Number(prompt("ingrese la cantidad de estudiantes:"));
    let per = [];
    let name = '';
    let edad = 0;
    let colegio = '';
    let ciudad = '';
    for(let i = 0; i < cant; i++){
        name = prompt("name del estudiante! ");
        edad = Number(prompt("edad!"));
        colegio = prompt("colegio! ");
        ciudad = prompt("ciudad! ");
        per.push(new estudiante(name,edad,colegio,ciudad));
    }

    console.log(`hola ${per[1].name}`)

Comentarios:
Me es confusa esta sintaxis: per_[i]
Considera que esto:
 var per_[i] = new estudiante(name,edad,colegio,ciudad);

Dentro del ciclo solo te almacenaría la última instancia creada (en el momento que el código funcionara)
Por lo tanto esta sintaxis es errónea desde el momento que per solo estaría almacenando un objeto, además de que el acceso al ìndice tampoco luce adecuado:
console.log(`hola ${per_0}`)

Incluso si lo modificamos por algo como esto:
per[0].clave

Nos debería indicar que esa clave no esta definida
Comentarios finales:

*

*Las variables las declararía por fuera del ciclo, para que no se estén generando por cada iteración

*Tu variable per yo la declararía como un array vacío (posterior veremos por que)

*Por dentro del ciclo a cada variable le asignas valores

*Haces un push al array vacio agregando cada instancia generada con los argumentos deseados

*Finalmente por fuera del ciclo puedes imprimir el contenido indicando el índice del objeto y la propiedad que deseas

A: El problema es el nombre de la variable, no puedes asignar i dentro de la variable, lo que puedes hacer es guardar variable en window para exportarla de manera global, de manera que podemos asignarle un nombre dinámico a la variable

class estudiante{
    constructor(name,edad,colegio,ciudad){
        this.name = name;
        this.edad = edad;
        this.colegio = colegio;
        this.ciudad = ciudad;
    }
}

var cant = Number(prompt("ingrese la cantidad de estudiantes:"));
for(let i = 0; i < cant; i++){
    var name = prompt("name del estudiante! ");
    var edad = Number(prompt("edad!"));
    var colegio = prompt("colegio! ");
    var ciudad = prompt("ciudad! ");
    window[`per_${i}`] = new estudiante(name,edad,colegio,ciudad);
}

// var per_2 = new estudiante(name,edad,colegio,ciudad);
// var per_3 = new estudiante(name,edad,colegio,ciudad);

console.log(`hola ${per_0.name}`)

Lo que está haciendo el intérprete de JS, es  guardar la variable así
per_[i]

La variable i no va a ser parte del nombre de la variable, por ende se aplican las reglas para el nombre de una variable

*

*No empieza con números

*Es alfanumérico

Y los signos [] no son alfanuméricos, por eso está dando un error


text:
Q: Updating the page number with OpenXML inside the page content (not in header) I have a Word document with the page number inside of the header. I update this document through OpenXML by adding new content. After that, when I open this document the page number is correctly (automatically) updated.
But now, I need to have this page number not inside the header but inside the page content. In this case the page number is not correctly (automatically) updated.
How to have this page number automatically updated ? Any ideas ?
PS: I already try this code without luck:
        DocumentSettingsPart settingsPart = mainPart.GetPartsOfType<DocumentSettingsPart>().First();
        //Create object to update fields on open
        UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen();
        updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true);
        // Insert object into settings part.
        settingsPart.Settings.PrependChild<UpdateFieldsOnOpen>(updateFields);
        settingsPart.Settings.Save();


text:
Q: SwitchCompat onClickListener called for every button in group I am creating a ListView of switches, dynamically populated from the DB. I need to verify that at least one of them is chosen, and enable / disable a continue button. I am storing the values of the switches in a HashMap so that I can easily check if it contains a true value.
The switches are created in a CursorAdapter, and I have tried both setting an OnClickListener and OnCheckedChangeListener. It seems with both, that when an item is clicked, the listener fires for every button in the list, and the values I am storing in a HashMap are then being overwritten with the checked state of a button further down the list.
class LanguageInstallAdapter extends CursorAdapter {

    private final String LOG_TAG = LanguageInstallAdapter.class.getSimpleName();
    public HashMap<String,Boolean> mDBValues = new HashMap<String,Boolean>(); //original DB values
    public HashMap<String,Boolean> mChangedValues = new HashMap<String,Boolean>();//anything changed
    private HashMap<String,Boolean> mAllCurrentValues= new HashMap<String,Boolean>(); //complete current
    private View mRootView;

    public static class ViewHolder {
        public final TextView nameView;
        public final SwitchCompat installSwitch;

        public ViewHolder(View view) {
            nameView = (TextView) view.findViewById(R.id.language_textview);
            installSwitch = (SwitchCompat) view.findViewById(R.id.installed_switch);
        }
    }

    public LanguageInstallAdapter(Context context, Cursor c, int flags, View root) {
        super(context, c, flags);
        mRootView = root;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item_install_language, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        view.setTag(viewHolder);
        return view;
    }

    @Override
    public void bindView(View view, final Context context, final Cursor cursor) {
        ViewHolder viewHolder = (ViewHolder) view.getTag();
        String languageId = cursor.getString(LanguageInstallFragment.COL_ID);
        String name = cursor.getString(LanguageInstallFragment.COL_NAME);
        boolean langInstalled = cursor.getInt(LanguageInstallFragment.COL_INSTALLED)>0; //convert DB 1 or 0 to java boolean
        mDBValues.put(languageId, langInstalled);
        mAllCurrentValues.put(languageId, langInstalled);
        viewHolder.nameView.setText(name);
        viewHolder.installSwitch.setChecked(langInstalled);
        viewHolder.installSwitch.setTag(languageId);
        viewHolder.installSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CompoundButton button = (CompoundButton) v;
                String buttonLang= (String) button.getTag();
                mChangedValues.put(buttonLang, button.isChecked());
                mAllCurrentValues.put(buttonLang, button.isChecked());
                setSubmitButton();
            }
        });
    }

    public void setSubmitButton(){

        for (Map.Entry<String,Boolean> entry : mAllCurrentValues.entrySet()) {
            Log.d(LOG_TAG, "Hashmap: " + entry.getKey() + " " + entry.getValue());
        }

        if(mAllCurrentValues.containsValue(true)) {
            mRootView.findViewById(R.id.submit_button).setEnabled(true);
            mRootView.findViewById(R.id.lang_prompt).setVisibility(View.GONE);
        } else {
            mRootView.findViewById(R.id.submit_button).setEnabled(false);
            mRootView.findViewById(R.id.lang_prompt).setVisibility(View.VISIBLE);
        }
    }
}

Log output from a sequence of selections:
Initial state (none selected)
09-07 20:21:29.445  ﹕ Hashmap: 4 false
09-07 20:21:29.445  ﹕ Hashmap: 2 false
09-07 20:21:29.445  ﹕ Hashmap: 3 false

Select 2 (1 selected)
09-07 20:22:42.096  ﹕ Hashmap: 4 false
09-07 20:22:42.096  ﹕ Hashmap: 2 true
09-07 20:22:42.096  ﹕ Hashmap: 3 false

Select 3 (2 selected)
09-07 20:23:28.192  ﹕ Hashmap: 4 false
09-07 20:23:28.192  ﹕ Hashmap: 2 false
09-07 20:23:28.192  ﹕ Hashmap: 3 true

Select 4 (3 selected)
09-07 20:23:43.608  ﹕ Hashmap: 4 true
09-07 20:23:43.608  ﹕ Hashmap: 2 false
09-07 20:23:43.608  ﹕ Hashmap: 3 true

Unselect 2 (2 selected)
09-07 20:23:58.507  ﹕ Hashmap: 4 true
09-07 20:23:58.507  ﹕ Hashmap: 2 false
09-07 20:23:58.507  ﹕ Hashmap: 3 false

Unselect 3 (1 selected)
09-07 20:24:13.942  ﹕ Hashmap: 4 false
09-07 20:24:13.942  ﹕ Hashmap: 2 false
09-07 20:24:13.942  ﹕ Hashmap: 3 false

Is there a way to not call the listener on every button? Even with the call for each button, why is the value being overwritten incorrectly? Shouldn't the call for each button still be getting the languageId and isChecked value for that button, and not overwriting a different one? Is there a better way to be doing this?

A: replace this line
mAllCurrentValues.put(languageId, langInstalled);

with
if (mAllCurrentValues.contains(languageId)) {
    langInstalled = mAllCurrentValues.get(languageId);
} else {
    mAllCurrentValues.put(languageId, langInstalled);
}


text:
Q: Select latest date     SELECT
    distinct

        HRM_Employee.EmployeeId EmployeeXId,
      ([HRM_Employee].[FirstName] +' '+ISNULL([HRM_Employee].[MiddleName],' ')+' '+ISNULL([HRM_Employee].[LastName],' ')) AS FirstName
     -- ,[FirstName]
          ,[HRM_Employee].[MiddleName]
          ,[HRM_Employee].[LastName]
          ,[HRM_Employee].[Code]
          ,[HRM_Employee].[UserName]
          ,[HRM_Employee].[Password]
          ,[HRM_Employee].[DateOfBirth]
          ,[HRM_Employee].[OriginalBirthDate]
          ,[HRM_Employee].[Gender]
          ,[HRM_Employee].[BloodGroup]
          ,[HRM_Employee].[Height]
          ,[HRM_Employee].[MaritalStatus]
          ,[HRM_Employee].[DateOfMarriage]
          ,[HRM_Employee].[IdentificationMark1]
          ,[HRM_Employee].[IdentificationMark2]
          ,[HRM_Employee].[Religion]
          ,(SELECT [A].[FirstName] +' '+  [A].[MiddleName] +' '+ [A].[LastName]
              FROM [dbo].[HRM_Employee] [A] WHERE [A].EmployeeId = [HRM_Transfer].[ReportingOfficerXId]
           ) [PersonInCharge]
          ,[HRM_Department].[Name] [DepartmentName]
          ,[HRM_Branch].[Name] [BranchName]
          ,[HRM_Division].[Name] [DivisionName]
          ,[HRM_Designation].[Name] [DesignationName]
          ,HRM_Transfer.TransferDate
    from HRM_Employee
    LEFT join [dbo].[HRM_Division]
            ON [HRM_Employee].DivisionXId  = [HRM_Division].DivisionId
            JOIN [dbo].[HRM_Designation]
            ON [HRM_Employee].DesignationXId = [HRM_Designation].DesignationId
            JOIN [HRM_Department]
            ON [HRM_Employee].[DepartmentXId] = [HRM_Department].[DepartmentId]
            JOIN [HRM_Branch]
            ON [HRM_Employee].[BranchXId] = [HRM_Branch].[BranchId]
            INNER JOIN HRM_Transfer
            ON HRM_Transfer.EmployeeXId=HRM_Employee.EmployeeId
    WHERE
        Convert(varchar(11),HRM_Transfer.TransferDate,103) <=Convert(varchar(11), getdate(),103)
END

When I excecute this i got the output as follows
EmployeeXId    FirstName               TransferDate
34             Ambarish   V               2012-08-09 00:00:00.000
54             Anil  N P                      2012-08-09 00:00:00.000
55         Ann  Rose Abraham              2012-08-08 00:00:00.000
55         Ann  Rose Abraham              2012-08-09 00:00:00.000
74             Anees  M S                     2012-08-09 00:00:00.000

From this I want to display data with latest Transfer date only. That is in EmployeeId 55 I need to display data with Transfer date 2012-08-09 00:00:00.000 only. What modification is I want to do in above SP to get required answer?. Please help me to solve this.

A: Group by EmployeeXId and select MAX(TransferDate).


text:
Q: Material OutlinedBox hint with androidx I am referring this: Outlined Edit Text from Material Design where the answer relates to the outdated support libraries rather than androidx.
How to achieve creating the OutlinedBox with the hint on the top left frame rather than inside the box?   Have spent the entire morning unsuccessful. What I want is this:

My graddle:
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'

My app Theme:
style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"

My layout:
<com.google.android.material.textfield.TextInputLayout
                android:id="@+id/textField"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                android:hint="Full name" >

                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    />
            </com.google.android.material.textfield.TextInputLayout>

My result (the frame is continuous, without the hint embedded in the top left corner):

A:         <com.google.android.material.textfield.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/etProposalTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/medium"
                android:hint="Title."
                android:inputType="text"
                android:textSize="18sp" />
        </com.google.android.material.textfield.TextInputLayout>

A: Try below code:
<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/etlFirst"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            app:hintTextColor="@color/colorPrimary"
            android:focusable="true"
            android:hint="Label">
            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/etFirst"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColorHint="@color/colorAccent"
                android:hint="PlaceHolder"/>
        </com.google.android.material.textfield.TextInputLayout>

To displaying two hints try below code in .java file:
etFirst.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                etFirst.setHint("Place Holder");

            } else {
                etFirst.setHint("Label");
            }
        }
    });

Output for above code is:

I hope this helps you

A: If you want to display at the same time the hint label on top left and a placeholder text inside the EditText you can use:

*

*app:placeholderText: to add a placeholder text in the EditText

*android:hint: to add a floating label

They can work together:
<com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:hint="Label"
        app:placeholderText="Placeholder Text"

Note: it requires at least the version 1.2.0-alpha03.


text:
Q: Pass request model inside of a parameter I am trying to pass a model that I send to an API inside on a parameter but get an error stating:

Type 'string' is not assignable to type 'AVAFModel'.

submitAvafDetails(): Observable<any> {
  this.avafBcmsVo = 'avafVO:{' + this.prepareAvafSubmitData() +'}';
  return this.httpService.processData('POST', CONSTANTS.API_URL + 'testService.exp', this.avafBcmsVo);
}

The error happens on this line:
this.avafBcmsVo = 'avafVO:{' + this.prepareAvafSubmitData() +'}';

Here is my model:
export interface AVAFModel {
  bankingDetails: BankingDetails;
  digitalAcquisitionsConsent: DigitalAcquisitionsConsent;
  employmentDetails: EmploymentDetails;
  financeDetails: FinanceDetails;
  incomeAndExpenseDetails: IncomeAndExpenseDetails;
  personalAddressDetails: PersonalAddressDetails;
  personalDetails: PersonalDetails;
  vehicleAssetDetails: VehicleAssetDetails;
  preQualifiedCustomer: boolean | true;
}

prepareAvafSubmitData() {
  const avafBcmsRequestObj: AVAFModel = {
    bankingDetails: bankingDetailsVoModel,
    digitalAcquisitionsConsent: digitalAcquisitionsConsentVoModel,
    employmentDetails: employmentDetailsVoModel,
    financeDetails: financeDetailsVoModel,
    incomeAndExpenseDetails: incomeAndExpenseDetailsVoModel,
    personalAddressDetails: personalAddressDetailsVoModel,
    personalDetails: personalDetailsVoModel,
    vehicleAssetDetails: vehicleAssetDetailsVoModel,
    preQualifiedCustomer: this.getPrequalifiedStatus
  };

  return avafBcmsRequestObj;
}

A: *

*You should declare another object variable instead of reusing this.avafBcmsVo which leads to an unmatched type.

*Don't build JSON string manually. This will highly chance to lead to an invalid JSON due to syntax error. Instead, converting an object to JSON string via JSON.stringify().
submitAvafDetails(): Observable<any> {
  let avafBcmsVo: any = {
    avafVO: this.prepareAvafSubmitData()
  };

  return this.httpService.processData('POST', CONSTANTS.API_URL + 'testService.exp', JSON.stringify(avafBcmsVo));
}


text:
Q: Trying to get exact keys based on the given value in the nested object - Javascript (using recursion) I have an object with nested objects like:
let menu = {
    vegetarian: {
        vegStarter: {
            plainPizza: 100,
            cheesePizza: 200,
            onionPizza: 200
        },
    },
    nonVegetarian: {
        nonVegStarter: {
            meatLoversPizza: 160,
            chickenPizza: 200,
            chilliMeatPizza: 200
        },
        nonVegMainCourse: {
            seafoodPizza: 300,
            spinachEggPizza: 200,
            eggPizza: 250
        }
    }

};

I need to collect all keys that have the same value and I must use recursion. My value is 200. I tried the code with both find() and filter() methods but didn't get the desired result. Here's the code below with outputs:
function searchUsingPriceFromMainMenu(mainObject) {
    let arrOfKeys = [];
    Object.values(mainObject).forEach(val => {
        if (val === 200 && typeof val !== "object") {
            arrOfKeys = Object.keys(mainObject).filter(key => mainObject[key] === val);
            document.write(arrOfKeys + "<br>")
        } else {
            if (typeof val === "object") {
                searchUsingPriceFromMainMenu(val, arrOfKeys)
            }
        }
    });
}
searchUsingPriceFromMainMenu(menu);

With filter() method:
cheesePizza,onionPizza
cheesePizza,onionPizza
chickenPizza,chilliMeatPizza
chickenPizza,chilliMeatPizza
spinachEggPizza

With find() method:  Just used find instead of filter. The code was same as above.
cheesePizza
cheesePizza
chickenPizza
chickenPizza
spinachEggPizza

But I want result something like:
cheesePizza
onionPizza
chickenPizza
chilliMeatPizza
spinachEggPizza

So, am I missing something or is there any other way to get the same? Please help.

A: Hope it will help =)

const menu = {
  vegetarian: {
    vegStarter: {
      plainPizza: 100,
      cheesePizza: 200,
      onionPizza: 200
    },
  },
  nonVegetarian: {
    nonVegStarter: {
      meatLoversPizza: 160,
      chickenPizza: 200,
      chilliMeatPizza: 200
    },
    nonVegMainCourse: {
      seafoodPizza: 300,
      spinachEggPizza: 200,
      eggPizza: 250
    }
  }
};

const search = (obj, checkedValue) => {
  const result = Object.entries(obj).flatMap(([key, value]) => {
    if (typeof value === 'object') {
      return search(value, checkedValue);
    }
    if (value === checkedValue) {
      return key;
    }
    return [];
  });
  return result;
};

const searched = search(menu, 200);
console.log(searched);

A: You can grab the entries of your object, and for each entry, check if it is a object. If it is, you can call your recursive function to process the child object. You can concatenate the result of this to the resulting array res, which is returned at the end of your function. Otherwise, if it is not an object, then you can check if the pizza value is equal to 200 (ie: val), and if it is, push it onto the result.

const menu = {vegetarian: { vegStarter: { plainPizza: 100, cheesePizza: 200, onionPizza: 200 }, }, nonVegetarian: { nonVegStarter: { meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200 }, nonVegMainCourse: { seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250 }}};

const getPizzasByValue = (menu, val) => {
  let res = [];
  Object.entries(menu).forEach(([pizza, pizzaVal]) => {
    if(Object(pizzaVal) === pizzaVal) { // check if value if object
      res = res.concat(getPizzasByValue(pizzaVal, val));
    } else if(pizzaVal === val) { // if value is not object, check if it matches the value
      res.push(pizza);
    }
  });
  return res;
}

console.log(getPizzasByValue(menu, 200));

A: Using recursion.

const menu = {vegetarian: { vegStarter: { plainPizza: 100, cheesePizza: 200, onionPizza: 200 }, }, nonVegetarian: { nonVegStarter: { meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200 }, nonVegMainCourse: { seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250 }}};
function recurse(menuObj, val, arr) {
  for (let key in menuObj) {

    if (typeof menuObj[key] === "object") {
       recurse(menuObj[key], val, arr);
    } else if (menuObj[key] === val){
       arr.push(key)
    }
  }

  return arr;
}

console.log(recurse(menu, 200, []))

A: We can write a generic function to filter the nested entries of an input object according to a predicate, and then write our menu function on top of that.  Here's one implementation:

const filterEntries = (pred) => (obj) =>
  Object .entries (obj) .flatMap ((entry) => [
    ... (pred (entry) ? [entry] : []),
    ... (typeof entry [1] == 'object' ? filterEntries (pred) (entry [1]) : [])
  ])

const matchingPrice = (price, menu) =>
  filterEntries (([k, v]) => v === price) (menu)
    .map (([k, v]) => k)

const menu = {vegetarian: {vegStarter: {plainPizza: 100, cheesePizza: 200, onionPizza: 200}}, nonVegetarian: {nonVegStarter: {meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200}, nonVegMainCourse: {seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250}}}

console .log (matchingPrice (200, menu))

The point is that JS objects can be considered a collection of key-value pairs.  So this object:
{
  plainPizza: 100,
  cheesePizza: 200,
  onionPizza: 200
}

can be thought of as containing these key-value pairs:
[
  ['plainPizza', 100],
  ['cheesePizza', 200],
  ['onionPizza', 200]
}

and this one:
{
  nonVegStarter: {
    meatLoversPizza: 160,
    chickenPizza: 200,
    chilliMeatPizza: 200
  },
  nonVegMainCourse: {
    seafoodPizza: 300,
    spinachEggPizza: 200,
    eggPizza: 250
  }
}

consists of these two key-value pairs:
[
  ['nonVegStarter', {meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200}],
  ['nonVegMainCourse', {seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250}]
]

Using recursion to add all the nested children of our objects, we can find a list of all such key-value pairs in our object.  It might look like this:
[
  ["vegetarian", {vegStarter: {cheesePizza: 200, onionPizza: 200, plainPizza: 100}}],
  ["vegStarter", {cheesePizza: 200, onionPizza: 200, plainPizza: 100}],
  ["plainPizza", 100],
  ["cheesePizza", 200],
  ["onionPizza", 200],
  ["nonVegetarian", {nonVegStarter: {meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200}, nonVegMainCourse: {seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250}}],
  ["nonVegStarter", {meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200}],
  ["meatLoversPizza", 160],
  ["chickenPizza", 200],
  ["chilliMeatPizza", 200],
  ["nonVegMainCourse", {seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250}],
  ["seafoodPizza", 300],
  ["spinachEggPizza", 200],
  ["eggPizza", 250]
]

Our filterEntries function does this and applies a predicate function (one which returns true or false for every value) to find all the entries in an object which match some condition.  It takes every entry of our object and creates a new array of entries.  If the predicate matches a given entry, that entry is included, and then, if the value at the entry is an object, we recursively call filterEntries with the same predicate and that value, including all matching results in the array.  It then combines the arrays for each entry into a single array, using flatMap.
We then use this in matchingPrice, creating a function which tests an entry to see if the value matches our given price, and passing that to filterEntries along with our menu object.  This creates an array of entries like this:
[
  ["cheesePizza", 200],
  ["onionPizza", 200],
  ["chickenPizza", 200],
  ["chilliMeatPizza", 200],
  ["spinachEggPizza", 200]
]

and the final map call converts these into
[
  "cheesePizza",
  "onionPizza",
  "chickenPizza",
  "chilliMeatPizza",
  "spinachEggPizza"
]

There is a good argument to write filterEntries slightly differently, layering the filtering on top of a separate utility function which generates all the entries as an array.  This wouldn't be too different:
const allEntries = (obj) =>
  Object .entries (obj) .flatMap ((entry) => [
    entry,
    ... (typeof entry [1] == 'object' ? allEntries (entry [1]) : [])
  ])

const filterEntries = (pred) => (obj) =>
  allEntries (obj) .filter (pred)

This has the advantage of creating two helpful utility functions instead of just the one.

A: Here's my take on the problem using JavaScript's generators. First we start with a function that generates all leafs of the tree, t, and yields only those which match the price input
function* matchingPrice (t, price)
{ for (const [k,v] of leafs(t))
    if (v == price)
      yield k
}

Now we write a leafs function which does a simple type analysis on the input, t, recurs on Objects, otherwise yields the input key and t as a pair -
function* leafs (t, key)
{ switch (t?.constructor)
  { case Object:
      for (const [k,v] of Object.entries(t))
        yield* leafs(v, k)
      break
    default:
      yield [key ?? null, t]
  }
}

Put it all together in an executable snippet -

function* matchingPrice (menu, price)
{ for (const [k,v] of leafs(menu))
    if (v == price)
      yield k
}

function* leafs (t, key)
{ switch (t?.constructor)
  { case Object:
      for (const [k,v] of Object.entries(t))
        yield* leafs(v, k)
      break
    default:
      yield [key ?? null, t]
  }
}

const menu =
  {vegetarian: {vegStarter: {plainPizza: 100, cheesePizza: 200, onionPizza: 200}}, nonVegetarian: {nonVegStarter: {meatLoversPizza: 160, chickenPizza: 200, chilliMeatPizza: 200}, nonVegMainCourse: {seafoodPizza: 300, spinachEggPizza: 200, eggPizza: 250}}}

console.log(Array.from(matchingPrice(menu, 200)))

Output -
[
  "cheesePizza",
  "onionPizza",
  "chickenPizza",
  "chilliMeatPizza",
  "spinachEggPizza"
]


text:
Q: clearing all cookies from my domain with javascript I know this i a duplicate from
Clearing all cookies with JavaScript
but i still got a problem.
I didn't add a path or a domain to my cookie but if i want to delete them by pressing the logout button
the cookie seems untouched
Here i built the cookie and x is the response from a AJAX-Request witch gives me the informations i need:
function setCookie(x) {
      document.cookie = x;
}

but if i want to delete them in the same javascript-script it seems untouched and i don't get any errors
This is the onLoad-function witch gets called when the user logout
function onLoad() {
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i];
            var eqPos = cookie.indexOf("=");
            var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
            document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
            alert(document.cookie);
        }
    }

can anyone tell my why it dosent work. should i add a domain or a path even when i dont add one when i creates the cookie?


text:
Q: What is the point of the Java keystores (JKS, JCEKS) when the keystore password is just as vulnurable as the keys themselves? I have some code that encrypts some user data. Currently I have the key stored in a configuration file that gets loaded at runtime. This sucks for a number of reasons, namely that if someone gets access to the config file they have access to the secret key. So I started looking into the Java keystores, but I can't seem to justify them. The keystores require a password, which would be just as vulnerable as hardcoding the key. Am I missing something, or do key stores suffer the same weaknesses as hard coding the secret keys?

A: By using the JKS or any keystore really you are taking the first step toward offloading the key protection requirements from your application or server to the keystore or the user of that keystore.  There are plenty of guidelines for protecting keys and keystores that can get quite fancy (HSM's, etc..), but leveraging the JCE architecture is just first step. In the meantime might as well start baking security into your application.
https://security.stackexchange.com/questions/11517/storage-of-secrets-keystores-hsms-and-the-rest

A: A common architecture I see is the application encrypts the data using a private key, or the application must decrypt database credentials for a specific dev/test/prod environment.  Developers commit code and configuration to a code repository.  However, the key used to encrypt/decrypt is created by another team and stored somewhere else. When the server or container is deployed, the keystore is deployed with it.  The codebase including the configuration files is built and deployed onto the the server.  The developer never have access to the decryption keys, the keys are never in the code repo.


text:
Q: Trying to configure samba share with office server i'm trying to set up fstab to automatically connect to my office shared server. I'm undoubtedly doing something silly here as the username and password and server name work fine in the first code snippet below, just not the second - any help would be appreciated!
The following command works as expected...
tom@tom-desktop: sudo /usr/bin/smbclient -L Server.local -Uguest
Enter guest's password:
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.0.10]

        Sharename       Type      Comment
        ---------       ----      -------
        Lacie Disk      Disk      macosx
        Server          Disk      macosx
        IPC$            IPC       IPC Service (Server)
        ADMIN$          IPC       IPC Service (Server)
Domain=[WORKGROUP] OS=[Unix] Server=[Samba 3.0.10]

        Server               Comment
        ---------            -------
        ACER-9D60040D10
        SERVER               Server

        Workgroup            Master
        ---------            -------
        WORKGROUP            ACER-9D60040D10

But when i add the following line to /etc/fstab, i get this error: cifs_mount failed w/return code = -22
//Server.local/Server  /media/maguires  cifs  username=guest,password=password  0  0

A: I think mount error 22 = invalid argument? Try IP address instead of Server.local.
Install the network file system:
sudo apt-get install smbfs

A: Try changing the line to specify that you're using a guest user, perhaps?
//Server.local/Server  /media/maguires  cifs  guest,users  0  0

the users tag will allow you mount/unmount it as a standard user.
Alternatively, try specifying guest, but keep the password blank :
//Server.local/Server  /media/maguires  cifs  username=guest,password=,users  0  0

Also, many people have reported that smbfs doesn't work so well with hostnames specified in /etc/fstab.  Perhaps try changing Server.local reference to an IP address.  (NB : This is still worth doing EVEN IF you have name resolution working, either through /etc/hosts or a relevant DNS entry.)
[Edit - didn't read Christopher's comments on this issue.  Worth keeping in though]
Hope this helps.

A: You may have to switch the slashes in your command to the backslashes, like so:
\\\\Server.local\\Server  /media/maguires  cifs  username=guest,password=password  0  0

Note the doubling of all of the slashes; backslash is an escape character, so to get a literal backslash you have to escape it with another one.
Hope that helps!


text:
Q: Google Weather API conditions I'm using SAX to pull information from the google weather API and I'm having issues with the "conditions".
Specifically I'm using this code:
public void startElement (String uri, String name, String qName, Attributes atts) {
    if (qName.compareTo("condition") == 0) {
        String cCond = atts.getValue(0);
        System.out.println("Current Conditions: " + cCond);
        currentConditions.add(cCond);
    }

To pull XML from something like this:
http://www.google.com/ig/api?weather=Boston+MA
Meanwhile I'm trying to get conditions only for the current day, and not for any days in the future.
Is there some check I could put into the xml to only pull data for the present day based on what's in the XML file?
Thanks!

A: This should do the trick. Keep in mind that if your are using a framework it might have utility functions for XPath to make it simpler.
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class XPathWeather {

  public static void main(String[] args)
   throws ParserConfigurationException, SAXException,
          IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("/tmp/weather.xml");

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("/xml_api_reply/weather/current_conditions/condition/@data");

    String result = (String) expr.evaluate(doc, XPathConstants.STRING);
    System.out.println(result);
  }

}


text:
Q: CSS: padding doesn't let element go fully top I was making navigator menu for my website, i tried properly setting line-height and height for navigator menu, where i got the problem, the profilebar element was too low and so was the balance paragraph.
Navigator menu style:
.menu {
  background-color: rgba(26, 26, 26, 0.9);
  width: 100%;
  height: 3.7em;
  line-height: 3.7em;
  border-style: solid;
  border-color: rgba(26, 26, 26, 0.9);
  z-index: 1;
  max-width: 102.5%;
  min-width: 1000px;
}

Fiddle Fullscreen ( Image is sample, so it being bigger than menu is not problem. The picture i originally use is 32x32 image from steam API ).
Fiddle Code.
What could the problem be? is it padding that i need to properly set? or are there other things that i have done wrong.

A: Try resize your profile picture: set height for .profilepicture
and set margin and padding for .balance
    margin: 0;
    padding: 0;
that is all


text:
Q: FTP or any others way?I just need guideline Actually I'm now have the basic skill in FTP only, and now I'm facing the problem of getting .log file from a remote site. I can access into it, and check for the file exist, but don't know how to retrieve it.

*

*Can I use apache FileUtils to set source and destination? If can, can I set the destination to another remote site? (like put ip address)

*Or can I use File input and output stream? and the same, can i apply ip address in the outputstream?
or any others suggestion for me?
thanks for your answer.

A: Java FTP libraries you can use: JavaWorld FTP libs article


text:
Q: Application Not installed in your phone I run the application in the emulator it works successfully and the icon of the application is show in the emulator menu but when i try to run again that app from the emulator menu it can't allow me to run from that and display the Toast "Application is Not installed in your phone".
In the Image the red rounded is my application icon.

A: Also, it happened to me once when I changed the launch activity. Reinstalling the application and restarting the phone make it work.

A: This can happen if you have your MainActivity declared twice in your AndroidManifest.xml,
first as a launhcer
<activity android:name=".MyActivity" android:label="@string/app_name">
    <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

and then just declared like:
<activity android:name=".MyActivity" />

So check for this and delete the second extra declaration.

A: I had the same error when there was a syntax error in my widget provider. Instead of
android:configure="com.android.worldagendaapp1.WidgetConfig"

I wrote
android:configure="com.android.WorldAgendaapp1.WidgetConfig"

perhaps this can be helpfull for those few who still experience the error

A: Remove the Repeat Main Activity Declaration in the manifest file. It work For me

A: Another scenario when you can receive such a message, if you have created the shortcut for an earlier version, and then moved the launcher activity into another package in the new version. (application package remained the same).
On my ZTE Blade, the shortcut is just removed during update.
On an HTC Nexus One the shortcut stays there, but clicking on it has no effect..
Further details here

A: Its funny but i have solved my issue by remove permission from activity tag
i have code like below:
<application
        android:allowBackup="true"
        android:debuggable="false"
        android:icon="@drawable/app_icon"
        android:permission="android.permission.ACCESS_FINE_LOCATION"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock.Light.DarkActionBar" >

i have remove permission
 <application
            android:allowBackup="true"
            android:debuggable="false"
            android:icon="@drawable/app_icon"

            android:label="@string/app_name"
            android:theme="@style/Theme.Sherlock.Light.DarkActionBar" >

A: I had this happen for including WRITE_EXTERNAL_STORAGE twice in the manifest. It only affected certain user phones, my test phones and the emulator launched fine, and lint gave no warning. I suffered quite a few 1 star ratings over several months before discovering the cause:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
<application android:permission="android.permission.WRITE_EXTERNAL_STORAGE"...

Deleting the second one fixed it.


text:
Q: How to split 1D array in to arrays based on multiple keys - Javascript? I have an 1D array like this, where a single object inside that array looks this
[
  {
    date: "01/01/2020",
    type1: 264,
    type2: 1937,
    type3: 30
  },
  ...
]

I want to modify the above array and convert it into a 2D array in the below format
[
  [
    {
      "date": "01/01/2020",
      "type": "type1",
      "value": 264
    },
    {
      "date": "01/01/2020",
      "type": "type2",
      "value": 1937
    }
    .....
  ],
  [
    {
      "date": "01/01/2020",
      "type": "type3",
      "value": 30
    }
    .....
  ]
]

Basically first array will consist of type1 and type2 values and the second array will consist of type3 value.
I am pretty new to javascript. I have tried this using plain javascript like below
const type1 = data.map((e: any) => ({
  date: e.date,
  type: "type1",
  value: e.type1
}));

const type2 = data.map((e: any) => ({
  date: e.date,
  type: "type2",
  value: e.type2
}));

const type3 = data.map((e: any) => ({
  date: e.date,
  type: "type3",
  value: e.type3
}));

const newData = [type1.concat(type2), type3];

Is there any better way to do it ?

A: As a first step, a way to convert the object(s) into the split up objects is to specify the property names (this is assuming there are no more unknown properties):

const arr = [{date:'01/01/2020', type1:264,type2: 1937,type3:30}];

const res = _.flatMap(arr,o=> ['type1','type2','type3'].map(t=> ({date:o.date, type:t, value:o[t]})));

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

After that though, I am not certain of the goal, If you want all objects of type 3 in a separate array, regardless of source object, a quick and dirty way could be:

const arr = [{date:'01/01/2020', type1:264,type2: 1937,type3:30}];

const res = [[],[]];
  _.flatMap(arr,o=> ['type1','type2','type3'].map(t=> ({date:o.date, type:t, value:o[t]})))
  .forEach(o=> res[o.type==='type3' ? 1: 0].push(o));

console.log(res);
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>