text:
Q: Get access to SQLAlchemy connection socket to prevent firewall timeouts I am having some issues with my database connections. They seem to be abruptly severed by some firewall in the network and a nice way to fix this at the TCP level seems to be to configure keepalive for a particular TCP socket. The problem is I have no idea how and if it is possible to gain access to the connections managed by SQLAlchemy. I am using it to connect to an Oracle database. This is enabled by the use of cx_Oracle and Oracle's Instant Client which is also installed.

A: Use the SQL*Net option EXPIRE_TIME as documented in the cx_Oracle doc. EXPIRE_TIME can be used to prevent firewalls from terminating idle connections and to adjust keepalive timeouts. The general recommendation for EXPIRE_TIME is to use a value that is slightly less than half of the termination period.
The details:

*

*With 18c client libraries it can be added as (EXPIRE_TIME=n) to the DESCRIPTION section of a connect descriptor (in a full connect descriptor string in the app, or in the tnsnames.ora file).

*With 19c client libraries it can be used via Easy Connect: host/service?expire_time=n.

*With 21c client libraries it can be used in a client-side (i.e. Python machine) sqlnet.ora.

With older client versions you can use ENABLE=BROKEN instead.
Also consider using a connection pool with SQLAlchemy, since this will do some checks and automatically re-establish connections if they have been killed.  Pools are also great for performance in heavily used, long running apps.


text:
Q: disallow the passing of generic type on function call I'm trying to define the following function:
  function sequence<T = number>(fn: (x: number) => T = (x => x) ) {
    return ((i: number) => () => fn(i++))(0)
  }

I'm getting the following complaint from the compiler:
Type 'number' is not assignable to type 'T'.
  'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'

However, the type inference just works fine:
const seq = sequence() // return type: () => number
const seq2 = sequence(x => `${x}`) // return type: () => string

Do you know how to get rid of this error while keeping the type inference?
EDIT: Investigating a little more about the error, I found this happens because I could call sequence as follows:
const seq3 = sequence<string>() // return type: () => string

what is effectively an error because by default sequence has () => number as return type.
Is there a way to disallow the third example?

A: I just found a solution, probably not the most elegant one:
function sequence(): () => number
function sequence<T>(fn: (x: number) => T): () => T

function sequence<T>(fn?: (x: number) => T) {
  if (fn) return ((i: number) => () => fn(i++))(0);
  return ((i: number) => () => i++)(0);
}

Essentially, you have to overload the function to disambiguate each case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: passing data from controller to view advice required i want to pass some data from my database on to a webpage i have Somme code in my model that specify what data i want to select and echo the data in my view my question is how would i go about passing Somme data in to view using the controller ? here is my code
survay/php
    <?php
class Survay extends CI_Model{

    function dosurvay($Question, $qA, $qB, $qC){
        $this->db->select('QID, Question, qA, qB, qC');
        $this->db->from('tblquestions');
        $this->db->where('Question', $Question);
        $this->db->where('qA', $qA);
        $this->db->where('qB', $qB);
        $this->db->where('qC', $qC);
         $this -> db -> limit(1);

   $query = $this -> db -> get();

   if($query -> num_rows() == 1)
   {
     return $query->result();
   }
   else
   {
     return false;
   }
 }

}
?>

survay_view.php

<?php echo $Question;?>

    <?php echo $qA; ?><?php form_checkbox('qA'); ?>
    <?php echo $qB; ?><?php form_checkbox('qB');?>
    <?php echo $qC; ?><?php form_checkbox('qC'); ?>

A: in controller
load your model
$this->load->model('survay');

call your model function
$survay_data = $this->survay->dosurvay($Question, $qA, $qB, $qC);

load your data to the view
$viewData = array();
$viewData['survay_data'] = $survay_data;
$this->load->view('survay_view', $viewData)


text:
Q: how can i escape a group of special characters in java in one method? i use lucene search but lucene has a bunch of special characters to escape like:
- && || ! ( ) { } [ ] ^ " ~ * ? : \

i am having problem escaping these characters because they are too many and if i use the String.replaceAll() method, i'll just end up having a really long line of code just for escaping the characters. what is the best way to do? thanks!

A: Use regular expression to replace those characters in one go.
example:
 String s="some text && || []!{} ()^*?~ and ";
        Pattern p= Pattern.compile("([-&\\|!\\(\\){}\\[\\]\\^\"\\~\\*\\?:\\\\])");

        s=p.matcher(s).replaceAll("\\\\$1");
        System.out.println(s);\\prints some text \&\& \|\| \[\]\!\{\} \(\)\^\*\?\~ and

A: There is also a method called QueryParser#escape, which may be useful:

Returns a String where those characters that QueryParser expects to be escaped are escaped by a preceding \.

A: Use regular expression. String.replaceAll() supports regular expression, so you can solve this problem using one single call. Just be careful: some of these characters are special for regular expressions too, so they mus be escaped "twice":
str.replaceAll("([-\\&\\|!\\(\\)\\{\\}\\[\\]\\^\\"~\\*\\?:\\])", "\\$1");
(I have not tried this, probably this line needs some fixes, but this is the idea)

A: There is a Apache Commons Library for that:
http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html


text:
Q: Yii CActiveDataProvider generate SQL query CActiveDataProvider generating auto query to count total item count:
SELECT COUNT(DISTINCT `t`.`id`) FROM `transaction` `t` LEFT OUTER JOIN `partner` `partner` ON (`t`.`partner_id`=`partner`.`id`)

This query is slow, because contain join, how I can set manualy total count, and disable this auto query ?

A: Try set use CActiveDataProvider->countCriteria.
http://www.yiiframework.com/doc/api/1.1/CActiveDataProvider#countCriteria-detail

A: You may manualy set total item count for CActiveDataProvider to prevent auto calculation.
class Model extends CActiveRecord {

    public function search(){
      $criteria = new CDbCriteria;
      // your criteria here
      $data_provider = new CActiveDataProvider($this, array('criteria'=>$criteria));
      // replace $this->count( $criteria ) with your own condition or another criteria
      $data_provider->setTotalItemCount( $this->count( $criteria ) );
      return $data_provider;
    }
}


text:
Q: Yad Button closed I have this code:
#!/bin/bash
choice=$(yad --title="Vyberte si prosím produkčnú ES" \
--borders=20 --text="<big><big>Vyberte si prosím program na výpočet produkčnej ES:</big></big> \n \n "   \
--form --field="Biomasa - poľnohospodárske plodiny (P1)":BTN "echo 1" \
--form --field="Biomasa - drevo a prírodné vlákna (P2)":BTN "echo 2" \
--form --field="Pitná voda (P3)":BTN "echo 3" \
--form --field="Úžitokvá voda (P4)":BTN "echo 4" \
--form --field="Voľne žijúca zver / prírodné plodiny (P5)":BTN "echo 5")

echo "$choice"

But when I click the button nothing will happen, I need after clicking on some button to close the window and send value 1 to 5 to the variable $choice. Thank you for any advice.

A: Further to my comment, I did some experimenting and came up with this script, which I believe does exactly what you want. While the documentation says that a form must call a function, with my version of yad, which is 0.40.0 (GTK+ 3.24.33), a 'bash -c {command}' works. As for not being able to close the yad dialogue after an option is selected, I got round this by killing the process using the YAD_PID variable.
#!/bin/bash
choice=$(yad --title "Vyberte si prosím produkčnú ES" \
--borders=20 --no-buttons \
--text "<big><big>Vyberte si prosím program na výpočet produkčnej ES:</big></big> \n \n "   \
--form --columns 1 \
--field="Biomasa - poľnohospodárske plodiny (P1):FBTN" 'bash -c "echo 1;kill $YAD_PID"' \
--field="Biomasa - drevo a prírodné vlákna (P2):FBTN" 'bash -c "echo 2;kill $YAD_PID"' \
--field="Pitná voda (P3):FBTN" 'bash -c "echo 3;kill $YAD_PID"' \
--field="Úžitokvá voda (P4):FBTN" 'bash -c "echo 4;kill $YAD_PID"' \
--field="Voľne žijúca zver / prírodné plodiny (P5):FBTN" 'bash -c "echo 5;kill $YAD_PID"')
echo "Choice was $choice"

Two years too late, but maybe it will help someone!


text:
Q: Can't set referer to localhost I have PHP script which need to generate playlist from stream links in specic url ($url).
So this url parsing and I get playlist with some strim links.
Like this
#EXTM3U
#EXTINF:0,top_stream
http://link1
#EXTINF:0,tv123
http://link2
#EXTINF:0,music
http://link3

And this is part works on localhost and on hosting server.
When I upload whis script on my hosting server, and run script I get same playlist and I have same strim links in playlist.
BUT all links in playlist doesn't works - URL Link Not found.
Example
http://link1
http://link2 ... can't open - Not found
So I need to set referel to localhost in PHP file.
I tried this, but doesn't work:
error_reporting(E_ALL & ~E_NOTICE);
header('Content-Type: application/json; charset=utf-8');
$url = "http://example.com".time();

$params = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_REFERER, "http://127.0.0.1/");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$_data = json_decode($data, true);
curl_close ($ch);

Curl enabled and working on server.
Sorry for unclear post.
Thanks


text:
Q: How to search for documents based on the value of adding 2 properties on the document? I have a document:
{"price1": 500, "price2": 500}

I want to find all documents where "(price1 + price 2) < 1200".  I assume I can do this by using the aggregation framework, but not seeing the correct way.

A: You can do it using $add. Try the following code:
db.collection.aggregate([
    { $project: { total: { $add: [ "$price1", "$price2" ] } } },
    { $match: {total: {$lt: 1200  }} }
])

A: Another way to do this is using the $redact operator to return all documents where the sum of "price1" and "price2" greater than 1200. Of course to get the sum you need to use the $add operator.The $condoperator evaluates and returns the documents that if that expression is true using the $$KEEP variable and exclude all documents where that condition evaluates to false using the $$PRUNE variable.
db.collection.aggregate([
    { "$redact": {
        "$cond": [
            { "$lt": [
                { "$add": [ "$price1", "$price2"] },
                1200
            ]},
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])


text:
Q: How to use random_shuffle to shuffle a 2D array C++ I have a 2D vector of objects and I want to shuffle them. What is the syntax for this?
    class node{
    public:
        string hex_type = "E";// empty to start
        int Xcoordinate;
        int Ycoordinate;
        vector<reference_wrapper<node>> neighbors;

    };
nodes = vector<vector<node> >(size, vector <node>(size));//filled elsewhere
random_shuffle(&nodes[0][0], &nodes[size-1][size-1]);

This generates an error that is is an access violation reading

A: If you have 2d array a n x m, you can put it in a 1d array b n x m like this:
b[i * m + j] = a[i][j];

Then you can shuffle array b and user reverse transformation
a[i / m][i % m] = b[i];


text:
Q: What's the point of using LiveData in ViewModel if I can use Flow and StateFlow with lifecycleScope \ viewLifecycleOwner.lifecycleScope Flow has a lot of operators, LiveData has only 3 (Transformations). Is there any reason to keep using LiveData except StateFlow is still experimental?
UPD. StateFlow, SharedFlow and corresponding operators are promoted to stable API in kotlinx.coroutines 1.4.0

A: There is not much reason to use LiveData nowadays. (State)Flow/Coroutines also brings new possibilites via lifecycleScope.launchWhenCreated/Started/Resumed, hard to do with LiveData.
But there is one reason when LiveData is needed - DataBinding. It currently doesn't support observing Flow.
EDIT: there is going to be support for StateFlow in DataBinding in Android  Studio 4.3: https://twitter.com/manuelvicnt/status/1314621067831521282


text:
Q: Compare two files, if match, only last two field will be shift down (awk) I have two input files (tab delimited) and I need find match between them for the $1 && $2 if the match only 3rd and 4th field will be shifted down:
INPUT:
File1:
p1   555
p1   557
p3   558

File2:
p1  323 lololo  aaaa
p1  555 papapp  kkka
p1  556 hooho   sssa
p1  557 jjjlo   kkka
p3  424 zzzzz   llla
p3  558 jjjjj   ssss

OUTPUT:
p1 323  lololo aaaa
p1 555
          papaapp kkka
p1 556   hooho   sssa
p1 557
          jjjlo kkka
 etc.

I have for comparison:
awk -F'\t' 'NR==FNR{c[$1$2]++;next};c[$1$2] > 0' file1 file2

But how to do condition for it I do not know:
awk '{if ($1$2file1 == $1$2file2) print $1$2"\n"$3$4; else print $0}' ?

A: give this one-liner a try:
awk -F'\t' 'NR==FNR{a[$0];next}
           {k=$1 FS $2;if(k in a){print k;$1=$2=FS}print}' file1 file2

with your data:
kent$  head f1 f2
==> f1 <==
p1      555
p1      557
p3      558

==> f2 <==
p1      323     lololo  aaaa
p1      555     papapp  kkka
p1      556     hooho   sssa
p1      557     jjjlo   kkka
p3      424     zzzzz   llla
p3      558     jjjjj   ssss

kent$  awk -F'\t' 'NR==FNR{a[$0];next}{k=$1 FS $2;if(k in a){print k;$1=$2=FS}print}' f1 f2
p1      323     lololo  aaaa
p1      555
                 papapp kkka
p1      556     hooho   sssa
p1      557
                 jjjlo kkka
p3      424     zzzzz   llla
p3      558
                 jjjjj ssss

A: The in operator will tell you whether the $1$2 value from file2 was seen in file1. This has an advantage over something like checking c[$1$2] > 0as the latter will actually create an entry for $1$2 even if it hadn't existed before (with value equivalent to 0, so still works, but we don't need to create it so nice to avoid that side effect by using in instead).
EDIT: Use the comma separator in the array index so that the SUBSEP value is inserted between $1 and $2, avoiding the issue so rightly pointed out in the comments.
$ cat tf.awk
BEGIN {FS=OFS="\t"}
NR==FNR {c[$1,$2]; next}
{if (($1,$2) in c) print $1,$2 RS OFS OFS $3, $4; else print}

$ awk -f tf.awk file1 file2
p1  323 lololo  aaaa
p1  555
        papapp  kkka
p1  556 hooho   sssa
p1  557
        jjjlo   kkka
p3  424 zzzzz   llla
p3  558
        jjjjj   ssss


text:
Q: Find and/or Edit file names in a directory hierarchy I created a python program and I used import.os... so I want to convert it but not with import.os
can someone help me?
So the main goal is the user to be able to search a path and also to change the file name but i only know the import.os method.
 tree.py
import os
import sys
import time
#logo
print("_______ _______________ ______  ___")
print("___    |___  __/__  __ \___   |/  /")
print("__  /| |__  /   _  / / /__  /|_/ /")
print("_  ___ |_  /    / /_/ / _  /  / /")
print("/_/  |_|/_/     \____/  /_/  /_/")
#os.getcwd() Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python.
path = os.chdir('/root')
bl = os.getcwd()
#To change our current working directories in python, we use the chdir() method.
print(os.listdir())
os.chdir(bl)
print("your current location is: ", path)
change = input("Do you want to change your directory (yes/no): ")
if change == "yes":
        dir = input("Add new Location: ")
        if dir == bl and dir == path:
                print("cant go to the same directory")
        else:
                print("please wait")
                time.sleep(2)
                os.chdir(dir)
                print(os.path.exists(dir))
                print(os.getcwd())
prDIR = input("Do you want to print the files (yes/no) : ")
if prDIR == "yes":
        for f in os.listdir():
                file_name, file_ext = os.path.splitext(f)
                print(file_name.split('-'))
change2 = input("Do you want to change again your DIR: ")
if change2 == "yes":
        dir = input("Add a new location: ")
        if dir == bl:
                print("cant go to the same place")
        else:
                print("please wait")
                time.sleep(1)
                os.chdir(dir)
                print(os.path.exists(dir))
                print(os.getcwd())
print("your current location is: ", path, dir)
pat = input("Do you want to rename this Dir (yes/no) : ")
if pat == "yes":
        ch = input("Enter the path but renamed: ")
        time.sleep(2)
        os.rename(dir, ch)
        print(ch)


text:
Q: Simple HTML & css table stupid issue, easy solution I have this simple table newsletter design and I cannot identify what causes the table to be wider than I set it to be.

            <anpa href="http://www.bdforum.org" style="font-weight:100;color: #ffffff; text-decoration: none; padding-right: 1em;">
            WEBSITE</anpa>
            <anpa href="##TellAFriend##" style="font-weight:none;color: #ffffff; text-decoration: none; padding-right: 1em;">
            FORWARD</anpa>
            <anpa href="http://www.anpdm.com/form/4743504075464B5943/414358407446455F4571" style="font-weight:none;color: #ffffff; text-decoration: none; padding-right: 1em;">
            SUBSCRIBE</anpa>
            <anpa href="##OptOutAll##" style="font-weight:none;color: #ffffff; text-decoration: none;">
            UNSUBSCRIBE

            </anpa>

          <anpa href="http://www.bdforum.org">
          Baltic Development Forum</anpa>

        LATEST BDF NEWS ESPECIALLY FOR YOU

      WEBSITE

If you could help me I would really appreciate it. I am kind of a beginner. Especially with writing html for emails as its super annoying with different supports

A: because you have to put max-width="600" inside the style attribute since max-width not a valid attribute for table, fix your problem like this style="height:auto;max-width:600px"
UPDATE
To handle the extra pixels on right and bottom add this style="padding: 0;width: 100%;" to the first td

A: Put max-width attribute inside style tag

For border issue, you can update table tag like

            <anpa href="http://www.bdforum.org" style="font-weight:100;color: #ffffff; text-decoration: none; padding-right: 1em;">
            WEBSITE</anpa>
            <anpa href="##TellAFriend##" style="font-weight:none;color: #ffffff; text-decoration: none; padding-right: 1em;">
            FORWARD</anpa>
            <anpa href="http://www.anpdm.com/form/4743504075464B5943/414358407446455F4571" style="font-weight:none;color: #ffffff; text-decoration: none; padding-right: 1em;">
            SUBSCRIBE</anpa>
            <anpa href="##OptOutAll##" style="font-weight:none;color: #ffffff; text-decoration: none;">
            UNSUBSCRIBE

            </anpa>

          <anpa href="http://www.bdforum.org">
          Baltic Development Forum</anpa>

        LATEST BDF NEWS ESPECIALLY FOR YOU

      WEBSITE

Hope it helps.


text:
Q: put atributes to X500NameBuilder Bouncy Castle to Generarte a PKCS10 we are trying to generate a PKCS10CertificationRequest (AKA CSR in Der Format), we know how is done i will put the code of that generation, but for the X500Name we are using X500NameBuilder that is really helpful but the style we are using is BCStyle, include almost al the data ned to be there.
the problem is we need to put another data that is not in the bcstyle (the data is specified in here http://www.alvestrand.no/objectid/2.5.4.45.html, and here http://www.alvestrand.no/objectid/2.5.4.23.html) and really can't see how to put it, we thinks is creating a new X500NameStyle, but we dont understand how to do it.
could anyone explain to us how to do it
thanks for the support
PS: the Code we are using
public PKCS10CertificationRequest generatedCSR(PrivateKey key, PublicKey pkey, Map<String,String> certdata, String CSRAlgorithm, String name, KeyFileManager kfm) throws OperatorCreationException, IOException
{
    Log.i(LOGCERT, "iniciando generacion de CSR");
    this.mensaje(LogType.MENI, "Se a iniciado la generacion de un CSR");
    ContentSigner signer = new JcaContentSignerBuilder(CSRAlgorithm).build(key);
    X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
    namebuilder.addRDN(BCStyle.CN, certdata.get("CN"));
    namebuilder.addRDN(BCStyle.OU, certdata.get("OU"));
    namebuilder.addRDN(BCStyle.O, certdata.get("O"));
    namebuilder.addRDN(BCStyle.L, certdata.get("L"));
    namebuilder.addRDN(BCStyle.ST, certdata.get("ST"));
    namebuilder.addRDN(BCStyle.C, certdata.get("C"));
    namebuilder.addRDN(BCStyle.EmailAddress, certdata.get("EMAIL"));
    PKCS10CertificationRequestBuilder csrbuilder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),pkey);
    PKCS10CertificationRequest csr = csrbuilder.build(signer);
    if(kfm.salvarLlave(csr.getEncoded(), KeyFileManager.CSRFILE, name)){
        Log.i(LOGCERT, "CSR Almacenado");
        return csr;
    }
    else{
        Log.i(LOGCERT, "CSR no almacenado");
        return csr;
    }
}

A: We found the Solution to our Problem the only thing we need to do is create the ASN1ObjectIdentifier("");, to put the missing data to the CSR
here is the correcte code
public PKCS10CertificationRequest generatedCSR(PrivateKey key, PublicKey pkey, Map<String,String> certdata, String CSRAlgorithm, String name, KeyFileManager kfm) throws OperatorCreationException, IOException
{
    Log.i(LOGCERT, "iniciando generacion de CSR");
    this.mensaje(LogType.MENI, "Se a iniciado la generacion de un CSR");
    ContentSigner signer = new JcaContentSignerBuilder(CSRAlgorithm).build(key);
    X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
    namebuilder.addRDN(BCStyle.CN, certdata.get("CN"));
    namebuilder.addRDN(BCStyle.OU, certdata.get("OU"));
    namebuilder.addRDN(BCStyle.O, certdata.get("O"));
    namebuilder.addRDN(BCStyle.L, certdata.get("L"));
    namebuilder.addRDN(BCStyle.ST, certdata.get("ST"));
    namebuilder.addRDN(BCStyle.C, certdata.get("C"));
    namebuilder.addRDN(BCStyle.EmailAddress, certdata.get("EMAIL"));
    namebuilder.addRDN(new ASN1ObjectIdentifier("2.5.4.45"), certdata.get("RIFCI"));
    namebuilder.addRDN(new ASN1ObjectIdentifier("2.5.4.23"), certdata.get("FAX"));
    PKCS10CertificationRequestBuilder csrbuilder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),pkey);
    PKCS10CertificationRequest csr = csrbuilder.build(signer);
    if(kfm.salvarLlave(csr.getEncoded(), KeyFileManager.CSRFILE, name)){
        Log.i(LOGCERT, "CSR Almacenado");
        return csr;
    }
    else{
        Log.i(LOGCERT, "CSR no almacenado");
        return csr;
    }
}

A: Use this builder:
public class X500VgaNameBuilder {
  private X500NameBuilder x500NameBuilder;

  public X500VgaNameBuilder()
  {
    x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
  }

  private String    BUSINESS_CATEGORY;
  private String    C;
  private String    CN;
  private String    COUNTRY_OF_CITIZENSHIP;
  private String    COUNTRY_OF_RESIDENCE;
  private String    DATE_OF_BIRTH;
  private String    DC;
  private String    DMD_NAME;
  private String    DN_QUALIFIER;
  private String    E;
  private String    EmailAddress;
  private String    GENDER;
  private String    GENERATION;
  private String    GIVENNAME;
  private String    INITIALS;
  private String    L;
  private String    NAME;
  private String    NAME_AT_BIRTH;
  private String    O;
  private String    OU;
  private String    PLACE_OF_BIRTH;
  private String    POSTAL_ADDRESS;
  private String    POSTAL_CODE;
  private String    PSEUDONYM;
  private String    SERIALNUMBER;
  private String    SN;
  private String    ST;
  private String    STREET;
  private String    SURNAME;
  private String    T;
  private String    TELEPHONE_NUMBER;
  private String    UID;
  private String    UNIQUE_IDENTIFIER;
  private String    UnstructuredAddress;
  private String    UnstructuredName;

  public String getBUSINESS_CATEGORY() {
    return BUSINESS_CATEGORY;
  }

  public X500VgaNameBuilder setBUSINESS_CATEGORY(String businessCategory) {
    this.BUSINESS_CATEGORY = businessCategory;
    x500NameBuilder.addRDN(BCStyle.BUSINESS_CATEGORY, businessCategory);
    return this;
  }

  public String getC() {
    return C;
  }

  public X500VgaNameBuilder setC(String countryCode) {
    C = countryCode;
    x500NameBuilder.addRDN(BCStyle.C, countryCode);
    return this;
  }

  public String getCN() {
    return CN;
  }

  public X500VgaNameBuilder setCN(String commonName) {
    this.CN = commonName;
    x500NameBuilder.addRDN(BCStyle.CN, commonName);
    return this;
  }

  public String getCOUNTRY_OF_CITIZENSHIP() {
    return COUNTRY_OF_CITIZENSHIP;
  }

  public X500VgaNameBuilder setCOUNTRY_OF_CITIZENSHIP(String countryOfCitizenship) {
    this.COUNTRY_OF_CITIZENSHIP = countryOfCitizenship;
    x500NameBuilder.addRDN(BCStyle.COUNTRY_OF_CITIZENSHIP, countryOfCitizenship);
    return this;
  }

  public String getCOUNTRY_OF_RESIDENCE() {
    return COUNTRY_OF_RESIDENCE;
  }

  public X500VgaNameBuilder setCOUNTRY_OF_RESIDENCE(String countryOfResidence) {
    this.COUNTRY_OF_RESIDENCE = countryOfResidence;
    x500NameBuilder.addRDN(BCStyle.COUNTRY_OF_RESIDENCE, countryOfResidence);
    return this;
  }

  public String getDATE_OF_BIRTH() {
    return DATE_OF_BIRTH;
  }

  public X500VgaNameBuilder setDATE_OF_BIRTH(String dateOfBirth) {
    this.DATE_OF_BIRTH = dateOfBirth;
    x500NameBuilder.addRDN(BCStyle.DATE_OF_BIRTH, dateOfBirth);
    return this;
  }

  public String getDC() {
    return DC;
  }

  public X500VgaNameBuilder setDC(String DC) {
    this.DC = DC;
    x500NameBuilder.addRDN(BCStyle.DC, DC);
    return this;
  }

  public String getDMD_NAME() {
    return DMD_NAME;
  }

  public X500VgaNameBuilder setDMD_NAME(String dmdName) {
    this.DMD_NAME = dmdName;
    x500NameBuilder.addRDN(BCStyle.DMD_NAME, dmdName);
    return this;
  }

  public String getDN_QUALIFIER() {
    return DN_QUALIFIER;
  }

  public X500VgaNameBuilder setDN_QUALIFIER(String dnQualifier) {
    this.DN_QUALIFIER = dnQualifier;
    x500NameBuilder.addRDN(BCStyle.DN_QUALIFIER, dnQualifier);
    return this;
  }

  public String getE() {
    return E;
  }

  public X500VgaNameBuilder setE(String emailVerisign) {
    E = emailVerisign;
    x500NameBuilder.addRDN(BCStyle.E, emailVerisign);
    return this;
  }

  public String getEmailAddress() {
    return EmailAddress;
  }

  public X500VgaNameBuilder setEmailAddress(String emailAddressPkcs9) {
    EmailAddress = emailAddressPkcs9;
    x500NameBuilder.addRDN(BCStyle.EmailAddress, emailAddressPkcs9);
    return this;
  }

  public String getGENDER() {
    return GENDER;
  }

  public X500VgaNameBuilder setGENDER(String gender_size1) {
    this.GENDER = gender_size1;
    x500NameBuilder.addRDN(BCStyle.GENDER, gender_size1);
    return this;
  }

  public String getGENERATION() {
    return GENERATION;
  }

  public X500VgaNameBuilder setGENERATION(String generation) {
    this.GENERATION = generation;
    x500NameBuilder.addRDN(BCStyle.GENERATION, generation);
    return this;
  }

  public String getGIVENNAME() {
    return GIVENNAME;
  }

  public X500VgaNameBuilder setGIVENNAME(String givenname) {
    this.GIVENNAME = givenname;
    x500NameBuilder.addRDN(BCStyle.GIVENNAME, givenname);
    return this;
  }

  public String getINITIALS() {
    return INITIALS;
  }

  public X500VgaNameBuilder setINITIALS(String initials) {
    this.INITIALS = initials;
    x500NameBuilder.addRDN(BCStyle.INITIALS, initials);
    return this;
  }

  public String getL() {
    return L;
  }

  public X500VgaNameBuilder setL(String localityName) {
    L = localityName;
    x500NameBuilder.addRDN(BCStyle.L, localityName);
    return this;
  }

  public String getNAME() {
    return NAME;
  }

  public X500VgaNameBuilder setNAME(String name_idatname) {
    this.NAME = name_idatname;
    x500NameBuilder.addRDN(BCStyle.NAME, name_idatname);
    return this;
  }

  public String getNAME_AT_BIRTH() {
    return NAME_AT_BIRTH;
  }

  public X500VgaNameBuilder setNAME_AT_BIRTH(String nameAtBirth) {
    this.NAME_AT_BIRTH = nameAtBirth;
    x500NameBuilder.addRDN(BCStyle.NAME_AT_BIRTH, nameAtBirth);
    return this;
  }

  public String getO() {
    return O;
  }

  public X500VgaNameBuilder setO(String organization) {
    O = organization;
    x500NameBuilder.addRDN(BCStyle.O, organization);
    return this;
  }

  public String getOU() {
    return OU;
  }

  public X500VgaNameBuilder setOU(String organizationUnit) {
    this.OU = organizationUnit;
    x500NameBuilder.addRDN(BCStyle.OU, organizationUnit);
    return this;
  }

  public String getPLACE_OF_BIRTH() {
    return PLACE_OF_BIRTH;
  }

  public X500VgaNameBuilder setPLACE_OF_BIRTH(String placeOfBirth) {
    this.PLACE_OF_BIRTH = placeOfBirth;
    x500NameBuilder.addRDN(BCStyle.PLACE_OF_BIRTH, placeOfBirth);
    return this;
  }

  public String getPOSTAL_ADDRESS() {
    return POSTAL_ADDRESS;
  }

  public X500VgaNameBuilder setPOSTAL_ADDRESS(String postalAddress) {
    this.POSTAL_ADDRESS = postalAddress;
    x500NameBuilder.addRDN(BCStyle.POSTAL_ADDRESS, postalAddress);
    return this;
  }

  public String getPOSTAL_CODE() {
    return POSTAL_CODE;
  }

  public X500VgaNameBuilder setPOSTAL_CODE(String postalCode) {
    this.POSTAL_CODE = postalCode;
    x500NameBuilder.addRDN(BCStyle.POSTAL_CODE, postalCode);
    return this;
  }

  public String getPSEUDONYM() {
    return PSEUDONYM;
  }

  public X500VgaNameBuilder setPSEUDONYM(String pseudonym) {
    this.PSEUDONYM = pseudonym;
    x500NameBuilder.addRDN(BCStyle.PSEUDONYM, pseudonym);
    return this;
  }

  public String getSERIALNUMBER() {
    return SERIALNUMBER;
  }

  public X500VgaNameBuilder setSERIALNUMBER(String serialNumber) {
    this.SERIALNUMBER = serialNumber;
    x500NameBuilder.addRDN(BCStyle.SERIALNUMBER, serialNumber);
    return this;
  }

  public String getSN() {
    return SN;
  }

  public X500VgaNameBuilder setSN(String serialNumber) {
    this.SN = serialNumber;
    x500NameBuilder.addRDN(BCStyle.SN, serialNumber);
    return this;
  }

  public String getST() {
    return ST;
  }

  public X500VgaNameBuilder setST(String stateOrProvince) {
    this.ST = stateOrProvince;
    x500NameBuilder.addRDN(BCStyle.ST, stateOrProvince);
    return this;
  }

  public String getSTREET() {
    return STREET;
  }

  public X500VgaNameBuilder setSTREET(String street) {
    this.STREET = street;
    x500NameBuilder.addRDN(BCStyle.STREET, street);
    return this;
  }

  public String getSURNAME() {
    return SURNAME;
  }

  public X500VgaNameBuilder setSURNAME(String surname) {
    this.SURNAME = surname;
    x500NameBuilder.addRDN(BCStyle.SURNAME, surname);
    return this;
  }

  public String getT() {
    return T;
  }

  public X500VgaNameBuilder setT(String title) {
    T = title;
    x500NameBuilder.addRDN(BCStyle.T, title);
    return this;
  }

  public String getTELEPHONE_NUMBER() {
    return TELEPHONE_NUMBER;
  }

  public X500VgaNameBuilder setTELEPHONE_NUMBER(String telephoneNumber_idattn) {
    this.TELEPHONE_NUMBER = telephoneNumber_idattn;
    x500NameBuilder.addRDN(BCStyle.TELEPHONE_NUMBER, telephoneNumber_idattn);
    return this;
  }

  public String getUID() {
    return UID;
  }

  public X500VgaNameBuilder setUID(String userId_LDAP) {
    this.UID = userId_LDAP;
    x500NameBuilder.addRDN(BCStyle.UID, userId_LDAP);
    return this;
  }

  public String getUNIQUE_IDENTIFIER() {
    return UNIQUE_IDENTIFIER;
  }

  public X500VgaNameBuilder setUNIQUE_IDENTIFIER(String uniqueIdentifier) {
    this.UNIQUE_IDENTIFIER = uniqueIdentifier;
    x500NameBuilder.addRDN(BCStyle.UNIQUE_IDENTIFIER, uniqueIdentifier);
    return this;
  }

  public String getUnstructuredAddress() {
    return UnstructuredAddress;
  }

  public X500VgaNameBuilder setUnstructuredAddress(String unstructuredAddress) {
    UnstructuredAddress = unstructuredAddress;
    x500NameBuilder.addRDN(BCStyle.UnstructuredAddress, unstructuredAddress);
    return this;
  }

  public String getUnstructuredName() {
    return UnstructuredName;
  }

  public X500VgaNameBuilder setUnstructuredName(String unstructuredName) {
    UnstructuredName = unstructuredName;
    x500NameBuilder.addRDN(BCStyle.UnstructuredName, unstructuredName);
    return this;
  }

  public X500Name build()
  {
    return x500NameBuilder.build();
  }
}

Like this:
    X500Name subject = new X500VgaNameBuilder()
        .setC("AU")
        .setO("The Legion of the Bouncy Castle")
        .setL("Melbourne")
        .setST("Victoria")
        .setEmailAddress("feedback-crypto@bouncycastle.org")
        .setCN("Common Name")
        .build();

Then
 PKCS10CertificationRequest certRequest =
        createPKCS10CertificationRequest(subject, "SHA1withRSA", keyPair);
    JcaPKCS10CertificationRequest jcaCertRequest =
        new JcaPKCS10CertificationRequest(certRequest.getEncoded()).setProvider("BC");

But if you need to add custom attributes, then you need an ASN1ObjectIdentifier for the builder inside the builder I posted, considering the BCStyle._ parameters are just ASN1ObjectIdentifiers.
For example,
public static final ASN1ObjectIdentifier CN = new ASN1ObjectIdentifier("2.5.4.3");


text:
Q: What would happen if I changed permissions of 'Program Files (x86)' folder on Windows 10?
*

*What if I went ahead and added "Everyone" in 'Program Files (x86)'s permissions tab and gave 'Everyone' full access?

*and if I deleted every other permission than 'Everyone'?

A: In the normal course of events this is impossible, but there exist hacks
that could enable it.
After you succeed, Windows will become unusable.
You will need to reinstall Windows from scratch.

A:
What if I went ahead and added "Everyone" in 'Program Files (x86)'s
permissions tab and gave 'Everyone' full access?
and if I deleted every other permission than 'Everyone'?

This folder is owned by "All Application Packages" and the security permissions cannot natively be changed (I just tried on a test machine).
In the regular use of a computer, there has not been a need to change these permissions, so I suggest you do not try this.
If you mess up your computer, it will need a major repair. Messed up registries normally mean reinstalling Windows.


text:
Q: Can I create Dynamic Column Names in DB2? I two tables, one table contains the names of columns, the other table contains the actual data that I need to display in a report. The data and columns are linked by a column key.
Is there a way to build a select statement that can use the column name from the column table for the actual temp table column?
Something like this;
Select A.value AS B.ColumnName

Simply put Can I create a table column name based on the value in another table in sql?

A: You can´t do it without using dynamic SQL as mentioned question that can be useful for you.
SQL Server: How to set column alias from another table during select?


text:
Q: Loading different view port based on input parameter Currently, we use an embedded tomcat, to start up ext-js application locally.
The Ext.application contains below code that loads the view port:
var viewPort = Ext.create('Ext.container.Viewport', {
     layout  : 'fit',
        items: [
           Ext.create('Ext.tab.Panel', {
                items: [
                    Ext.create('Tab 1', {title: ' Tab 1'}),
                    Ext.create('Tab 2', {title: ' Tab 2'}),
                 ],

            }),
        ]
  });

Can I load the tab2, above in the panel on condition basis. How can I configure say an option, some where in the web-application that loads tab2 only if the option is set?
For better clarification, something like -
// load tab 1
if (optionSet) {
 // then load tab 2
}

Is this even possible? Thanks!

A: See if this snippet helps you:
var items = [{
     xtype:'tab1'
    ,title:'Tab 1'
}];
if(condition) {
    items.push({
         xtype:'tab2'
        ,title:'Tab 2'
    });
}
var viewPort = Ext.create('Ext.container.Viewport',{
     layout:'fit'
    ,items:[{
         xtype:'tabpanel'
        ,items:items
    }]
});


text:
Q: Save spreadsheet as a csv file in given folder I need a spreadsheet from my root folder to be saved as a csv file in a specific given folder.
With the help of members, I was able to merge multiple CSV files into a single sheet and delete the same contents from multiple rows, now I want to save this sheet from my root folder as a CSV file in my given folder.

  /* Retrieve the desired folder */
  var myFolder = DriveApp.getFolderById('1niUw2-');

  /* Get all spreadsheets that resided on that folder */
  var spreadSheets = myFolder.getFilesByType(MimeType.CSV);

  /* Create the new spreadsheet that you store other sheets */
  var newSpreadSheet = SpreadsheetApp.create("Merge Sheets");

  /* Iterate over the spreadsheets over the folder */
  while(spreadSheets.hasNext()) {

    var sheet = spreadSheets.next();

    var file = DriveApp.getFileById(sheet.getId());
    var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
    var newSheet = newSpreadSheet.getActiveSheet();
for (var i=0;i<csvData.length;i++) {
        newSheet.appendRow(csvData[i]);
      }
     var data = newSheet.getDataRange();
  var values = data.getValues();
 for (var i=values.length -1; i >=1; i--){
    if (values[i][0] == "Titel"){
   newSheet.deleteRow(i+1);
      }
 }
myFolder.createFile('MERGED',newSheet,MimeType.CSV);
  } }

I need this edited spreadsheet file " Merged sheet " from my root folder into my given folder as a csv file.

A: *

*You want to merge the CSV files in one CSV file.

*

*The CSV files are in a specific folder.

*You want to create the merged CSV file in the specific folder.

*When the CSV data is merged, you want to delete the rows which has Titel in the column "A".

*You want to achieve this using Google Apps Script.

If my understanding is correct, how about this modification? Please think of this as just one of several answers.
In your script, each CSV data is put to the new Spreadsheet using appendRow(), and then, when the value of column "A" is Titel, the row is deleted. In this case, I thought that the process cost might become high. So how about the following flow?
Flow:

*

*Retrieve each CSV file from the specific folder.

*Parse the file as the CSV data.

*From the CSV data, delete the rows which has Titel in the column "A".

*Put the CSV data to an array.

*After all CSV files were processed from above 2 to 4, the array including the CSV data is exported as a CSV file to the specific folder.

When above flow is reflected to the script, it becomes as follows.
Modified script:
function myFunction() {
  var myFolder = DriveApp.getFolderById('###'); // Please set the folder ID including the CSV files.

  var csvFiles = myFolder.getFilesByType(MimeType.CSV);
  var data = [];
  while (csvFiles.hasNext()) {
    var csvFile = csvFiles.next();
    var file = DriveApp.getFileById(csvFile.getId());
    var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()).filter(function(row) {return row[0] != "Titel"});
    Array.prototype.push.apply(data, csvData);
  }
  myFolder.createFile('MERGED', data.map(function(row) {return row.join(",")}).join("\n"), MimeType.CSV);
}

Note:

*

*If you want to create the merged CSV data as a Spreadsheet, please put the following script to the last line of the function of myFunction.
SpreadsheetApp.create("Merge Sheets").getSheets()[0].getRange(1, 1, data.length, data[0].length).setValues(data);

References:

*

*Array.prototype.push

*map()

*filter()
If I misunderstood your question and this was not the direction you want, I apologize.
Edit:
Pattern 1:
If you want to delete the 1st row of each CSV data, how about the following modification? Please modify my above modified script as follows.

From:

var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()).filter(function(row) {return row[0] != "Titel"});

To:

var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
csvData.shift();

or
var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
if (data.length > 0) csvData.shift();

*

*Below modified script leaves only the 1st row at the 1st CSV file.


text:
Q: Google search via AppleScript I would like to make a Google search with an AppleScript. The code looks like this:
set search to text returned of (display dialog "Google Search" buttons {"OK"} default answer {""})
open location ("https://www.google.de/#q=" & search)

The problem is, how can I change the spaces to a +?

A: Here's a subroutine for replacing characters:

on replace_chars(this_text, search_string, replacement_string)
  set AppleScript's text item delimiters to the search_string
  set the item_list to every text item of this_text
  set AppleScript's text item delimiters to the replacement_string
  set this_text to the item_list as string
  set AppleScript's text item delimiters to ""
  return this_text
end replace_chars

Source: http://www.macosxautomation.com/applescript/sbrt/sbrt-06.html
Between those two lines of AppleScript, insert the following:
set search to replace_chars(search," ","+")


text:
Q: Problem with clock picker direction in RTL bootstrap I use ClockPicker library in my project with RTL version of bootstrap. When click on input clock picker loads but with wrong direction.
Wrong direction in clockpicker
how to solve it, thanks a lot.

A: add direction in popover class in your html or picker css
.popover { direction: rtl; }


text:
Q: Hibernate - function to check if persistent properties have changed Is there a built-in function which can check if any property of a persistent entity differs from the one of a detached instance?
Else I will have to write a generic criteria function to check it myself using the class meta data.


text:
Q: Probability and standard error I need help to get started with this question.
A grain mill manufactures 100 pound bags of flour for sale in restaurant supply warehouses. Historically the weights of bags of flour manufactured at the mill were normally distributed with a mean of 100 pounds and a standard deviation of 15 pounds.
A. what is the probability that the weight of a randomly selected bag of flour falls between 94 and 106 pounds?
B. if samples of 36 bags are taken, what is the standard error of the mean?
c. what is the probability that a sample of 36 bags of four has a mean weight between 94 and 106 pounds?


text:
Q: string array with a if from an array string created with a FROM i want to include an IF condition to it but bigquery is telling me that cannot be possible. I am having the following error Syntax error: Expected ")" but got keyword FROM whenever i am trying to do something like:
SELECT
  IF(TRUE, STRING_AGG(x, ' | ')
  FROM UNNEST([
    IF(FALSE, 'new_customer', NULL),
    IF(TRUE, 'new_customer_vertical', NULL),
    IF(TRUE, 'new_customer_expedition', NULL),
    IF(FALSE, 'new_customer_pandapro', NULL)
  ]) AS x, NULL)

If i remove the IF condition, is passing
SELECT
  STRING_AGG(x, ' | ')
  FROM UNNEST([
    IF(FALSE, 'new_customer', NULL),
    IF(TRUE, 'new_customer_vertical', NULL),
    IF(TRUE, 'new_customer_expedition', NULL),
    IF(FALSE, 'new_customer_pandapro', NULL)
  ]) AS x

A: Not sure below is what you try to do, but you looks want a scalar subquery in IF() function.
SELECT IF(TRUE, -- some condition
          (SELECT STRING_AGG(x, ' | ')
             FROM UNNEST([
               IF(FALSE, 'new_customer', NULL),
               IF(TRUE, 'new_customer_vertical', NULL),
               IF(TRUE, 'new_customer_expedition', NULL),
               IF(FALSE, 'new_customer_pandapro', NULL)
             ]) AS x
          ), -- IF true
          NULL) -- IF false


text:
Q: How can I build a shell script to build a Docker-Compose Image and start up the Docker container if successful? I'm trying to write a shell script that will attempt to build a Docker-Compose image, then if that's successful, start up the Docker container with it by doing a Docker-Compose up -d.
In the second step, I load some JSON files into Mongo, but then if there's a problem with that step, I want want to stop all Docker services and print out an error message saying "Could not start Docker service because there was a problem seeding the DB."
My problem is that I don't know how to check if the image was created successfully in the first step. (I want to stop and print out a message saying that there were errors in the build.)
I think I can figure out something that checks if both services are running at the end, but I'm wondering if there is a way to print out the name of the problematic JSON file that couldn't load.
Does anyone have a similar script that I can use or modify for my own use?

A: My understanding is you are trying to branch out the logic of the script based on whether the build command was a success. Here is what you can do:

cat create-image.sh

#!/bin/bash

docker build -q -t test-image .

if [ $? -eq 0 ]; then
   echo OK, images created
else
   echo FAIL, image not created
   exit 1
fi

echo "...DOING OTHER THINGS... (like docker-compose up)"

Let me know if this is what you were looking for.

A: You don't need a script if you just want to build images before starting containers:
docker-compose --build up
If you must use a script, you can certain call the above command and check its exit code. There is no need to call docker build individually for every service in the docker-compose file.


text:
Q: How to properly implement a function with variadic number of std::string_view arguments? Desired behavior
What I basically want is to create a function like this:
void func(std::string_view... args)
{
    (std::cout << ... << args);
}

It should be able to work only with classes that are convertible to std::string_view.
Example:
int main()
{
    const char* tmp1 = "Hello ";
    const std::string tmp2 = "World";
    const std::string_view tmp3 = "!";

    func(tmp1, tmp2, tmp3, "\n");

    return 0;
}

should print: Hello World!

Accomplished behavior
So far, I got here:
template<typename... types>
using are_strings = std::conjunction<std::is_convertible<types, std::string_view>...>;

template<typename... strings, class = std::enable_if_t<are_strings<strings...>::value, void>>
void func(strings... args)
{
    (std::cout << ... << args);
}

int main()
{
    const char* tmp1 = "Hello ";
    const std::string tmp2 = "World";
    const std::string_view tmp3 = "!";

    func(tmp1, tmp2, tmp3, "\n");

    return 0;
}

This actually works as expected, but there is still one big problem.

Problem
Only classes that are convertible to std::string_view can be used in this function and that's great.
However, even though classes are convertible, they are not converted to std::string_view!
This leads to needless copying of data(for example when std::string is passed as argument).

Question
Is there a way to force implicit conversion of variadic arguments to std::string_view?

Note
I know about std::initializer_list, but I would like to keep function call simple, without {}.

A: namespace impl{
  template<class...SVs>
  void func(SVs... svs){
    static_assert( (std::is_same< SVs, std::string_view >{} && ...) );
    // your code here
  }
}
template<class...Ts,
  std::enable_if_t< (std::is_convertible<Ts, std::string_view >{}&&...), bool > =true
>
void func( Ts&&...ts ){
  return impl::func( std::string_view{std::forward<Ts>(ts)}... );
}

or somesuch.

A: #include <string_view>
#include <utility>

template <typename>
using string_view_t = std::string_view;

template <typename... Ts>
void func_impl(string_view_t<Ts>... args)
{
    (std::cout << ... << args);
}

template <typename... Ts>
auto func(Ts&&... ts)
    -> decltype(func_impl<Ts...>(std::forward<Ts>(ts)...))
{
    return func_impl<Ts...>(std::forward<Ts>(ts)...);
}

DEMO

A: If you simply want to avoid needless copying of data, use a forward reference and then perform explicit casts (if still required). This way no data is copied but forwarded (in your main.cpp example, all params are passed as const references)
template <typename... strings,
          class = std::enable_if_t<are_strings<strings...>::value, void>>
void func(strings&&... args) {
  (std::cout << ... << std::string_view{args});
}

A: Not exactly what you asked... but if you can set a superior limit for a the length of args... (9 in following example) I propose the following solution: a foo<N> struct that inherit N func() static function that accepting 0, 1, 2, ..., N std::string_view.
This way, func() function are accepting what is convertible to std::string_view and all argument are converted to std::string_view.
That is exactly
void func(std::string_view... args)
{ (std::cout << ... << args); }

with the difference that func() functions are static methods inside foo<N>, that there is a limit in args... length and that there is a func() method for every supported length.
The full example is the following.
#include <string>
#include <utility>
#include <iostream>
#include <type_traits>

template <std::size_t ... Is>
constexpr auto getIndexSequence (std::index_sequence<Is...> is)
   -> decltype(is);

template <std::size_t N>
using IndSeqFrom = decltype(getIndexSequence(std::make_index_sequence<N>{}));

template <typename T, std::size_t>
struct getType
 { using type = T; };

template <typename, typename>
struct bar;

template <typename T, std::size_t ... Is>
struct bar<T, std::index_sequence<Is...>>
 {
   static void func (typename getType<T, Is>::type ... args)
    { (std::cout << ... << args); }
 };

template <std::size_t N, typename = std::string_view,
          typename = IndSeqFrom<N>>
struct foo;

template <std::size_t N, typename T, std::size_t ... Is>
struct foo<N, T, std::index_sequence<Is...>> : public bar<T, IndSeqFrom<Is>>...
 { using bar<T, IndSeqFrom<Is>>::func ...; };

int main ()
 {
    const char* tmp1 = "Hello ";
    const std::string tmp2 = "World";
    const std::string_view tmp3 = "!";

    foo<10u>::func(tmp1, tmp2, tmp3, "\n");
 }

A: Make it a two-stage production:
template <class... Args>
std::enable_if_t<... && std::is_same<Args, std::string_view>()>
func(Args... args)
{
    (std::cout << ... << args);
}

template <class... Args>
auto func(Args&&... args)
-> std::enable_if_t<... || !std::is_same<std::decay_t<Args>, std::string_view>(),
    decltype(func(std::string_view(std::forward<Args>(args))...))>
{
    func(std::string_view(std::forward<Args>(args))...);
}


text:
Q: usar username en user_id cuando quiero buscar el perfil de un usuario mediante la url: http://localhost/personajes/user_profile.php?id=1
Pero lo que estoy intentando hacer es buscarlo desde
http://localhost/personajes/user_profile.php?id=Nombre_Apellido
Este es mi código para obtener el usuario
function find_user_by_id($id){
        try{
            $find_user = $this->db->prepare("SELECT * FROM `characters` WHERE characterID = ?");
            $find_user->execute([$id]);
            if($find_user->rowCount() === 1){
                return $find_user->fetch(PDO::FETCH_OBJ);
            }
            else{
                return false;
            }
        }
        catch (PDOException $e) {
            die($e->getMessage());
        }
    }

Y aquí el código del user_profile.php
<?php
require 'includes/init.php';
    if(isset($_GET['id'])){
        $user_data = $user_obj->find_user_by_id($_GET['id']);
    }

?>

¿Cómo puedo realizar este cambio?

A: En tu función find_user_by_id($id) tiene una consulta a una tabla de la base de datos donde el criterio de comparación es characterID que es la columna en tu tabla characters que tiene el id.
si lo que deseas es buscar por el nombre solo debes cambiar el nombre de la columna que hace la selección del criterio  ejemplo nombre
pudiera quedarte así
$find_user = $this->db->prepare("SELECT * FROM `characters` WHERE nombre= ?");

debes tener en cuenta que deberías definir una nueva función y definir nuevas variables, para que tenga lógica tu código y sea fácil de leer, el ejemplo que te di es solo para que puedas usar el mismo código sin mucho cambio


text:
Q: Flickering horizontal black lines, streaks on screen (Kali, Tails), not present in other OS As the subject, I have flickering, horizontal small black lines (thin, and also not a complete line, rather small streaks). Please see the video evidence for better explanation..
This is a fresh kali install, only update and upgrade was executed. I am multi booting Linux Mint Mate and Linux Lite as well and neither of these have the same problem, this only occurs in TailsOS, and Kali on bare metal. Only sudo apt update, sudo apt upgrade was executed, then I also installed the latest
Neofetch here for system info
xserver-xorg-video-intel is already the newest version (2:2.99.917+git20200714-1+b1).
The flickering black lines are changing positions as well when I change the display settings.
I have tried changing almost every combination of acceptable resolutions, refresh rates, only the place and length of the black lines change. Any ideas how to fix it? Should I try to build Mesa from the latest source? I'm kind of novice on Linux still, just getting into it, and this is the first actual issue I face with it. Any help is appreciated.
> └─$ glxinfo | grep OpenGL
>OpenGL vendor string: Intel Open Source Technology Center
>OpenGL renderer string: Mesa DRI Intel(R) HD Graphics 4000 (IVB GT2)
>OpenGL core profile version string: 4.2 (Core Profile) Mesa 20.3.4
>OpenGL core profile shading language version string: 4.20
>OpenGL core profile context flags: (none)
>OpenGL core profile profile mask: core profile
>OpenGL core profile extensions:
>OpenGL version string: 3.0 Mesa 20.3.4
>OpenGL shading language version string: 1.30
>OpenGL context flags: (none)
>OpenGL extensions:
>OpenGL ES profile version string: OpenGL ES 3.0 Mesa 20.3.4
>OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.00
>OpenGL ES profile extensions:

xdpyinfo | grep version
version number:    11.0
X.Org version: 1.20.11


text:
Q: Autoload classes from different folders This is how I autoload all the classes in my controllers folder,
# auto load controller classes
    function __autoload($class_name)
    {
        $filename = 'class_'.strtolower($class_name).'.php';
        $file = AP_SITE.'controllers/'.$filename;

        if (file_exists($file) == false)
        {
            return false;
        }
        include ($file);
    }

But I have classes in models folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to models/ (but isn't this repetitive??)?
Thanks.
EDIT:
these are my classes file names in the controller folder:
class_controller_base.php
class_factory.php
etc

these are my classes file names in the model folder:
class_model_page.php
class_model_parent.php
etc

this is how I name my controller classes class usually (I use underscores and lowcaps),
class controller_base
{
...
}

class controller_factory
{
...
}

this is how I name my model classes class usually (I use underscores and lowcaps),
class model_page
    {
    ...
    }

    class model_parent
    {
    ...
    }

A: I have to mention something about "good" autoload scripts and code structure, so read the following CAREFULLY

Keep in Mind:

*

*Classname === Filename

*Only ONE class per file

e.g: Example.php contains
class Example {}

*

*Namespace === Directory structure

e.g: /Path1/Path2/Example.php matches
namespace Path1\Path2;
class Example {}

*

*There SHOULD be a Root-Namespace to avoid collisions

e.g: /Path1/Path2/Example.php with root:
namespace APP\Path1\Path2;
class Example {}

*

*NEVER use manually defined path or directory lists, just point the loader to the top most directory

*Keep the loader AS FAST AS POSSIBLE (because including a file is expensive enough)

With this in mind, i produced the following script:
function Loader( $Class ) {
    // Cut Root-Namespace
    $Class = str_replace( __NAMESPACE__.'\\', '', $Class );
    // Correct DIRECTORY_SEPARATOR
    $Class = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, __DIR__.DIRECTORY_SEPARATOR.$Class.'.php' );
    // Get file real path
    if( false === ( $Class = realpath( $Class ) ) ) {
        // File not found
        return false;
    } else {
        require_once( $Class );
        return true;
    }
}

Where to place it..

*

*/Loader.php <-- there goes the loader

*/Controller/... <-- put ur stuff here

*/Model/... <-- or here, etc

*/...

Remeber:

*

*if you use a root namespace, the loader has to be in this namespace too

*you may prefix $Class to match your needs (controller_base {} -> class_controller_base.php)

*you may change __DIR__ to an absolute path containing your class files (e.g. "/var/www/classes")

*if you don't use namespaces, all files has to be in the same directory together with the loader (bad!)

Happy coding ;-)

A little review at other answers:
THIS IS JUST MY PERSONAL OPINION - NO OFFENSE INTENDED!
https://stackoverflow.com/a/5280353/626731
@alex good solution, but don't make you class names pay for bad file structures ;-)
this is job for namespaces
https://stackoverflow.com/a/5280510/626731 @Mark-Eirich it works, but its pretty nasty/ugly/slow/stiff[..] style to do it this way..
https://stackoverflow.com/a/5284095/626731 @tealou for his problem to be solved this is the most clear approach so far :-) ..
https://stackoverflow.com/a/9628060/626731 @br3nt this reflects my point of view, but please(!) .. dont use strtr!! .. which brings me to:
https://stackoverflow.com/a/11866307/626731 @Iscariot .. to you, a little "you-know-bullshit-benchmark:
Time        sprintf preg_replace strtr    str_replace v1 str_replace v2
08:00:00 AM 1.1334  2.0955       48.1423  1.2109         1.4819
08:40:00 AM 1.0436  2.0326       64.3492  1.7948         2.2337
11:30:00 AM 1.1841  2.5524       62.0114  1.5931         1.9200
02:00:00 PM 0.9783  2.4832       52.6339  1.3966         1.4845
03:00:00 PM 1.0463  2.6164       52.7829  1.1828         1.4981
Average     1.0771  2.3560       55.9839  1.4357         1.7237

Method         Times Slower (than sprintf)
preg_replace   2.19
strtr          51.97
str_replace v1 1.33
str_replace v2 1.6

Source: http://www.simplemachines.org/community/index.php?topic=175031.0
Questions?.. (But he is in fact right about full path including)
https://stackoverflow.com/a/12548558/626731 @Sunil-Kartikey
https://stackoverflow.com/a/17286804/626731 @jurrien
NEVER loop in time critical environment! Don't search for files on os! - SLOW
https://stackoverflow.com/a/21221590/626731 @sagits .. much better than Marks ;-)

A: I see you are using controller_***** and model_***** as a class naming convention.
I read a fantastic article, which suggests an alternative naming convention using php's namespace.
I love this solution because it doesn't matter where I put my classes.  The __autoload will find it no matter where it is in my file structure.  It also allows me to call my classes whatever I want.  I don't need a class naming convention for my code to work.
You can, for example, set up your folder structure like:

*

*application/

*

*controllers/

*

*Base.php

*Factory.php

*models/

*

*Page.php

*Parent.php

Your classes can be set up like this:
<?php
namespace application\controllers;
class Base {...}

and:
<?php
namespace application\models;
class Page {...}

The autoloader could look like this (or see 'a note on autoloading' at the end):
function __autoload($className) {
    $file = $className . '.php';
    if(file_exists($file)) {
        require_once $file;
    }
}

Then... you can call classes in three ways:
$controller = new application\controllers\Base();
$model = new application\models\Page();

or,
<?php
use application\controllers as Controller;
use application\models as Model;

...

$controller = new Controller\Base();
$model = new Model\Page();

or,
<?php
use application\controllers\Base;
use application\models\Page;

...

$controller = new Base();
$model = new Page();

EDIT - a note on autoloading:
My main auto loader looks like this:
// autoload classes based on a 1:1 mapping from namespace to directory structure.
spl_autoload_register(function ($className) {

    # Usually I would just concatenate directly to $file variable below
    # this is just for easy viewing on Stack Overflow)
        $ds = DIRECTORY_SEPARATOR;
        $dir = __DIR__;

    // replace namespace separator with directory separator (prolly not required)
        $className = str_replace('\\', $ds, $className);

    // get full name of file containing the required class
        $file = "{$dir}{$ds}{$className}.php";

    // get file if it is readable
        if (is_readable($file)) require_once $file;
});

This autoloader is a direct 1:1 mapping of class name to directory structure; the namespace is the directory path and the class name is the file name.  So the class application\controllers\Base() defined above would load the file www/application/controllers/Base.php.
I put the autoloader into a file, bootstrap.php, which is in my root directory.  This can either be included directly, or php.ini can be modified to auto_prepend_file so that it is included automatically on every request.
By using spl_autoload_register you can register multiple autoload functions to load the class files any which way you want.  Ie, you could put some or all of your classes in one directory, or you could put some or all of your namespaced classes in the one file.  Very flexible :)

A:
function autoload($className)
{
//list comma separated directory name
$directory = array('', 'classes/', 'model/', 'controller/');

//list of comma separated file format
$fileFormat = array('%s.php', '%s.class.php');

foreach ($directory as $current_dir)
{
    foreach ($fileFormat as $current_format)
    {

        $path = $current_dir.sprintf($current_format, $className);
        if (file_exists($path))
        {
            include $path;
            return ;
        }
    }
}
}
spl_autoload_register('autoload');

A: Here is my solution,
/**
     * autoload classes
     *
     *@var $directory_name
     *
     *@param string $directory_name
     *
     *@func __construct
     *@func autoload
     *
     *@return string
    */
    class autoloader
    {
        private $directory_name;

        public function __construct($directory_name)
        {
            $this->directory_name = $directory_name;
        }

        public function autoload($class_name)
        {
            $file_name = 'class_'.strtolower($class_name).'.php';

            $file = AP_SITE.$this->directory_name.'/'.$file_name;

            if (file_exists($file) == false)
            {
                return false;
            }
            include ($file);
        }
    }

    # nullify any existing autoloads
    spl_autoload_register(null, false);

    # instantiate the autoloader object
    $classes_1 = new autoloader('controllers');
    $classes_2 = new autoloader('models');

    # register the loader functions
    spl_autoload_register(array($classes_1, 'autoload'));
    spl_autoload_register(array($classes_2, 'autoload'));

I'm not sure whether it is the best solution or not but it seems to work perfectly...
What do you think??

A: You should name your classes so the underscore (_) translates to the directory separator (/). A few PHP frameworks do this, such as Zend and Kohana.
So, you name your class Model_Article and place the file in classes/model/article.php and then your autoload does...
function __autoload($class_name)
{
    $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';

    $file = AP_SITE.$filename;

    if ( ! file_exists($file))
    {
        return FALSE;
    }
    include $file;
}

Also note you can use spl_autoload_register() to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions.

If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

Edit

Note : __autoload has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Please refer to PHP documentation for more details. http://php.net/manual/en/function.autoload.php

A: My version of @Mark Eirich answer:
    function myload($class) {
      $controllerDir = '/controller/';
      $modelDir = '/model/';
      if (strpos($class, 'controller') !== false) {
        $myclass = $controllerDir . $class . '.php';
      } else {
        $myclass = $modelDir . $class . '.inc.php';
      }
          if (!is_file($myclass)) return false;
          require_once ($myclass);

    }

    spl_autoload_register("myload");

In my case only controller class have the keyword in their name, adapt it for your needs.

A: Simpliest answer I can give you without writing down those complex codes and even without using the namespace (if this confuses you)
Sample Code. Works 100%.
function __autoload($class_name){
$file = ABSPATH . 'app/models/' . $class_name . '.php';
if(file_exists($file)){
    include $file;
}else{
    $file = ABSPATH . 'app/views/' . $class_name . '.php';
    if(file_exists($file)){
        include $file;
    }else{
        $file = ABSPATH . 'app/controllers/' . $class_name . '.php';
        include $file;
    }
}

I guess the logic is explainable itself. Cheers mate! Hope this helps :)

A: Here's what I'd do:
function __autoload($class_name) {
    $class_name = strtolower($class_name);
    $filename = 'class_'.$class_name.'.php';

    if (substr($class_name, 0, 5) === 'model') {
        $file = AP_SITE.'models/'.$filename;
    } else $file = AP_SITE.'controllers/'.$filename;

    if (!is_file($file)) return false;
    include $file;
}

As long you name your files consistently, like class_controller_*.php and class_model_*.php, this should work fine.

A: Everyone is is coping and pasting things from code they got off the internet (With the exception of the selected answer).  They all use String Replace.
String Replace is 4 times slower than strtr.  You should use it instead.
You should also use full paths when including classes with autoloading as it takes less time for the OS to resolve the path.

A: __autoload() function should not be use because it is not encourged. Use spl_autoload(), spl_autoload_register() instead. __autoload() just can load one class but spl_autoload() can get more than 1 classes. And one thing more, in future __autoload() may deprecated. More stuff can be find on http://www.php.net/manual/en/function.spl-autoload.php

A: Altough this script doesn't have the name convention and this thread is already a bit old, in case someone is looking of a possible answer, this is what I did:
function __autoload($name) {
    $dirs = array_filter(glob("*"), 'is_dir');

    foreach($dirs as $cur_dir) {
        dir_searcher($cur_dir, $name);
    }

}

function dir_searcher($cur_dir, $name) {

    if(is_file("$cur_dir/$name.php")) {
        require_once "$cur_dir/$name.php";
    }

    $dirs = array_filter(glob($cur_dir."/*"), 'is_dir');
    foreach($dirs as $cdir) {
        dir_searcher("$cdir", $name);
    }
}

not sure if it is really optimal, but it searches through the folders by reading dir recursively. With a creative str_replace function you can get your name cenvention.

A: I use this. Basically define your folder structure (MVC etc) as a constant in a serialised array. Then call the array in your autoload class. Works efficiently for me.
You could obviously create the folder array using another function but for MVC you may as well type it in manually.
For this to work you need to call your classes ...... class.classname.php
  //in your config file
    //define class path and class child folders
    define("classPath","classes");
    define("class_folder_array", serialize (array ("controller", "model", "view")));

  //wherever you have your autoload class
    //autoload classes
    function __autoload($class_name) {
    $class_folder_array = unserialize (class_folder_array);
    foreach ($class_folder_array AS $folder){
        if(file_exists(classPath."/".$folder.'/class.'.$class_name.'.php')){require_once classPath."/".$folder.'/class.'.$class_name.'.php';break;}
    }

    }


text:
Q: Red Hat: How to sftp upload and git push with 755/644 and apache:apache rights/owner? I have apache web server, linux, ssh access with sudo. And many troubles with editing, uploading, pushing, committing there. Because there are set 755 for dirs, 644 for files, and apache:apache owner
Question: how to upload, push with such permissions or with smallest changes of config. May be using extra soft will be helpful.
Current work process; 1. changing rights/owners 2. making file operations 3. changing rights/owners back or 1. making file operations directly via bash with sudo 2. setting correct rights/owners


text:
Q: No Wifi Adapter Found on HP Laptop - 18.04 My laptop:
HP 15-DA1006NT 5MM06EA i5-8265U 4GB 1TB 128GB SSD 2GB MX110 15.6 FreeDOS
I installed 18.04 Ubuntu both with 3rd party hardware and without them. I have same problem:
"No wifi adapter found"
iwconfig
**
eno1 no wireless extension
lo no wireless extension
**
When I wrote "rfkill", I didn't have any results or error.
I looked the old topics and populer solution is bcmwl-kernel-source. However, when I wrote bcmwl-kernel-source to ınstall to termınal, I took this error:
unable to locate package bcmwl-kernel-source
Then I researced this error's solution.
Installing Broadcom Wireless Drivers for ubuntu 15.04
This topic doesn't work for me.
and I've tried a few more things like that, but it didn't work. What are your solution suggestions?


text:
Q: Leaflet angular. can i write a loop inside an array? I have the following code
$scope.paths = {
    p1: {
        color: '#008000',
        weight: 8,
        latlngs: [
            { lat: Number(route.data[0].stops[0].latitude), lng: Number(route.data[0].stops[0].longitude) },
            { lat: Number(route.data[0].stops[1].latitude), lng: Number(route.data[0].stops[1].longitude) },
            { lat: Number(route.data[0].stops[2].latitude), lng: Number(route.data[0].stops[2].longitude) }
        ],
}};

For this I grab data from a .json file using angular's $http service and store it as 'route'. Then i use 'route' to grab data from the json and pass it to the latlngs array.
latlngs: [
    { lat: Number(route.data[0].stops[0].latitude), lng: Number(route.data[0].stops[0].longitude) },
    { lat: Number(route.data[0].stops[1].latitude), lng: Number(route.data[0].stops[1].longitude) },
    { lat: Number(route.data[0].stops[2].latitude), lng: Number(route.data[0].stops[2].longitude) }
],

This works as expected.
But i have to write a new line for each item in my json array. Can i do a loop inside this array to grab the data? Something like:
latlngs: [
    for (var i = 0, i <route.data[0].stops, i++){
        {
            lat: Number(route.data[0].stops[i].latitude),
            lng: Number(route.data[0].stops[i].longitude)
        }
    }
]


text:
Q: Not redirecting the nodejs page while adding heavy data in mongodb I am adding heavy data to mongo db through looping as below
function updateData() {
    for (l = 0; l < 10000 ,l++) {
        db.fbpost.update({pagename:page,'post.id': postsId},{'post.data': posts.data[l]}},{upsert: true},function (err,data){
            if (err) {
                 console.log('could not fetch post from after update', page, err);
            }
        })
    }
}

i am calling this function from a post method link while the above code inserting data into db, and parallely  i was unable to redirect other links, it was blocked by the loop. So i tried to make the for loop to run async like below but could not help even it was looping continuously without allowing me to access the other page.
function forloop(){
            if(i < posts.data.length){
                i++;
                setTimeout(forloop(), 0);
            }
        }
        forloop();

A: I suppose you have sent the Location header. Check if you have missed response.end();.
var http = require('http');
http.createServer(function (req, res) {

  res.writeHead(302, {'Location': 'http://google.com'});
  res.end(); // End the response

}).listen(1337);


text:
Q: Symfony LDAP Authentication and MySQL user provider I am trying to use the following:
1) form_login_ldap just for user authentification
2) A custom UserProvider for retrieving user roles from a MySQL database
Everything seems to work fine: I am able to login, the roles are used etc.
As soon as I change the roles in the database, isEqualTo() kicks in - the user is redirected to the login page. There the browser hangs in an endless loop. After using tcpdump I realized that form_login_ldap is trying to authenticate the user without a password.
I think I am generally missing the point how the password will be handled in this scenario. My UserProvider can't retrieve an (encrypted) password as he is querying MySQL and the user is authenticated using LDAP.
If the "refreshUser function of my UserProvider returns a new user object with the new roles, the password seems to be lost.
If within the UserProvider i just modify the array of roles for the user, the web application does not recognize that and old roles apply (I guess the session must be updated?).
How are form_login_ldap and my UserProvider supposed to interact? How do I make sure that upon "refreshUser" the password is still available?
What am I missing for my general picture?


text:
Q: Changing html5 canvas buffer size and webgl Changing html5 canvas buffer size i.e. canvas.width and canvas.height seems to change the canvas display dimentions on ios 8 and ios 9 when using webgl, in desktop browsers seems to be ok:
https://jsfiddle.net/psqvur80/

I tried viewport settings, but with no luck.
How can I keep the display dimentions while changing buffer size of the canvas ?

A: sigh ... looks like a bug in iOS Safari. Filed a bug
I haven't found a direct workaround yet. One crappy workaround is to change the size of the container for a moment.
iv.style.width = "401px";
requestAnimationFrame(function() {
  iv.style.width = "400px";
});

I think I haven't noticed this issue since I always make the canvas the same size as it's being displayed.
Is there some reason your use case requires the canvas to be smaller? It's clearly a bug in Safari. Just asking if you can work around it


text:
Q: Float right & left don't work properly On my new site www.unicmedia.nl/case/oranje i have a problem with my floats. In IE they work (for the first time lol) but FF and CH are way off.
I tried literally everything but can't seem to find the problem. My css code is valid according to the w3c validator.
Hope you guys can find something that is wrong!
Screen: Incorrect Correct

A: The div with id=content=right should have some width. Please set it to 600px.
Note that a parent element should float if one of its child elements floats. Thats is why the div#content appears outside its children. To make the parent element not float you can use the clearfix hack.
http://www.positioniseverything.net/easyclearing.html

A: Looking at that page, I see a div with the class content-left. It looks floated left, but it's also got 25px of margin-left. Is that what you mean by "way off"?
Your content-right div is also floated left. Are you trying to make two columns? The problem might be that your right content has so much information that it's trying to be full-width so not floating. If you force it to be a specific number of pixels or percent, that should make that work. Try making your content-left width: 20% and your content-right width:80%.
Better yet, start with someone else's cross-browser column layout.


text:
Q: Radio Button within a table with Material Design I'm actually trying to insert a radio button group within a table component of material design and angular 6.
So in the examples of Material design official website there is a table with checkboxes but what I want is to do the same with radio button for each element of the table.
I tried to do it with a *ngFor directive but i can't access the ELEMENT_DATA array even if it's a global const.
import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

  <ng-container matColumnDef="select">

      <mat-checkbox (change)="$event ? masterToggle() : null"
                    [checked]="selection.hasValue() && isAllSelected()"
                    [indeterminate]="selection.hasValue() && !isAllSelected()">
      </mat-checkbox>

      <mat-checkbox (click)="$event.stopPropagation()"
                    (change)="$event ? selection.toggle(row) : null"
                    [checked]="selection.isSelected(row)">
      </mat-checkbox>

  </ng-container>

  <ng-container matColumnDef="position">
     No.
     {{element.position}}
  </ng-container>

  <ng-container matColumnDef="name">
     Name
     {{element.name}}
  </ng-container>

  <ng-container matColumnDef="weight">
     Weight
     {{element.weight}}
  </ng-container>

  <ng-container matColumnDef="symbol">
     Symbol
     {{element.symbol}}
  </ng-container>

So with this code i want to remove the checkboxes and replace it with radio buttons.
what i tried is to put :
<mat-radio-group>
   <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
</mat-radio-button>

and like I said before I can't access my Array ELEMENT_DATA. I also tried to change it with dataSource.length, but nothing do.
thanks for helping.

A: you can add the mat-radio-group to mat-cell and use ngModel:
<ng-container matColumnDef="radio">
  <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
  <mat-cell *matCellDef="let row">
    <mat-radio-group [(ngModel)]="selectedPerson">
      <mat-radio-button [value]="row"></mat-radio-button>
    </mat-radio-group>
  </mat-cell>
</ng-container>

A: This is probably too late, but thought I would chime in.  I just wanted to implement this same behavior, and I found that using the SelectionModel from the CKD basically allowed me to visually replicate this behavior, even if not in a better way.
https://material.angular.io/components/table/overview#selection
It supports multi or single selection modes and you can easily put the click logic on the mat-row, along with any kind of visual styling (or even a radio button) to inform the user of the state of the current selection.

A: you can just add  inside of the td of your table and it would work. but I got no idea how to know which radio button is selected.

                                <ng-container matColumnDef="select">

                    <mat-radio-button disabled>
                    </mat-radio-button>

                    <mat-radio-button (click)="$event.stopPropagation()"
                                      (change)="$event ? selection3.toggle(row) : null"
                                      [checked]="selection3.isSelected(row)"
                                      ></mat-radio-button>

                </ng-container>

typescript
  selection3 = new SelectionModel<Instruments>(false, []);

if you work in the row section you can always use let row as I did is also handy when you want to put a routerLink on your entire row

A: Every thing you've done is correct. But, why are you trying to do *ngIf = "let i of Element_Data":
    <mat-radio-group>
        <mat-radio-button *ngIf="let i of ELEMENT_DATA" value = i></mat-radio-button>
    </mat-radio-button>.

Are you trying to do *ngFor? You can't do ' let i of Element_Data ' in *ngIf

A: ELEMENT_DATA should be a property of the core component not a constant. Otherwise you cannot access it in html part.

A: ELEMENT_DATA needs to be part of the class.
Try this:
import {Component} from '@angular/core';
import {MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'table-selection-example',
  styleUrls: ['table-selection-example.css'],
  templateUrl: 'table-selection-example.html',
})
export class TableSelectionExample {
  displayedColumns = ['select', 'position', 'name', 'weight', 'symbol'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
  selection = new SelectionModel<PeriodicElement>(true, []);

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];
}

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

A: Try replicating the code below, worked for me

                 No.

                        <mat-radio-button [value]="row" (click)="radiobuttonClick(row)" color="primary"></mat-radio-button>

            </mat-radio-group>


text:
Q: Using angular factories and services interchangeably - no error I am using a service where there should be a factory and I don't get an error.
My service returns and object when it should return a constructor function.
But my code works perfectly.
for example, the code below should not work. But it works fine:
angular.module('myApp', [])
    .service('myService', myService);

function myService(/*<dependencies go in here>*/){
   return {
     /*<object attributes in here>*/
   }
}

The correct code should be this:
angular.module('myApp', [])
    .factory('myService', myService);

function myService(/*<dependencies go in here>*/){
   return {
     /*<object attributes in here>*/
   }
}

My question is why angular allows you to use a .service when you are actually returning an object and should be using .factory

A: OK This is my answer for this interesting question.
First of all lets make sure we understand the main difference between service and factory, it will be easier after we see both implementations:
Factory:
function factory(name, factoryFn) {
    return provider(name, { $get: factoryFn });
}

Service:
function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

As we can see what factory actually is doing is getting us the object the factory functions returns.
Service in the other hand instantiates a new object using the constructor function we provided. Needless to say both are singletons.
In your example above the factory is used just like it should be, thats the best practice.
I guess the interesting part is why the service is working while his constructor function doesn't really defines a class but returns an object as well.
Here comes the tricky part, it is working because as said before using the service actually instantiate an object, in our bad practice we override the default constructor with new constructor.
Sounds confusing? here is a Fiddle that performs basically the same thing, we use new ConstructorFunc() while the ConstructorFunc() instead of defining an object and create its properties using this.prop=something is returning an object.
Maybe it is not a best practice but it is possible.
I think we better keep working with service as we used to for following the convention.
Interesting article factory vs service vs provider

A: The explicit return in your service overrides the default constructor behavior.
function factory () {

    return {
        foo: 'bar'
    };

}

console.log(factory().foo); // bar

function service () {

    this.foo = 'foo';

    return {
        foo: 'bar'
    };

}

console.log(new service().foo); // bar

Fiddle


text:
Q: IllegalAccessError: tried to access method org.apache.avro.specific.SpecificData.() Using Avro for serializing data to byte[] and deserializing data. https://cwiki.apache.org/confluence/display/AVRO/FAQ#FAQ-HowcanIserializedirectlyto/fromabytearray? shows sample usage.
SpecificDatumReader<User> reader = new SpecificDatumReader<User>(User.getClassSchema());

The above line is causing the following error
IllegalAccessError: tried to access method org.apache.avro.specific.SpecificData.<init>() from class com.abc.schema.generated.User

Any pointers to what might be going wrong here? No errors seen at compile time.

A: This is likely due to you having an older version of Avro in your classpath. To check, run your program with the -verbose:class parameter and look for instance of SpecificData in the output. Example:
 java -verbose:class -jar your_jar.jar

A: Changing the class loading from parent-first to child-first fixed this for me


text:
Q: Calling multiple WCF services return error - Disposed Object can't be used My WCF service provides  multiple services from different end points.
Currently my client app calls these methods independently as shown below:
object result1 = null;
object result2 = null;

using (OperationContextScope contextScope = new OperationContextScope((IContextChannel)ServiceInstance))
{
   MyService.AddHeaders();
   result1 =  ServiceInstance.Method1()
}

//some other processing depending on the value of result1

using (OperationContextScope contextScope = new OperationContextScope((IContextChannel)ServiceInstance))
{
   MyService.AddHeaders();
   result2 =  ServiceInstance.Method2()
}

Now, to improve performance, I tried doing the following:
using (OperationContextScope contextScope = new OperationContextScope((IContextChannel)ServiceInstance))
{
   MyService.AddHeaders();
   result1 =  ServiceInstance.Method1()
   result2 =  ServiceInstance.Method2()
}

//some other processing depending on the value of result1 && result2

But this is failing with the error: "disposed object can't be used" and in the inner exception the disposed object is ChannelService.
Can someone help me how can I combine multiple WCF service calls under one OperationContextScope?
Thanks
Aravind

A: I am not certain but this may be because your service might be single call (and/or does not support sessions). You may want to tweak with service behaviors to get this working.

A: If the intention is only to make more than 1 call within the single OperationContextScope, you may use Innerchannel of the service.
    using (OperationContextScope contextScope = new
        OperationContextScope((IContextChannel)abc.InnerChannel))
        {

            /* Add Headers */
                    MessageHeader header
            = MessageHeader.CreateHeader(
            "Service-Bound-CustomHeader",
            "http://Microsoft.WCF.Documentation",
            "Custom Happy Value."
            );

                    header = MessageHeader.CreateHeader(
                "Service-Bound-OneWayHeader",
                "http://Microsoft.WCF.Documentation",
                "Different Happy Value."
              );

            OperationContext.Current.OutgoingMessageHeaders.Add(header);

            Console.WriteLine(abc.GetData(100));
            Console.WriteLine(abc.GetDataUsingDataContract(new ServiceReference1.CompositeType()).ToString());
        }


text:
Q: Windows 10 update changes partition labels I have recently booted my dual system SuSe 42.1/Windows 10, under Windows, in order to install and use iTunes. As usual, since I use Windows rarely, the system went through an upgrade, rebooted, and the Linux grub disappeared. Further, I had difficulties in booting from USB.
After tweaking for a while and using a new installation on a usb-stick of Suse 42.2, I was able to use fdisk to find out that the labels of /swap, /home and / on three different partitions have been changed to something like WINDOWS RESERVED PARTITION and UEFI is now windows ...
The data are still there if I mount the partitions using the usb-linux but the tools do not see the system anymore. I have looked on internet and there seems to be confusion between "upgrade", such as from windows 8 to 10, which I did one year ago without any problem, and "update" as in my case i.e. update of a windows 10 system already working. I didn't find any discussion on this issue. I do not know the cause: aggressive policy of Microsoft, installation of iTunes, a virus?
I will try to see if I can revert the labels back to their previous settings, in which case some help would be appreciated, but mainly the issue here is that the usual state of affairs of Windows coexisting quietly with Linux on a machine seems to be lost. Is it no longer possible to have Windows and Linux coexisting and not affecting each other?

A: Problem solved, so far. After backing up, I started a new installation using a USB stick loaded with openSUSE 42.2.
I started the beginning and I left the partitions chosen by the software, not doing any change. I left for a meeting and I got the smoothest installation ever. The network was set correctly, software downloaded without any intervention on my side and I found coming back my system up waiting for me to log-in. Further all my settings on the user part are there.
The printout from fdisk is the following:
Disk /dev/sda: 465,8 GiB, 500107862016 bytes, 976773168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: gpt
Disk identifier: A1FA4776-F20C-4E88-9353-F97E31C4F3B0
Dispositivo     Start      Fine   Settori   Size Tipo
/dev/sda1        2048    206847    204800   100M EFI System
/dev/sda2      206848   2050047   1843200   900M Windows recovery environment
/dev/sda3     2050048   2312191    262144   128M Microsoft reserved
/dev/sda4     2312192 392095735 389783544 185,9G Microsoft basic data
/dev/sda5   392095744 393017343    921600   450M Windows recovery environment
/dev/sda6   393017344 397238271   4220928     2G Microsoft basic data
/dev/sda7   397238272 439185407  41947136    20G Microsoft basic data
/dev/sda8   439185408 934809599 495624192 236,3G Microsoft basic data
/dev/sda9   934809600 976773119  41963520    20G Windows recovery environment

Despite the labels, still there as set by the Microsoft update, /dev/sda1 is now an EFI boot set up by Linux, was UEFI Windows before, /dev/sda7 is /, /dev/sda6 is swap and /dev/sda8 is /home
The printout of df -k is the following:
File system    1K-blocchi     Usati Disponib. Uso% Montato su
devtmpfs          1950580         0   1950580   0% /dev
tmpfs             1964664     46292   1918372   3% /dev/shm
tmpfs             1964664      2344   1962320   1% /run
tmpfs             1964664         0   1964664   0% /sys/fs/cgroup
/dev/sda7        20973568   5308908  15484596  26% /
/dev/sda7        20973568   5308908  15484596  26% /.snapshots
/dev/sda7        20973568   5308908  15484596  26% /srv
/dev/sda7        20973568   5308908  15484596  26% /var/cache
/dev/sda7        20973568   5308908  15484596  26% /var/lib/machines
/dev/sda7        20973568   5308908  15484596  26% /boot/grub2/x86_64-efi
/dev/sda7        20973568   5308908  15484596  26% /var/tmp
/dev/sda7        20973568   5308908  15484596  26% /var/lib/pgsql
/dev/sda7        20973568   5308908  15484596  26% /tmp
/dev/sda7        20973568   5308908  15484596  26% /var/lib/mysql
/dev/sda7        20973568   5308908  15484596  26% /var/spool
/dev/sda7        20973568   5308908  15484596  26% /var/lib/named
/dev/sda7        20973568   5308908  15484596  26% /var/lib/mariadb
/dev/sda7        20973568   5308908  15484596  26% /usr/local
/dev/sda7        20973568   5308908  15484596  26% /opt
/dev/sda7        20973568   5308908  15484596  26% /var/log
/dev/sda7        20973568   5308908  15484596  26% /var/lib/mailman
/dev/sda7        20973568   5308908  15484596  26% /var/lib/libvirt/images
/dev/sda7        20973568   5308908  15484596  26% /boot/grub2/i386-pc
/dev/sda1           98304     41295     57009  43% /boot/efi
/dev/sda7        20973568   5308908  15484596  26% /var/opt
/dev/sda7        20973568   5308908  15484596  26% /var/crash
/dev/sda8       243792168 223358848  19425688  92% /home
tmpfs              392936        16    392920   1% /run/user/1000

Quick and dirty, I badly need the machine working, and, for my present needs, it is. As soon as I have time I will try to do better. To my knowledge, mounting the partitions by hand, I got to know that /dev/sda7 is Btrfs and /dev/sda8 is ext4.
I hope this can be useful to others somehow.


text:
Q: Implementing a Boolean function using NOR gates with maximum 4 ports I need to implement a Boolean function using NOR gates only. The minimized function written as PoS is:
f(a, b, c, d) = (a+b)(a+c+d)(b+c+d')(a+c'+d')(a'+c'+d)
I used double negation and DeMorgan's laws to make the following (unfinished) circuit in the Hades simulator:

Now, the problem is that Hades has NOR gates that have a maximum of 4 ports, and I have 5 separate sums I need to input in the NOR gate. Any ideas how to solve this problem?

A: You can cascade them. Send two of the inputs into a NOR gate and then invert the result to send it into the last one.


text:
Q: jQuery getScript returns an parse error exception I'm trying to load two scripts with the $.getScript function of getting Google Map script, then after that is loaded, I get another script (goMap) which makes map applets easily to be made.
However, when loaded, the first script of getting Google Map API is good, then the second script returns a parse error and shows this:

TypeError: 'undefined' is not a constructor'

Yet, I don't know where that is referencing from or which line, I think it must be trying to execute the Geocoder on this file (first line after (function($){:

http://www.pittss.lv/jquery/gomap/js/jquery.gomap-1.3.2.js

Here is my code:
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function()
{
    $.getScript('../js/gomap.js').done(function()
    {
            // this never gets called
            alert('gomap loaded');
    }).fail(function(jqxhr, settings, exception)
    {
        alert(exception); // this gets shown
    });
}).fail(function()
{
    alert('failed to load google maps');
});

I tried changing the AJAX settings to set async to false, but it didn't help at all.

A: The error is caused by the fact that the Google Maps API expects to be loaded in the head, using <script src="http://maps.google.com/maps/api/js?sensor=true"></script>.
If you cannot do that for some reason, there's still hope. The Google Maps API does not work, because it uses document.write to inject a dependency in the page. To get the code to work, you can overwrite the native document.write method.
Demo: http://jsfiddle.net/ZmtMr/
var doc_write = document.write; // Remember original method;
document.write = function(s) {$(s).appendTo('body')};
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function() {
    $.getScript('../js/gomap.js').done(function() {
        alert('gomap loaded');
        document.write = doc_write; // Restore method
    }).fail(function(jqxhr, settings, exception) {
        alert(exception); // this gets shown
        document.write = doc_write; // Restore method
    });
}).fail(function() {
    alert('failed to load google maps');
});

A: @lolwut
Try
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function()
{
    alert(11);
    $.getScript('http://www.pittss.lv/jquery/gomap/js/jquery.gomap-1.3.2.js').done(function()
    {
            // this never gets called
            alert('gomap loaded');
    }).fail(function(jqxhr, settings, exception)
    {
        alert(exception); // this gets shown
    });
}).fail(function()
{
    alert('failed to load google maps');
});

If this works then you're relative path ../js/gomap.js is wrong!


text:
Q: Show data in listview Android code I have added data in sqlite now I want to show
It in listview.I have shown it in text view but only one record show in text view.I want to show it in text view. Can anyone help me?

A: Fetch data from sqlite to a cursor and iterate data, then add each rows to arraylist by creating custom item. Then create custom adapter and pass the arraylist to it. Then set adapter to tge listview