text:
Q: Gson Java - Child class from JSON I have an abstract class for configuration files, which can be extended by lots of other classes. I managed to get the system working for writing it to JSON, but now I need the load function.
Here's the general Configuration class:
public class Configuration {

    public boolean load(){
        FileReader reader = new FileReader(this.getClass().getSimpleName() + ".json");
        Gson gson = new Gson();
        gson.fromJson(reader, this.getClass());
        reader.close();
        /** Doesn't give an error, but doesn't set any info to the child class */
    }

    public boolean save(){
        FileWriter writer = new FileWriter(this.getClass().getSimpleName() + ".json");
        Gson gson = new Gson();
        gson.toJson(this, writer);
        writer.close();
        /** This all works fine. */
    }

}

Here's an example of an extending class:
public class ExampleConfig extends Configuration {

    private static transient ExampleConfig i = new ExampleConfig();
    public static ExampleConfig get() { return i; }

    @Expose public String ServerID = UUID.randomUUID().toString();

}

In my main class I would do:
ExampleConfig.get().load();
System.out.println(ExampleConfig.get().ServerID);

This does not give any errors, but neither is the class loaded from the JSON. It keeps outputting a random UUID even though I want to load one from the JSON file. I'm probably getting the wrong instance of the child class, but I'm out of ideas on how to fix this. (Using this in gson.fromJson(.....); does not work.

A: You're missing to assign a read value to your configuration instance. Java cannot support anything like this = gson.fromJson(...), and Gson can only return  new values and cannot patch existing ones. The below is a sort of Gson hack, and please only use it if it's really a must for you. Again, I would strongly recommend you to redesign your code and separate your configuration objects and configuration readers/writers -- these are just two different things that conflict from the technical perspective. As a result of refactoring, you could have, let's say, once you get an instance of your configuration, just delegate it to a writer to persist it elsewhere. If you need it back, then just get an instance of a reader, read the configuration value and assign it to your configuration (configurations are singletons, I remember), like:
final ConfigurationWriter writer = getConfigurationWriter();
writer.write(ExampleConfig.get());
...
final ConfigurationReader reader = getConfigurationReader();
ExampleConfig.set(reader.read(ExampleConfig.class));

At least this code does not mix two different things, and makes the result of reader.read be explicitly read and assigned to your configuration singleton.
If you're fine to open the gate of evil and make your code work because of hacks, then you could use Gson TypeAdapterFactory in order to cheat Gson and patch the current configuration instance.
abstract class Configuration {

    private static final Gson saveGson = new Gson();

    public final void load()
            throws IOException {
        try ( final FileReader reader = new FileReader(getTargetName()) ) {
            // You have to instantiate Gson every time (unless you use caching strategies) in order to let it be *specifically* be aware of the current
            // Configuration instance class. Thus you cannot make it a static field.
            final Gson loadGson = new GsonBuilder()
                    .registerTypeAdapterFactory(new TypeAdapterFactory() {
                        // A Gson way to denote a type since Configuration.class may not be enough and it also works with generics
                        private final TypeToken<Configuration> configurationTypeToken = new TypeToken<Configuration>() {
                        };

                        @Override
                        @SuppressWarnings("deprecation") // isAssignableFrom is deprecated
                        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
                            // Checking if the type token represents a parent class for the given configuration
                            // If yes, then we cheat...
                            if ( configurationTypeToken.isAssignableFrom(typeToken) ) {
                                // The map that's artificially bound as great cheating to a current configuration instance
                                final Map<Type, InstanceCreator<?>> instanceCreators = bindInstance(typeToken.getType(), Configuration.this);
                                // A factory used by Gson internally, we're intruding into its heart
                                final ConstructorConstructor constructorConstructor = new ConstructorConstructor(instanceCreators);
                                final TypeAdapterFactory delegatedTypeAdapterFactory = new ReflectiveTypeAdapterFactory(
                                        constructorConstructor,
                                        gson.fieldNamingStrategy(),
                                        gson.excluder(),
                                        new JsonAdapterAnnotationTypeAdapterFactory(constructorConstructor)
                                );
                                // Since the only thing necessary here is to define how to instantiate an object
                                // (and we just give it an already-existing instance)
                                // ... just delegate the job to Gson -- it would think as if it's creating a new instance.
                                // Actually it won't create one, but would "patch" the current instance
                                return delegatedTypeAdapterFactory.create(gson, typeToken);
                            }
                            // Otherwise returning a null means looking up for an existing type adapter from how Gson is configured
                            return null;
                        }
                    })
                    .create();
            // The value is still loaded to nowhere, however.
            // The type adapter factory is tightly bound to an existing configuration instance via ConstructorConstructor
            // This is actually another code smell...
            loadGson.fromJson(reader, getClass());
        }
    }

    public final void save()
            throws IOException {
        try ( final FileWriter writer = new FileWriter(getTargetName()) ) {
            saveGson.toJson(this, writer);
        }
    }

    private String getTargetName() {
        return getClass().getSimpleName() + ".json";
    }

    private static Map<Type, InstanceCreator<?>> bindInstance(final Type type, final Configuration existingConfiguration) {
        return singletonMap(type, new InstanceCreator<Object>() {
            @Override
            public Object createInstance(final Type t) {
                return t.equals(type) ? existingConfiguration : null; // don't know if null is allowed here though
            }
        });
    }

}

I hope that the comments in the code above are exhaustive. As I said above, I doubt that you need it just because of intention to have a bit nicer code. You could argue that java.util.Properties can load and save itself. Yes, that's true, but java.util.Properties is open to iterate over its properties by design and it can always read and write properties from elsewhere to anywhere. Gson uses reflection, a method of peeking the fields under the hood, and this is awesome for well-designed objects. You need some refactoring and separate two concepts: the data and data writer/reader.


text:
Q: How to return observations which are %in% a vector? # My vector:
day <- c("day", "night")

Observation
Column #1
Column #2

1
Day
Evening

2
Evening
Morning

3
Night
Evening

4
Morning
Night

5
Morning
Morning

6
Night
Day

How can I return observations in which columns contain at least one value in my vector?

Observation
Column #1
Column #2

1
Day
Morning

3
Night
Evening

4
Morning
Night

6
Night
Day

Data Frame
df = data.frame(
obs = c(1:6),
Column1 = c("Day","Evening","Night","Morning","Morning","Night"),
Column2 = c("Evening","Morning","Evening","Night","Morning","Day")
)

A: We use if_any in filter to filter the rows having at least a match for the columns that have "Column" in column names
library(dplyr)
df %>%
   filter(if_any(starts_with("Column"),  ~ toupper(.x) %in% toupper(day)))

-output
  obs Column1 Column2
1   1     Day Evening
2   3   Night Evening
3   4 Morning   Night
4   6   Night     Day

redpajama_set_name: RedPajamaStackExchange


text:
Q: Consequences of violation of independence assumption in ANOVA test Can you please explain me what is the consequences of violation of independence assumption in ANOVA test?
I couldn't visualize it.
Does Cochran Theorem relates to independence assumption ?

A: The independence assumption allows us to use simple statistical concepts to quantify the evidence for/against the null hypothesis. That is, independence (among the other assumptions) allows us to say that the errors from the mean are normally distributed. Then we can use the Cochran Theorem to quantify the p-value (how extreme the actual data is given the null hypothesis), which we then use to make a decision.
The Cochran Theorem is the workhorse theorem for ANOVA and requires independence, so yes there is a very strong relation.


text:
Q: How to achive below result using provided array? I'm builing notifications component where I want to sort notification by dates and display them.
Can someone give me a hint to achieve that?
How can I do it over a following array ?

Array :
   notificationRows: Array(25)
    0:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191431"
    info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]"
    key: "1.11.191431"
    time: "2022-05-17 16:54:21"
    type: "transfer"
    [[Prototype]]: Object
    unread: false
    [[Prototype]]: Object
    1:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191430"
    info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]"
    key: "1.11.191430"
    time: "2022-05-17 14:52:39"
    type: "transfer"
    [[Prototype]]: Object
    unread: false
    [[Prototype]]: Object
    2:
    notificationRow:
    fee: "20 TEST"
    id: "1.11.191427"
    info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]"
    key: "1.11.191427"
    time: "2022-05-17 14:34:15"
    type: "transfer"
    [[Prototype]]: Object
    unread: false

My expected result is :

A: Sort the array with descending dates, use sort() and getTime() for dates.
And in the return of your component, use map() to return an HTML element for each array item.
example using a function component
function App(props) {
  const {arr} = props;
  arr.sort((a, b) => {
    const date1 = new Date(a.notificationRow.time);
    const date2 = new Date(b.notificationRow.time);
    return date2.getTime() - date1.getTime();
  })

  return (
    {
      arr.map((elem, i) => (
whatever you want here
))
    }
  )
}

A: you can use array.sort() function in JavaScript to sort by date.

const notificationRows = [
    {
      notificationRow: {
        fee: "20 TEST",
        id: "1.11.191431",
        info: "[userlink=demo3], send 0.00021 TEST to ,[userlink=demo1]",
        key: "1.11.191431",
        time: "2022-05-17 16:54:21",
        type: "transfer",
        unread: false
      }
    },
    {
      notificationRow: {
        fee: "20 TEST",
        id: "1.11.191430",
        info: "[userlink=demo3], send 0.012 TEST to ,[userlink=demo1]",
        key: "1.11.191430",
        time: "2022-05-17 14:52:39",
        type: "transfer",
        unread: false
      }
    },
    {
      notificationRow: {
        fee: "20 TEST",
        id: "1.11.191427",
        info: "[userlink=demo3], send 0.0021 TEST to ,[userlink=demo1]",
        key: "1.11.191427",
        time: "2022-05-17 14:34:15",
        type: "transfer",
        unread: false
      }
    }
  ];
    const sorted = constarr.sort(
    (a, b) =>
// return sorted date by newest. if want sort by old use Date.parse(a.notificationRow.time) - Date.parse(b.notificationRow.time)
      Date.parse(b.notificationRow.time) - Date.parse(a.notificationRow.time)
  );
  console.log("sorted", sorted);

Since you use react and you may use this sorted by time notifications to display, set this sorted arrays to the react state and render accordingly.


text:
Q: How to perform a smooth downscaling of background images in Qt styles? As default, Qt uses a very simple, quick and ugly way of scaling images, Qt::FastTransformation, probably a nearest neighbor interpolation or something very similar.
When dealing with a QPixmap, one can choose a visually better scaling, for example,
pixmap = pixmap.scaledToHeight(height, Qt::SmoothTransformation);

However, what can we do if the image is not in a QPixmap object, but simply a background of a button, or some other widget?
For example, the following is a very simple way of creating an automatically resizing, fully customized button, well suited for a resolution-independent application, when used with layouts and setStretch().
ui->pushButton->setStyleSheet(
    "QPushButton { border-image: url(:/img/button.png) 0 0 0 0 stretch stretch; }"
    "QPushButton:checked { border-image: url(:/img/button_checked.png) 0 0 0 0 stretch stretch; }"
    "QPushButton:pressed { border-image: url(:/img/button_pressed.png) 0 0 0 0 stretch stretch; }"
    "QPushButton:checked:pressed { border-image: url(:/img/button_checked_pressed.png) 0 0 0 0 stretch stretch; }"
    );

I used border-image instead of background-image due to a deficiency in the Qt style sheets.
How can I have a smoother scaling with images used in style sheets?
Implementing the same thing with pixmaps is much less elegant. I'll have to always catch resize events, recompute the new sizes of all my widgets, and repaint them manually.
Edit:
Interestingly, the smooth scaling works with stylesheets if the image is being enlarged, but not when it is shrinked.
In the following example, in the first row, a 32*32 icon is used, and in the second row, a uniform grid larger than 2000*2000.

A: Internally, Qt uses QPainter to draw the styles, and QPainter uses bilinear interpolation when drawing scaled pixmaps. This has a major drawback from quality perspective when the downscaling factor is small enough, see this bug report for example. For best quality, the background source image should always be within [0.5, 2.0] factor of the target size. AFAICT there is no easy way out of this limitation.


text:
Q: Codeigniter next_row() returns null Im trying to get the next row everytim ei run the function but it always returns 0
Model
function getNextMuziek($id)
    {
        $this->db->where('id', $id);
        $this->db->limit(1);
        $query = $this->db->get('muziek')->num_rows() == 1;
        return $query->next_row();
    }

A: According to the documentation, next_row() is to be used to navigate through a result set. This will not serve your purposes. If you want your function to return the next row after the row specified by $id, the easiest thing would be to use a greater than comparison and return the first row. You could modify your code to
$query = $this->db->where('id >', $id)->limit(1)->get('muziek');
if ($query->num_rows() == 1) {
    return $query->row();
}


text:
Q: Base64 encoded string to Public Key using RSA From C# to Java I am converting legacy application from .net to java.  Legacy method using encryption using public key.
string text = "<base64encodedstring here>";
IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(text);
AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.get_RsaPkcs1());
CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(buffer, 3);
IBuffer buffer2 = CryptographicBuffer.ConvertStringToBinary(data, 0);
IBuffer buffer3 = CryptographicEngine.Encrypt(cryptographicKey, buffer2, null);
byte[] array;
CryptographicBuffer.CopyToByteArray(buffer3, ref array);
//return CryptographicBuffer.EncodeToBase64String(buffer3);

Here is my Java code to convert the given text into the public key
public static PublicKey getKey(String key) throws Exception{
    try{
        byte[] byteKey = Base64.getDecoder().decode(key);

        X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
        KeyFactory kf = KeyFactory.getInstance("RSA","BC");

        return kf.generatePublic(X509publicKey);

    }
    catch(Exception e){
       throw e;
    }

}

Here is my main method
public static void main(String[] args) {
    String text = "base64encodedstring";
    try {
        Security.addProvider(new BouncyCastleProvider());
        decode(text);
        PublicKey pubKey=getKey(text);
        byte[] input = "plaintext".getBytes();
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] cipherText = cipher.doFinal(input);
        System.out.println("cipher: " + new String(cipherText));

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

But When I try to get the public key I get the exception below
java.security.spec.InvalidKeySpecException: encoded key spec not recognised
    at org.bouncycastle.jcajce.provider.asymmetric.util.BaseKeyFactorySpi.engineGeneratePublic(Unknown Source)
    at org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePublic(Unknown Source)
    at java.security.KeyFactory.generatePublic(Unknown Source)
    at com.test.EncryptionUtil.getKey(EncryptionUtil.java:38)
    at com.test.EncryptionUtil.main(EncryptionUtil.java:60)

Am I doing something wrong?  I am new to cryptography.
With some more research I found the way how it is doing in C#, but not able to convert it into java
 public static CryptographicKey GetCryptographicPublicKeyFromCert(string strCert)

    {

        int length;

        CryptographicKey CryptKey = null;

        byte[] bCert = Convert.FromBase64String(strCert);

        // Assume Cert contains RSA public key

        // Find matching OID in the certificate and return public key

        byte[] rsaOID = EncodeOID("1.2.840.113549.1.1.1");

        int index = FindX509PubKeyIndex(bCert, rsaOID, out length);

        // Found X509PublicKey in certificate so copy it.

        if (index > -1)

        {

            byte[] X509PublicKey = new byte[length];

            Array.Copy(bCert, index, X509PublicKey, 0, length);

            AsymmetricKeyAlgorithmProvider AlgProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);

            CryptKey = AlgProvider.ImportPublicKey(CryptographicBuffer.CreateFromByteArray(X509PublicKey));

        }

        return CryptKey;

    }

What is the purpose of EncodeOID method and how it can be achieved in Java. The link below explains the creation of base64 encoded public key string and decode it in C#
http://blogs.msdn.com/b/stcheng/archive/2013/03/12/windows-store-app-how-to-perform-rsa-data-encryption-with-x509-certificate-based-key-in-windows-store-application.aspx

A: There is no direct way to read microsoft Capi1PublicKey into java. I first converted the Capi1PublicKey to  X509-encoded public key in WinRT. then I used created key in java.

A: Obviously the key isn't X509-encoded. Find out how it is encoded and use an appropriate KeySpec.

A: C# uses AsymmetricAlgorithmNames.get_RsaPkcs1 you need to find equivalent for your JAVA code.
You may want to have look at this Import Public RSA Key From Certificate


text:
Q: Zipping dictionary to pandas I am trying to zip my dictionary into a panda's data frame, and do it by the keys that are in the dictionary and not manually:
import pandas as pd

dict = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
columns = list(dict.keys())   # ['A', 'B']
manual_results = list(zip(dict['A'], dict['B'])) #  [('a1', 'b1'), ('a2', 'b2'), ('a3', 'b3')]
df = pd.DataFrame(manual_results, columns=columns)

I wish to create the results without the need to explicitly write the name of each key (dict['A'], dict['B'] etc). Any Ideas?

A: There is no need to zip it.  Pandas can create a dataframe directly from a dict:
import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d)
print(df)

    A   B
0  a1  b1
1  a2  b2
2  a3  b3

reference: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.from_dict.html

Note: You can also orient it the other way (so the dict keys become the row index instead of colums) ...
import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame.from_dict(d,orient='index')
print(df)

    0   1   2
A  a1  a2  a3
B  b1  b2  b3

A: There is no need to use zip() as pd.DataFrame natively expect the parameter data to be a dict that can contain Series, arrays, etc.
You can simply do as follows:
import pandas as pd
d = {'A': ['a1', 'a2', 'a3'], 'B': ['b1', 'b2', 'b3']}
df = pd.DataFrame(d)

Which output:
    A   B
0  a1  b1
1  a2  b2
2  a3  b3


text:
Q: Angular 2 - Unable to copy values from one object to another using typescript for I have a employee object and i want to copy some of the values in to a new object. I'm using Typescript for to copy them, but i'm getting error.
Typescript code:
employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
  ];
  companies : any;
  for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
  console.log("Companies",this.companies);

Plunker code link:
https://plnkr.co/edit/CnBR4JouNhzH3DWm7QCo?p=preview

A: You need to run that code in a function. Here I'm running it in the constructor. You can only declare variables in the class.
also you need to initialize companies with an empty array.
  employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
  ];
  companies : any = [];

  constructor(){
    for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
   console.log("Companies",this.companies);

  }

A: There are couple of issues,
you have to write code iside some function
constructor(){
    for (let c of this.employee) {
      this.companies.push({
        empDesc: c.empDesc,
        empId: c.empId
      })
    };
  console.log("Companies",this.companies);
 }

and initialize companies property,
Check out updated the Plunker!!
Hope this helps!!

A: This worked for me:
public employee: any[] = [];
public companies: any[] = [];

ngOnInit() {
    this.employee = [
    { "empId": "59C", "empDesc": "Software","location":"Dallas"},
    { "empId": "AMI", "empDesc": "Hardware", "location":"San Francisco"}
    ];

    for (let c of this.employee) {
      let temp = [{
        empDesc: c.empDesc,
        empId: c.empId
      }]
      this.companies.push(temp);
    };
    console.log("Companies",this.companies);
}


text:
Q: How to copy Specific folders from source folder to destination folder Good Evening.
I am new to writing scripts and I am trying to copy specific folder from a source directory to a destination directory.
OS- Linux Ubuntu
I have listed all the required folders in an excel and reading that dataframe and converting the same to list using the following script.

folderName = pd.read_excel(
    "/Users/aravindv/Documents/Programming/Bitbucket-Prod/working_linux_scripts/Folder_copy/data/fnames.xlsx")
folderName = folderName.Folders.values.tolist()
print(folderName)

I only want the folders and its subdirectories/files in folderName to be copied in the destination folder.
I have written the following code however what I notice is that only the content of that folder in folderName is copied. I want the folder and its sub folder copied in the destination directory. Could you please help

# importing the modules
import os
import shutil
import pandas as pd

# Providing the folder path
src = '/Users/aravindv/Documents/Programming/Bitbucket-Prod/working_linux_scripts/Folder_copy/src'
dest = '/Users/aravindv/Documents/Programming/Bitbucket-Prod/working_linux_scripts/Folder_copy/dest'

# Fetching the list of all the files

data = os.listdir(src)
print(data)

folderName = pd.read_excel(
    "/Users/aravindv/Documents/Programming/Bitbucket-Prod/working_linux_scripts/Folder_copy/data/fnames.xlsx")
folderName = folderName.Folders.values.tolist()
print(folderName)

for folder in folderName:
    if folder in data:
        src = f'/Users/aravindv/Documents/Programming/Bitbucket-Prod/working_linux_scripts/Folder_copy/src/{folder}'
        try:
            shutil.copytree(src, dest, symlinks=False, ignore=None, copy_function=shutil.copy2,
                            ignore_dangling_symlinks=False,
                            dirs_exist_ok=True)
        except FileExistsError:
            print(f"folder {folder} exist")

# def cpf():
#     for dt in data:
#
#
#
# print("Files are copied successfully")

Folder Structure


text:
Q: Difference between trunk and subscriber line Being new to telecommunication, this definition confused me as to what is the difference between a trunk and subscriber line. Please help! :)
definition of folded and non-folded network

A: Its not a particularly well explained term in that reference, but all it really means is that in a folded network the network  is closed - in other words subscribers can only makes calls to other subscribers of the same network.
A non folded or open network means that subscribers can make calls to people outside the network being discussed.
Its mostly useful as a planning tool.
In real life, most network are not closed or folded for obvious reasons, although local exchanges might be modelled as closed or folded for planning and dimensioning purposes.
Dimensioning in telecoms is very important as telecoms equipment is traditionally expensive so most networks are blocking in one way or another - i.e. they are not engineered to allow every subscriber make a call at the same time as this would be a very rare occurrence and it would be costly to have much of the equipment sitting idle at all other times.
There is a better definition than the one you reference above with some diagrams etc here: http://www.newagepublishers.com/samplechapter/001222.pdf


text:
Q: Post multiple data from Android to PHP web service So far I can send one set of data from Android to PHP web service. I'm hoping to send an array, and have a for loop in the web service. Is that possible? Is that a good solution? In this project, I'm trying to sync SQLite with MySQL.
Here's my code
String username, userid;
    username = "Kate";
    userid = "3";
    String data = "";

    try {
        data = URLEncoder.encode("username", "UTF-8") + "="
                + URLEncoder.encode(username, "UTF-8");
        data += "&" + URLEncoder.encode("userid", "UTF-8") + "="
                + URLEncoder.encode(userid, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String text = "";
    BufferedReader reader = null;

    try {

        URL url = new URL(
                address);

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(
                conn.getOutputStream());
        wr.write(data);
        wr.flush();

        // Get the response
        reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        text = sb.toString();
    } catch (Exception ex) {

    } finally {
        try {
            reader.close();
        } catch (Exception ex) { }
    }

And this
<?php
include '../inc/connect.php';
include '../inc/class/mysql.class.php';

$name   = urldecode($_POST['username']);
$user   = urldecode($_POST['userid']);

print " ==== POST DATA =====
Name  : $name
Email : $email
User  : $user
Pass  : $pass";

$ins = mysql_query("INSERT INTO users (UserName, FullName) VALUES ('$name','$user')") or die(mysql_error());
if ($ins) {
    echo json_encode(array("result"=>"success","result_txt"=>"Branch sucessfully added."));
    exit();
}
?>

A: You could send the input as JSON and then get PHP to decode it.
So you'd encode all your data in the android app and send it as one big encoded string, possibly using URI encoding or Base64, then in the PHP do:
$data = json_decode($_POST['data']);

If you use base64 then you'd do:
$data = json_decode(base64_decode($_POST['data']));

If you just send it as one string
$data = json_decode(urldecode($_POST['data']));


text:
Q: Why doesn't strlen() count the byte of the terminating NUL-character, when the NUL-character is defined to be part of a string? I know that strlen() does not count the NUL-terminating character with. I really know that this is a fact. Thus, this question is NOT about asking for why strlen() might "presumably" not return the right string length, which is already asked and answered alot well here on StackOverflow, f.e. in this thread, or this one.
So lets go ahead to my question:
In ISO/IEC 9899:1990 (E); 7.1.1., is stated:

A string is a contiguous sequence of characters terminated by and including the first null character.

What is the reason, why strlen() deviate from this formed standard, and does not "want" to accept a string with its NUL-terminating character?
Why?

A: Because you would expect this pseudocode's assertion to hold true:
str1 = "foo"
str2 = "bar"
str3 = concatenate(str1, str2)

Assert strlen(str1) + strlen(s2) == strlen(str3)

If terminating '\0' was counted by strlen, above assertion would not hold, which would be much more of overall headache, than what the current C string behavior is. More importantly, it would in my opinion be quite unintuitive and illogical.

A: Taking your doubt as a reasonable point we can state that: The C-string consists of two parts:

*

*the string's useful content ("the text");

*the null terminating character;

The null terminating character is purely a technical measure for determination of the end of the string by the C-originated library functions. Still, if one types a declaration:
char * str = "some string";

they logically would rather expect its length to be 11 which is as many as they can see in this statement. Hence the strlen() value yields only the length of the part 1. of the string.

A: Not really an answer to your question, but consider this example:
char string[] = "string";
printf("sizeof: %zu\n", sizeof(string));
printf("strlen: %zu\n", strlen(string));

This prints
sizeof: 7
strlen: 6

So sizeof counts the \0, but strlen doesn't.
Questions like this, that ask why a certain age-old decision was made one way and not another way, are hard to answer.  I can say that it's perfectly obvious to me, anyway, that strlen should count just the real, "interesting" characters that are in the string, and ignore the \0 at the end that merely terminates it. I'm used to accounting for the \0  separately.  I imagine it would have been considerably more of a nuisance overall if strlen had been defined the other way.  But I can't prove this with convincing arguments, and I've been using strlen with its current definition for so long that I'm probably hopelessly biased; I might be saying "it's perfectly obvious to me that..." even if strlen's definition were quite wrong.

A: There is a difference between the physical, stored representation of a C style string and the logical representation of a C style string.
The physical representation, how the string is actually stored in memory or other media includes the null character. The null character is included when discussing the physical representation because it take up an additional piece of storage. In order to be a C style string the null character must be stored.
However the logical representation of a string does not include the null character. The logical representation of a string includes only the text characters that the programmer is wanting to manipulate.
I suspect that the null character, a value of binary zero, was chosen because of the original ASCII character set defined a character value of zero as the NULL character. Part of the lower values among the various teletype control codes, it seems to be the least likely ASCII character that may appear in text. See ASCII Character Codes.
Another nice quality of using a binary zero as the string terminator is that is the value that represents logical false so iterating over a string is often a matter of incrementing an array index or incrementing a pointer while logical true since all characters other than the end of string indicator have a non-zero or logical true value.
Due to how close to the hardware that the C programming language is, the programmer needs to be concerned about both representations, the physical representation when allocating memory to store a string which includes the null character and the logical representation which is the string without the null character.
The various C style string manipulation functions in the Standard Library (strlen(), strcpy(), etc.) are all designed around the logical representation of a C style string. They perform their actions by using the null character as not being part of the text but rather as a special indicator character which indicates the end of the string. However as a part of their operations they need to be aware of the null character and its use as a special symbol. For instance when strcpy() or strcat() are used to copy strings, they must also copy the null character that indicates the end of the string even though it is not part of the actual text of the logical representation.
This choice allows text strings to be stored as arrays of characters, as befits the hardware orientation and efficiency characteristics of C. There is no need to create an additional built in type for text strings and it fits well with the lean character of the C programming language.
C++ is able to provide the std::string because of being object oriented and having the additional facilities of the language that allows for objects to be created and managed. The C programming language, due to its simple syntax and lack of object oriented facilities does not have this convenience.
The problem with this approach is that the programmer needs to be aware of both the physical representation and the logical representation of text strings and be able to accommodate the needs of both when writing programs.


text:
Q: Supply 3.3 V from a 5 V phone charger For a project I'm working on I need a power supply of 3.3 V to supply power and current for 14 mini vibration motors that work on 3.3 V. Each motor is rated at 85 mA so I need to be able to deliver ~1.2 A.
A voltage regulator such as this one can deliver up to 800 mA current so I guess it is not a good choice. I was thinking of using voltage divider and a voltage follower circuit using an LM358 op-amp. What do you think about that solution? Here is my schematic for that:

With that circuit the output voltage at LM358 pin 1 will be fixed at ~3.3 V and the current will be as much as the phone charger can deliver(?), so if my phone charge is rated @5 V with 2 A, will I be able to deliver almost 2 A of current to the motors?
Full schematic in here:

A: One option could be to just use two of the 800ma regulators that you all ready referenced then run the 14 motors in 2 banks of 7 ? Each bank of 7 should draw 595ma.
Yet another option is to find a 3.3v step-down module with a higher output current, such as this or even this.

A: Your circuit won't work. Those op-amps are used for signals or very weak loads.  They can't provide enough current for the motors.
If you are not explicitly after a sophisticated solution I'd actually recommend to just put a resistance of 20 ohm in series with each motor and supply them with 5V. At 85 mA each resistor will dissipate around 150 mW. Resistors rated for 250 mW or even 500 mW are common and cheap.

A: It won't work.
The LM358 op-amp can only output few tens of milliamps, so it can't drive even one motor.

A: If you must have an op-amp circuit, use a power device, such as OPA548, which supply sufficient current.

A: Do you really, really, really need to power these motors from a regulated source?
I don't think so.

*

*Chances are that the motors have a bit higher current draw at start. If you power them at once you will get a lot more than 1.2A inrush current. You will need a big-big capacitor or a better power supply or some logic not to allow them to start together.

*Chances are the motors don't have very tight specs, so the vibration frequency and amplitude vary between items even when the voltage is fixed.

In short, use 20 ohm resistors in series with the motors and power them with 5.0V directly.

*

*inrush current limited to 250ma (maybe less, depending on the unknown motor properties)

*simple

*you may use vary the resistance in order to get lower frequency or higher fault-tolerance.

A: Feedback the voltage from the output transistor to the op amp to regulate the voltage
Yep you do need a 5 watt transistor(maybe more)to feed all of those motors.
Or as Henros states a TI OPA548
But if one of the motors locks.
You also need a trigger to shutdown the motor current.
Or you can use a cheap  (2N550, BSR13?) transistor (much less than 5 watts) as a fuse to each motor. I don't know of any fast blow small current fuses.

A: Opamp you use is not good choice for your application. LM358 can source 40-50 mA.


text:
Q: Checked some chekbox when another checkbox is checked I tried to checked the two checkbox with id check1 and check2 when opt1 is checked , i use jquery for this, here is the following code.
    the jquery is:
$(document).ready(function() {
    $('#opt1').change(function() {
        if(this.checked) {
            $('#raw').slideDown(400);
            $('#check1').changeAttr('checked');
            $('#check2').prop('checked', true);
        } else {
            $('#raw').slideUp(200)
        }
    });
});

this is my html code

<input id="opt1" type="checkbox" name="vehicle" value="Raw Material">Raw Material

<input id="check1" type="checkbox" name="lol[]" value="Add Raw Name">Add Raw Name

<input id="check2" type="checkbox" name="lol[]" value="View Raw Materials">View Raw Materials

A: You need to pass a value to the prop() method as well as the property to set.
$('#check1').prop('checked', true);

http://jsfiddle.net/K63mF/

A: If you want to check the 2 other checkboxes when the first checkbox is checked, you can do it this way:
(Shown in this fiddle)
$(document).ready(function() {
    $('#opt1').change(function() {
        if($(this).is(":checked")) {
            $('#check1').prop('checked', 'checked');
            $('#check2').prop('checked', 'checked');
        } else {
            $('#check1').prop('checked', '');
            $('#check2').prop('checked', '');
        }
    });
});

A: Use following code
$(document).ready(function() {
    $('#opt1').change(function() {
        if(this.checked) {

            $('#raw').slideDown(400);

            //update code
            $('#check1').attr('checked','checked');
            $('#check2').attr('checked','checked');

        } else {
            $('#raw').slideUp(200);

            //if you want to remove check
            //$('#check1').removeAttr('checked');
            //$('#check2').removeAttr('checked');
        }
    });
});


text:
Q: Can't select People (@) when adding a comment in VSTS Since last Friday, I have a weird issue with VSTS. I no longer have the option to mention people in comments when reviewing a Pull request. However, the option still works properly in the Team Room chat.
In the window of adding a comment, I only see save (enter) - cancel (esc) - workitems (#), while for other colleagues it is save (enter) - cancel (esc) - workitems (#) - people (@)
My question: What did I do to turn it off and how can I enable it again?
update
I deleted cookies and emptied browser cache, I tried using different browsers (also in private / incognito mode), but it didn't help.
I also tried to log in on a different machine, while a colleague logged in on mine. Still no success.
update #2
I also tried to remove / re-add my account to VSTS. First it looked good, I got back the option to mention others, but after a day it's gone again.
update #3
I found a workaround, if I type in@<email-address> in the comment, it is displayed properly, the person gets a notification, etc. But still, the dropdown is not shown.


text:
Q: Denial of Service - how to prevent this I keep getting spam attempts from a single IP address at a time (though this single IP address changes daily) trying to lucky-guess executable files on my web server. They all trace back to the same place - Tencent Cloud Computing in China. These spam attempts keep crashing the server, rendering the website inaccessible. How can I stop this?
I have tried contacting the network abuse email and calling my ISP to see if there's anything they could do, but to no avail.
Example Apache log shown below.
[Thu Sep 20 22:47:34.169296 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/help.php' not found or unable to stat
[Thu Sep 20 22:47:34.418703 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/java.php' not found or unable to stat
[Thu Sep 20 22:47:34.682234 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/_query.php' not found or unable to stat
[Thu Sep 20 22:47:34.910484 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/test.php' not found or unable to stat
[Thu Sep 20 22:47:35.138673 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/db_cts.php' not found or unable to stat
[Thu Sep 20 22:47:35.369907 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/db_pma.php' not found or unable to stat
[Thu Sep 20 22:47:36.382860 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/logon.php' not found or unable to stat
[Thu Sep 20 22:47:37.920666 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/help-e.php' not found or unable to stat
[Thu Sep 20 22:47:38.149610 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/license.php' not found or unable to stat
[Thu Sep 20 22:47:38.382743 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/log.php' not found or unable to stat
[Thu Sep 20 22:47:38.616254 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/hell.php' not found or unable to stat
[Thu Sep 20 22:47:38.880654 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/pmd_online.php' not found or unable to stat
[Thu Sep 20 22:47:39.111538 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/x.php' not found or unable to stat
[Thu Sep 20 22:47:39.344646 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/shell.php' not found or unable to stat
[Thu Sep 20 22:47:40.321053 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/desktop.ini.php' not found or unable to stat
[Thu Sep 20 22:47:41.916380 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/z.php' not found or unable to stat
[Thu Sep 20 22:47:42.167929 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/lala.php' not found or unable to stat
[Thu Sep 20 22:47:42.429254 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/lala-dpr.php' not found or unable to stat
[Thu Sep 20 22:47:42.691206 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/wpo.php' not found or unable to stat
[Thu Sep 20 22:47:42.944551 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/text.php' not found or unable to stat
[Thu Sep 20 22:47:43.199610 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/wp-config.php' not found or unable to stat
[Thu Sep 20 22:47:43.455259 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/muhstik.php' not found or unable to stat
[Thu Sep 20 22:47:44.529700 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/muhstik2.php' not found or unable to stat
[Thu Sep 20 22:47:45.925214 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/muhstiks.php' not found or unable to stat
[Thu Sep 20 22:47:46.165955 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/muhstik-dpr.php' not found or unable to stat
[Thu Sep 20 22:47:46.424593 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/lol.php' not found or unable to stat
[Thu Sep 20 22:47:46.683114 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/uploader.php' not found or unable to stat
[Thu Sep 20 22:47:46.941768 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/cmd.php' not found or unable to stat
[Thu Sep 20 22:47:47.199412 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/cmx.php' not found or unable to stat
[Thu Sep 20 22:47:47.436995 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/cmv.php' not found or unable to stat
[Thu Sep 20 22:47:48.608073 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/cmdd.php' not found or unable to stat
[Thu Sep 20 22:47:49.941993 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/knal.php' not found or unable to stat
[Thu Sep 20 22:47:50.202085 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/cmd.php' not found or unable to stat
[Thu Sep 20 22:47:50.465856 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/shell.php' not found or unable to stat
[Thu Sep 20 22:47:50.719343 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/appserv.php' not found or unable to stat
[Thu Sep 20 22:47:53.919666 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/wuwu11.php' not found or unable to stat
[Thu Sep 20 22:47:54.135087 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/xw.php' not found or unable to stat
[Thu Sep 20 22:47:54.365319 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/xw1.php' not found or unable to stat
[Thu Sep 20 22:47:54.600458 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/9678.php' not found or unable to stat
[Thu Sep 20 22:47:54.844971 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/wc.php' not found or unable to stat
[Thu Sep 20 22:47:55.109660 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/xx.php' not found or unable to stat
[Thu Sep 20 22:47:55.364916 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/s.php' not found or unable to stat
[Thu Sep 20 22:47:55.581704 2018] [:error] [pid 27541] [client 192.144.156.249:29474] script '/var/www/html/w.php' not found or unable to stat

update: additional logs
[Tue Sep 25 07:59:21.537385 2018] [core:notice] [pid 28393] AH00094: Command line: '/usr/sbin/apache2'
[Tue Sep 25 08:32:08.233864 2018] [autoindex:error] [pid 29290] [client 192.141.161.31:41020] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 08:51:23.208687 2018] [autoindex:error] [pid 29759] [client 81.199.17.114:33476] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 09:07:45.829806 2018] [autoindex:error] [pid 30004] [client 157.119.212.30:38609] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 09:33:49.984459 2018] [autoindex:error] [pid 30699] [client 187.10.199.101:35686] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 11:24:46.399677 2018] [autoindex:error] [pid 794] [client 31.7.122.119:57011] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 11:53:06.380975 2018] [autoindex:error] [pid 1362] [client 84.22.54.93:37588] AH01276: Cannot serve directory /var/www/html/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml,index.htm) found, and server-generated directory index forbidden by Options directive
[Tue Sep 25 12:22:27.732958 2018] [mpm_prefork:notice] [pid 28393] AH00169: caught SIGTERM, shutting down
[Tue Sep 25 12:22:51.582214 2018] [:notice] [pid 2041] FastCGI: process manager initialized (pid 2041)
[Tue Sep 25 12:22:51.892511 2018] [mpm_prefork:notice] [pid 2040] AH00163: Apache/2.4.10 (Raspbian) mod_fastcgi/mod_fastcgi-SNAP-0910052141 mpm-itk/2.4.7-02 PHP/5.6.36-0+deb8u1 OpenSSL/1.0.1t configured -- resuming normal operations
[Tue Sep 25 12:22:51.892924 2018] [core:notice] [pid 2040] AH00094: Command line: '/usr/sbin/apache2'
[Tue Sep 25 12:23:01.247551 2018] [core:error] [pid 2040] AH00046: child process 2046 still did not exit, sending a SIGKILL
[Tue Sep 25 12:23:01.247755 2018] [core:error] [pid 2040] AH00046: child process 2047 still did not exit, sending a SIGKILL
[Tue Sep 25 12:23:02.249062 2018] [mpm_prefork:notice] [pid 2040] AH00169: caught SIGTERM, shutting down

A:
in China.

You can't stop it.
You could add a firewall rule to drop traffic from that IP; however it's useless because it will just appear from another IP and eventually you'll have thousands of drop rules, which will impact performance.
Limiting requests from a single IP will reduce server load, however it won't stop the scans. If you do want to go down the "blocking" road, fail2ban works nicely.
Mostly, your code just needs to be able to handle this.
If your web app is internal or has a limited audience, you can drop all traffic except authorized addresses.

A: I have a Node based HTTP server running on a Raspberry Pi3B+ -- I know this probe well. Every IP probe uses only IP addresses and so if you look at the HTTP header 'host' -- it will be your domain's IP address or worse yet literally localhost.
This particular probe I captured tonight starts with an attack vector on WebDAV by attempting to overflow a buffer. WebDAV uses a unique HTTP header -- PROPFIND. The entire capture doesn't fit in one image, but the next part uses localhost and further probes WebDAV.

 The probe then begins checking for PHP scripts, which is what you showed in your Apache log.
Legitimate traffic does not do that -- it uses the domain's host name and legitimate bots have their name in the user-agent header, so a little HTTP header analysis goes a long way.
;-)

Also -- the crash you are experiencing happens on the final bit of the scan, which is NOT a GET -- it is a POST. (CGI = Common Gateway Interface -- POST).
 Notice that the flurry of GETs is at 24 second intervals...interesting -- this scanner is probably probing literally thousands of IPs concurrently -- it will likely do you no good to complain about abuse, considering the source of the probe.
 The best advice would be to ignore it entirely. In Node, I can destroy the connection and even blacklist the IP, but -- I run a lot of my own analytic code to support that and so I have no idea what Apache offers in that respect.

A: I have created a script that runs every 1 minute, and detect all kind of failes in both error.log and access.log
It also check asterisk message le for "Failed to"
When find an IP with over 20 ailed attempt it adds it to ufw.
So far - It works like a charm.
Here is the script:
#!/bin/bash
clear
#ban IPs:
bip() {
echo "" > tmpIPs
ufw status | grep DENY | awk '$1 !="Anywhere" {print $1}' | sort > tmpinc
exst=$(ufw status | grep "Anywhere                   DENY" | awk '{print $3}' | sort | uniq)
cat $cTarget | while read line
do
 add=$(cat tmpinc | grep $line)
 if [ "$add" != "$line" ]
  then
   ip=$(echo $line | cut -d '.' -f 1,2,3)
   if [ $ip != $ignorIP ]
    then
    echo $line >> tmpIPs
   fi
  fi
done

lAdd=$(cat tmpIPs)
cat tmpIPs | while read line
do
 if [ "$line" != "" ]
  then
  /usr/sbin/ufw insert 1 deny from $line to any  >> $cBanIpLog
  /usr/sbin/ufw insert 1 deny to $line from any >> $cBanIpLog
  echo "       Banned $line" >> $cBanIpLog
  fi
done
rm tmpIPs
}

nMax=5 # Maximum failes
cTarget="/tmp/_ban.ip" # Temporary storage file
cLogFile="/var/log/apache2/access.log" # apache2 access log file
cLogFile1="/var/log/apache2/error.log" # apache2 error.log
cLogFile2="/var/log/asterisk/messages" # asterisk log file
cBanLog="/var/log/banips.log"          #This script log file
cBanIpLog="/var/log/banIP.log"
ignorIP="192.168.1" #IP to ignor, usually home network
dt=$(date +%Y-%m-%d)

echo "Banning IP run at $(date)
Maximum offends: $nMax
Checking logs
        $cLogFile
        $cLogFile1
        $cLogFile11
        $cLogFile12
        " > $cBanIpLog

#Get the bastards out of apache2 and asterisk:
#apache2 access.log
grep 404 $cLogFile | cut -d ' ' -f 1,4 | cut -d ':' -f 1,2,3 | tr -d '[' | sort | uniq -c | sort -rn | awk ' $1 > '"$nMax"' {print $2}' | uniq -c | awk '{print $2}' > $cTarget.tmp
#apache2 error.log
grep "not found or unable to stat" $cLogFile1 | awk '{print $1,$2,$3,$5,$10}' | cut -d ':' -f 1 | sort | uniq -c | awk ' $1 > '"$nMax"' {print $6}' >> $cTarget.tmp
#asterisk messages
grep "failed for" $cLogFile2 | awk -F'failed for' '{print $2}' | awk -F' ' '{print $1}' | awk -F':' '{print $1}'  | tr -d "'" | sort | uniq -c | sort -nr | awk ' $1 > '"$nMax"' {print $2}' >> $cTarget.tmp
#asterisk messages
grep "rejected because extension not found" /var/log/asterisk/messages | awk -F'(' '{print $2}' | awk -F':' '{print $1}' | sort | uniq -c | awk ' $1 > '"$nMax"' {print $2}' >> $cTarget.tmp
#Check myAnt logons
#grep LogonERR /var/www/html/_Public/sys_logs/_qryLogIn.log | awk '{print $3}' | sort | uniq -c | sort -nr | awk '$1 > $nMax {print $2}' >> $cTarget.tmp

#Leave uniq ips
cat $cTarget.tmp | sort | uniq > $cTarget
rm $cTarget.tmp

#Banning
bip
if [ "$lAdd" != "" ]
then
 #Conclude:
 /bin/systemctl restart ufw
 /bin/systemctl status ufw >> $cBanIpLog
 /usr/sbin/ufw status >> $cBanIpLog
 cat $cBanLog | sort | uniq | sort >> /var/log/banips.tmp
 rm $cBanLog
 mv /var/log/banips.tmp $cBanLog
 cat $cBanLog | nl >> $cBanIpLog
 echo "Log file at $cBanIpLog
 nano $cBanLog
 Finished banning $(date)
 " >> $cBanIpLog
 #echo nano /var/log/banips.log
 clear
 cat $cBanIpLog
fi

A: this is not "denial of service", but quite common scans for possible exploits. that the IP is in China, does not matter the least - while not having to serve to that territory, one can refuse to serve them.
you could a .htaccess file (or vhost configuration); this would at least make the server not respond:
deny from 192.144.156.249

one can deny requests from whole sub-nets ...which may help to get rid of them, altogether:
deny from 192.144.

adding similar firewall rule, would not even let these requests reach the server.
telling IP traffic apart is barely within the responsibility of application code.


text:
Q: PHP uploads with 2Tb partition limit Using PHP/Apache and now face a problem on Ubuntu linux where my web application's uploads are nearly 2Tb in total.
Does anyone have any experience in programming their PHP uploads to use multiple partitions? Maybe filling-up the partitions in a round-robin method to effectively give more storage?
The SAN I use has over 20Tb of storage, but I'm effectively being limited to only 10% of this!
Any help much appreciated!

A: You can do a chunked upload.
There are libraries that can handle it on the client side for you.
http://www.plupload.com/index.php

A: PHP will hand off to the OS to handle the details and report any errors.
I'm assuming the problem isn't that any one single file is bigger than 2TB. but that you have thousands of files that are taking up all the partition that your web-server is on.
If you need to use multiple partitions, you should split your uploads folder using something that will split nicely according to your requirements.
You might want to know where a file is without having to trawl the whole uploads tree
e.g. you could split by something like:
 - upload date /year/month,
 - starting letter of file or
 - round(user-id/100)
Then you can mount different partitions within uploads.
You could have a folder called uploads and within that you could mount other partitions
 mount /dev/sdb2 /var/www/html/myapp/uploads/2014
 mount /dev/sdb3 /var/www/html/myapp/uploads/2015

Initially you might have to transfer files from your old location to those new partitions so that the older uploads will be available under the new scheme.
To php this is transparent, I have done similar things even with mounted smb shares. You'll have to make sure the right permissions/users are set up so that PHP can write to those folders.


text:
Q: How many different solutions for this $\sqrt{3x^2 + 2x + 5} + \sqrt{x^2-4x+5} = \sqrt{2x^2 - 2x + 2} + \sqrt{2x^2+8}$
My attempt :
All the equation inside sqrt has $D<0$.
Let it be
$\sqrt A + \sqrt B = \sqrt C + \sqrt D$
2 possibilities
$$\sqrt A = \sqrt C \cap \sqrt B = \sqrt D$$
Find $x$ that match this condition.
$\sqrt A = \sqrt C $ i get $x=-3 \cup x=-5$
$\sqrt B = \sqrt D $ i get $x=-3 \cup x=-1$
$$\sqrt A = \sqrt D \cap \sqrt B = \sqrt C$$
Find $x$ that match this condition.
$\sqrt A = \sqrt D $ i get $x=-3 \cup x=1$
$\sqrt B = \sqrt C $ i get $x=-3 \cup x=1$
2 solutions.
Another posibility
$\sqrt A + \sqrt B = \sqrt C + \sqrt D$
${[\sqrt A + \sqrt B]}^2 = {[\sqrt C + \sqrt D]}^2$
This part is complicated.
Is there easier way to solve it?

A: Let $a=\sqrt{3x^2+2x+5}, b=\sqrt{2x^2+8}, c=\sqrt{2x^2-2x+2}, d=\sqrt{x^2-4x+5}$
$\implies a-b=c-d$
Observe that $$3x^2+2x+5-(2x^2+8)=x^2+2x-3=2x^2-2x+2-(x^2-4x+5)$$
$\implies a^2-b^2=c^2-d^2$
$\implies a+b=\dfrac{c-d}{a-b}\cdot c+d=c+d$
Now add and subtract to find $$a=c$$
$$\implies\sqrt{3x^2+2x+5}=\sqrt{2x^2-2x+2}$$
Square both sides


text:
Q: Nginx docker react ec2 https connection refused Tried a number of different versions of nginx.conf, but nothing appears to be mitigate the classic connection refused page when I enter my https://domain.
It should be noted that the domain ends with .dev, wondering if this matters.
The domain was purchased on google domains, and there are A record mappings to a public EC2 instance that has the running nginx server (inside the docker container).
nginx.conf:
server {
  listen 80;

  server_name random.dev www.random.dev;

  return 301 https://random.dev$request_uri;
}

server {
  listen 443 default_server ssl;

  server_name random.dev www.random.dev;

  ssl on;
  ssl_certificate /etc/ssl/certs/ssl-bundle.crt;
  ssl_certificate_key /etc/ssl/private/private.key;

  index index.html index.htm;
  root /usr/share/nginx/html;

  location / {
    try_files $uri $uri/ /index.html;
  }

}

Dockerfile:
FROM node:17.7.1 as builder

WORKDIR /usr/src/app

COPY package*.json /usr/src/app/

RUN npm install

COPY . /usr/src/app/

RUN npm run build

FROM nginx:latest

COPY --from=builder /usr/src/app/build /usr/share/nginx/html

RUN rm /etc/nginx/conf.d/default.conf

COPY nginx.conf /etc/nginx/conf.d

COPY ./ssl /etc/ssl

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

docker-compose:
version: "3"

services:
  ui:
    image: <image>
    ports:
      - 80:80
      - 443:443

EC2 instance has an Amazon Linux 2 flavor.
Security group mapping appears to be correct, with ssh (22), http (80), and https (443) accepting inbound from everywhere.
Network ACL is default (open to all, inbound and outbound).
After running docker-compose, I've also tried checking using netstat (inside ec2 outside docker) whether 80 and 443 were listening, and they were.
http on the raw IP (not domain) has worked when I commented out the 443 nginx conf code, but the domain does not work because .dev and .app automatically redirects to https on chrome (and firefox I believe).
Given this, wondering if anyone else faced any problems similar to mine. Is this an Amazon Linux 2 problem, or is it a .dev problem, or could it possibly be an ssl problem?

A: A series of changes were made, but the fix appears to have something to do with assigning an elastic IP address to the ec2 instance.
For some reason the local wifi I was using (Verizon) always led to a timeout request to the IP address on ping <ip-address>. However, on the other networks we tested (comcast as well as ATT mobile data), the IP address was not refused. This is likely to have something to do with the IP address being blacklisted by Verizon. I am not sure if all static IPs are blacklisted or we just got unlucky. The elastic IP that was assigned seemed to fix the issue.


text:
Q: HTML table with resizable columns using percentage width There are plenty solutions for resizable tables out there. But all of them have in common that they are using pixel widths and not percentage widths.
In my use case my tables col widths need to be with a percentage width or at least set to an percentage width after the resize action. My implemented solution is buggy when starting to resize.
http://jsfiddle.net/bg843pkt/24/
var thElm;
var startOffset;

var eG;

Array.prototype.forEach.call(
  document.querySelectorAll("table th"),
  function (th) {
    th.style.position = 'relative';

    var grip = document.createElement('div');
    grip.innerHTML = " ";
    grip.style.top = 0;
    grip.style.right = 0;
    grip.style.bottom = 0;
    grip.style.width = '5px';
    grip.style.position = 'absolute';
    grip.style.cursor = 'col-resize';
    grip.addEventListener('mousedown', function (e) {
        thElm = th;
        startOffset = th.offsetWidth - e.pageX;
    });

    th.appendChild(grip);
  });

document.addEventListener('mousemove', function (e) {
  if (thElm) {
    thElm.style.width = startOffset + e.pageX + '%';
    eG = e.pageX;
  }
});

document.addEventListener('mouseup', function () {
    thElm = undefined;
});

How it acts
How it should act
Can anyone tell me how i can implement this functionality with percentage width without any buggy behaviour?

A: I created a working example but it is using an older jQuery Version.
http://jsfiddle.net/Ln280eqc/17/
    $("table").resizableColumns();

Source: https://github.com/dobtco/jquery-resizable-columns

A: I created table with column resize, the initial width is percentage.
When you resize the column, you can get the PX of the column first and then convert it to percentage according to the width of the whole table.
https://biechao.github.io/2019/11/20/storybook-static/?path=/story/table--resizable-column-table


text:
Q: Setting up EBS/EFS disk storage for disaster recovery I am thinking about how to best setup a couple of environments on AWS. I would like to setup two servers:

*

*Application server (running web application and REST services)

*Tools server (running several ETL jobs)

The end result should be two application servers and two tools servers (i.e. one appserver/toolserver on each availability zone)

*

*All environments will be talking to the same database

*Each environment will have its own EBS storage

*A single external shared storage (EFS) which will be accessible from any of the 4 environments.

I am a little confused in terms of how to setup the storage. The objective is to ensure that if an EC2 instance is lost, i don't loose any data.
To achieve this, i would like to set it up so that code is deployed on the local storage (EBS) and dynamic content is stored on the external shared storage (EFS).
All appliations will be in a folder with the following structure
├─ application
    ├─ bin
    ├─ lib
    ├─ config
    ├─ logs
    ├─ data
        ├─ processed
        ├─ failed

In an EC2 instance dies, i would like to retain config, logs and data folder. The other folders (bin and lib) will contain only binary code which can be rebuilt from GIT.
To achieve this, i am thinking of the following storage
EBS on appserver 1 and appserver 2
├─ applications
    ├─ finance
        ├─ appname1
            ├─ bin
            ├─ lib
            ├─ config --> /storage/finance/config
            ├─ logs --> /storage/finance/logs
            ├─ data --> /storage/finance/date

The last three will be symbolik links to folders on the external storage.
EFS (Shared storage)
├─ storage
    ├─ finance
        ├─ appname1
            ├─ config
            ├─ logs
            ├─ data

The above structure can be a maintenance nightmare but i cant think of other alternatives. With the above approach, code is deployed on each appserver but data is shared between two appservers.
If one appserver on one AV zone dies, the other will still be functional.
Other options i have considered include having everything on EBS storage and rely on backups/images. This will not work because the configuration files are dynamic and the image might not always have the latest data.
Reading about EFS storage, it looks like writing to it might be slow which is something that is slightly worrying me.
Questions:

*

*Are there alternatives to the above?

*Are there any other disadvantages to the above approach?

*Is there a way i can have everything (code + data) on local EBS storage and still be able to recover (to the second) in case of a disaster.

Thanks in advance

A: In looking at the AWS pages for EFS, it mentions that "Each Amazon EFS file system object (i.e. directory, file, and link) is redundantly stored across multiple Availability Zones." Similar wording on the EBS page.  So there's some redundancy there. Here's an Amazon PDF on high availability.
For EC2, using multiple availability zones will lower your risk exposure. I'd put each instance in a separate availability zone. And the PDF recommends using snapshots of EBS with a standby EC2 instance for HA.  Snapshots are available within regions so they are easily accessed for disaster recovery.  Doing it that way would answer your question about putting everything into AWS EBS. And it's fairly simple to copy EBS volumes between regions to add redundancy and keep everything sync'd.  You could, with that, have a production environment, a standby environment and a replacement environment that could be spun up quickly in the event of a failure, leaving you with 2 environments available at almost all times.
Check out that PDF and link plus Amazon's docs on high availability and see what works best for your business needs and staff levels.


text:
Q: how can I use await/async to get this data? I'm calling a service from a component. The service calls an external service which returns data asyncronously. My component needs to know when the data is returned in order to get a handle to the data.  I think I've done something like this with async/await in the past but I seem to be forgetting something in the example below.  Any idea what the gap is here?:
my.component.ts:
constructor(private afdb: AngularFireDatabase,  private ts: TestService)
{
    this._ts = ts;
    this._afdb = afdb;
    this.loadData();
}

async loadData()
{
    this._vms = new TestService(this._afdb);
    this.testData = await this._ts.getTestData();
}

test.service.ts:
public getTestData()
{
    this._afdb.list('TestData').snapshotChanges().map(actions => {
        return actions.map(action => ({ key: action.key, ...action.payload.val() }));
    }).subscribe(items => {
        return items;
    });
}

A: There are 3 ways you can go about this .

*

*Subscribe to the service and render the component once the data is available using ngIf
this.yourService.yourFunction.subscribe(value=>{
this.displayValue = value;
this.displayValueAvailable = true;
})
and in the templete you can do
<div *ngIf="displayValueAvailable"></div>

*You can use async pipe
You can let the template know that the data is async and render when the data is available using async pipe.
You can see the documentation here https://angular.io/api/common/AsyncPipe

*Set the component value to empty ie. if it is an array
ar: Array = [];
and in the subscribe function set the value of this array. Once the value is available, angular change detection should take care of the rest :) Hope this helps.

A: I think what you want is the async pipe, which you use in your template. If a property in your component class is an observable, you can add that property to the component's template with the async pipe.
https://angular.io/api/common/AsyncPipe


text:
Q: Golang variable declaration syntax meaning I am going through some Golang code and came through this block of code, I am not able to comprehend it. I can see that d1,d2,d3 are variables of type int. But what is the last string json:"start"
type obj1 struct {
    d1   int `json:"start"`
    d2     int `json:"end"`
    d3 int   `json:"retries"`
}

A: d1, d2, and d3 are not variables, they are struct fields. The string is a "struct tag".
This is all described in the Struct Types documentation in the language spec.


text:
Q: Linking mingw libs with cmake Long story short, I rewrote the Godot build system to cmake (only windows part), mostly because I wanted to learn it, but I have trouble compiling Godot with mingw. When I'm trying to compile it, at first everything goes fine, up until the point of linking final exe, where I get a lot of "undefined reference to" errors. It looks like main libraries (core/scene/editor/..) can't see functions from each other. MSVC build is working fine, and scons version is also compiling under mingw, so I clearly just missed something in my cmake version.. I tried to remove some compile/linking options throughout my cmake scripts as a test, but nothing changed. I don't really know how even debug this problem, so if someone could kick me in the right direction I would be really glad for it.

A: Ok, I finally got time to came back to this.
The problem
So basically the problem was in circular dependency on godot libs. I didn't thought this was the problem because I'm spoiled by MSVC (which doesn't depend on link order). Also, I tried to replicate circular dependency in mingw on a test project with much smaller scale. The project was a 30 libs with two functions in each, first function printing string, and another calling all first functions from all 30 libs, so there is 30 libs of circular dependency. Strangely enough, the project linked no problems, and printed 30^2 strings..
The solution
The solution is to use -Wl,--start-group/-Wl,--end-group linking flags around all libraries. There is two ways you can do it.
First way, is to add all your libraries to the some list of sorts. This could be global property, or property on some target (not just a simple variable), so it could be accessed from other subdirectories. After you formed your list of libraries you simply link it to the executable as follows
# getting all your libs from the global property..
get_property(__LIBS_LIST GLOBAL PROPERTY EXE_LIBS_LIST)
# linking all libraries to the exe..
target_link_libraries(my-exe PRIVATE -Wl,--start-group ${__LIBS_LIST} -Wl,--end-group)

This is the easiest solution, but be cautious about dependencies on libraries which you link to your exe, because it seems that when CMake creates link line for your exe, it first lists all libraries which are linked directly to your exe, and only after it places libraries which came from dependencies of libraries linked directly. Basically if your target dependency tree looks something like this:
exe // your main exe file
    - lib_A // lib A linked directly to the main exe
        - lib_AA // lib AA linked to the lib_A
            - lib_AAA // lib AAA linked to the lib_AA
    - lib_B // lib B linked directly to the main exe
        - lib_BB // lib BB linked to the lib_B
            - lib_BBB // lib BBB linked to the lib_BB

your link order for the exe will look something like this:
// first libs linked directly to the exe
lib_A
lib_B
// only after recursively initial libs dependencies
lib_AA
lib_AAA
lib_BB
lib_BBB

That's meen, that if you will link your libs like target_link_libraries(my-exe PRIVATE -Wl,--start-group ${__LIBS_LIST} -Wl,--end-group), --start-group and --end-group will guard only the libraries linked directly to your exe. I didn't found this described in documentation, but I found SO question which talks pretty much about same behaviour (CMake library linking order). Also, as I tested this on mingw, it didn't mattered how exactly libs lib_AA/lib_AAA/lib_BB/lib_BBB were linked, via PRIVATE or via INTERFACE, the results were the same.
Second way, is to exploit recursivity of link expanding for dependencies of libraries linked directly to the exe. From my example you can see, that dependencies of lib_A (lib_AA/lib_AAA) weren't mixed with dependencies of lib_B (lib_BB/lib_BBB). So basiacaly what we can do, is to create INTERFACE library and connect to it -Wl,--start-group immediately after that. Then add any number of libraries to it's interface and link global-libs to your exe (order does not matter). And in very end, close the group in your global-libs library
add_library(global-libs INTERFACE)
target_link_libraries(global-libs INTERFACE -Wl,--start-group)
# ...
# linking another libs, and linking global-libs to exe
# ...
target_link_libraries(global-libs INTERFACE -Wl,--end-group)

This will ensure, that all libraries connected to global-libs will be surrounded by -Wl,--start-group/-Wl,--end-group.
Now, theoretically, CMake should handle circular dependency by itself, by placing libraries in link line multiple times (how many times controlled by LINK_INTERFACE_MULTIPLICITY). But this method didn't worked for me (mb I just missed something..). Plus, you need declare dependencies between cmake targets, and with -Wl,--start-group/-Wl,--end-group you can just set one specific interface library as a holder for all libs with circular dependencies..


text:
Q: Can I Trust LoadOperation.Completed event Suppose that we have the code shown below,
LoadOperation lop=_dsrvX.Load(_dsrvX.GetUserDetails(userID));
lop.Completed +=(s,a)=>
{
  Debug.WriteLine("Completed but,
           First I load it then I registered Completed evet!");
}

I see this type code everywhere so I wonder is it right?
As I know when you call domainService methods this automatically fills domain service object's related EntitySet.
Suppose that LoadOperation(Can be Submit,Invoke ops.) completed rapidly and when I passed to the next line where I register completed event everything has done.Is it possible? It seems hard to achive that but can you give me 100% guarantee?
If you can't guarantee that I'm asking if there is a method of calling OperationBase objects manually?
Any comment will be appreciated.

A: Well, this is a crazy world, I would not give 100% guarantee of anything :P - But I do not think it should be a problem. If this bothers you, you can pass the callback as a parameter, like this:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), userDetailsCallBack, null);

(...)

void userDetailsCallBack(LoadOperation<UserDetails> op)
{
   //do anything with the results
}

or, to simplify even further:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), (op)=>
   {
       //do anything with the results
   }, null);

A: Yes you can trust it - 100% guaranteed!
If you dig into the code behind the asynchronous Load method, you will see that it starts up another thread, to do the actual load, then returns immediately.
That separate thread then prepares for a service call, performs the service call, and eventually returns the resulting data.
It cannot trigger the Completed event until that is all done and we are talking "a lot" of code to get through, not to mention waiting on a web-service, whereas the return is pretty much instantaneous after the thread was started. i.e. no chance for the other thread to complete and interrupt it.
There is 0% chance that the load will complete before you add the handler on the next line.
The usual approach is to provide a callback or anonymous method instead, but your existing code is fine. MS knew what they were doing when the designed it that way :)
I had this argument with Jon Skeet, on a related question, and his reaction was that you don't know what the Load method is doing so it "might" happen faster than the return... My pragmatic answer was that we know exactly what is going on, by design, and it 100% returns before the Load even commences


text:
Q: Django Slugfield removing articles ('the', 'a', 'an', 'that') I'm using django 1.10 and I have this setup:
class Chapter(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(unique=True)
    date_completed = models.DateTimeField(blank=True, null=True)

    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

In the admin, I have :
class ChapterAdmin (admin.ModelAdmin):

    list_display = ('title','slug', 'date_completed',)
    list_filter = ['title', 'date_completed']
    prepopulated_fields = {"slug": ("title",)}

I noticed that when I create a chapter with a title like "A boy and the pig", I get "boy-and-pig" as the slug. Django is stripping of the articles from my slug. Why is this so and what's the way around it?

A: Why is this so?
Well, that's the default behaviour of the Slugfield, in Django.  Why is it like that?  Because generally, it's been considered better for SEO.
(I say considered, as the article linked mentions this might be dated thinking. The premise is that  articles and the like are usually considered Stop Words, the most common words in a language; they're so common that they are unhelpful for a search engine to index, as they feature in most, if not all titles.  )
What's the Way Around It?
Firstly - why do you want to get around it?  What's the use case?
But if you're satisified you really want to do it, then it's quite simple:
from django.template.defaultfilters import slugify
would_be_slug = 'This is one of those rarest of things: A blog that uses article.'
slugify(would_be_slug)
>>>u'this-is-one-of-those-rarest-of-things-a-blog-that-uses-article'

This answer has some great advice on overriding standard fields and slugfields.
There's also a nice package that will do this for you if you don't want to roll your own.

A: You can write your own logic to filter specific words and articles out:
List of Stop Words:
Check out this blog post about SEO and stop words. At the end of the page, you'll find a list containing over hundreds of stop words.
Implementation:
    def save(self, *args, **kwargs):  # new

      if not self.slug:
          # remove articles
          words_to_remove = ["the", "a", "an", "that", "this"] # etc.
          filtered_title = ""

          for word in self.title.split():
              if word not in words_to_remove:
                  filtered_title = filtered_title + " " + ''.join(str(word))
          # to keep uniqueness, combine the id with the title
          self.slug = slugify(str(self.pk) + "-" + filtered_title)
      return super().save(*args, **kwargs)


text:
Q: System.out.print() imprime dos veces Tengo el siguiente código java, la clase Pruebas contiene el main donde se hace uso de la clase de mas abajo "Empleados",creo unos empleados, luego solicito al usuario que ingrese la cantidad que quiera y ahi me da un extraño error, no entiendo por qué se imprime dos veces el System.out.print("ing nombre:") dentro del bucle for, el output sale así "ing nombre:ing nombre:" pero solo la primera vez, la siguiente vuelta del bucle ya se imprime normal como aparece en la salida
import java.util.ArrayList;
import java.util.Scanner;

public class Pruebas {
    public static void main(String[] args) {
        Empleados emp1=new Empleados("pedro");
        Empleados emp2=new Empleados("cristofer");
        System.out.println(emp1.devuelveDatos());
        System.out.println(emp2.devuelveDatos());
        emp1.cambiaSeccion("Jefe");
        System.out.println(emp1.devuelveDatos());

        Scanner inp=new Scanner(System.in);
        String nombre="";
        System.out.print("ctos empleados desea ing: ");
        int x=inp.nextInt();
        Empleados[] e=new Empleados[x];
        for (int i = 0; i < x; i++) {
            System.out.print("ing nombre:");
            nombre=inp.nextLine();
            e[i]=new Empleados(nombre);
        }
        for(Empleados emp:e){
            System.out.println(emp.devuelveDatos());
        }
//OUTPUT:
//        Nombre: pedro |Seccion: Administracion |Id: 1
//        Nombre: cristofer |Seccion: Administracion |Id: 2
//        Nombre: pedro |Seccion: Jefe |Id: 1
//        ctos empleados desea ing: 3
//        ing nombre:ing nombre:lolo
//        ing nombre:maria
//        Nombre:  |Seccion: Administracion |Id: 3
//        Nombre: lolo |Seccion: Administracion |Id: 4
//        Nombre: maria |Seccion: Administracion |Id: 5
    }
}

//los trabajadores parten en administracion, luego desde ahi van escalando
class Empleados{
    //campos ejemplar
    private final String nombre; //el nombre no cambia por lo que lo declaramos como constante (final)
    private String seccion;
    private int Id; //cada objeto tendra su copia que puede ser distinta, es privada por tanto no accedible si no es por metodo
    private static int IdCorrelativo=1; //solo la clase tendra una copia de esta variable

    //CONSTRUCTOR:
    public Empleados(String nom){
        nombre=nom;
        seccion="Administracion";
        Id=IdCorrelativo; //la copia de la variable id para cada objeto sera el valor que almacene la clase en su variable Idcorrelativo
        IdCorrelativo++; //el id de la clase se irá incrementando por cada objeto creado el cual tendra su propia copia de dicho id correlativo
    }

    public void cambiaSeccion(String seccion){
        this.seccion=seccion; //this permite diferenciar el campo de clase (sección) con el argumento (tiene el mismo nombre)
    }

    //getter q nos devuelva la info del trabajador:
    public String devuelveDatos(){
        return "Nombre: "+nombre+" |Seccion: "+seccion+" |Id: "+Id;

    }

}

A: Lo que me parece es que queda un "enter" en el buffer de entrada después de leer el int que es la cantidad de elementos a ingresar en el loop.
Y cuando entra al bucle, el ingreso del primer nombre está vacío porque se lee ese enter que había quedado olvidado en el buffer.
Probá agregando la lectura de la linea después de leer el int:
Scanner inp=new Scanner(System.in);
String nombre="";
System.out.print("ctos empleados desea ing: ");
int x=inp.nextInt();

inp.nextLine(); // <----- si hay enter olvidado, este lo debe leer

Empleados[] e=new Empleados[x];
for (int i = 0; i < x; i++) {
    System.out.print("ing nombre:");
    nombre=inp.nextLine();
    e[i]=new Empleados(nombre);
 }


text:
Q: how can i fix this download chromium prob i try to downwload chromium code .
i'm currently at the command
$ gn gen out/Default
but its show me this error :
C:\Users\sapir\Downloads\depot_tools\chromium\src>gn gen out/Default
Traceback (most recent call last):
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/vs_toolchain.py", line 577, in <module>
    sys.exit(main())
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/vs_toolchain.py", line 573, in main
    return commands[sys.argv[1]](*sys.argv[2:])
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/vs_toolchain.py", line 388, in CopyDlls
    _CopyDebugger(target_dir, target_cpu)
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/vs_toolchain.py", line 424, in _CopyDebugger
    (debug_file, full_path))
Exception: dbghelp.dll not found in "C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\dbghelp.dll"
You must installWindows 10 SDK version 10.0.19041.0 including the "Debugging Tools for Windows" feature.
**ERROR** at //build/toolchain/win/BUILD.gn:49:3: Script returned non-zero exit code.
  exec_script("../../vs_toolchain.py",
  ^----------
Current dir: C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default/
Command: C:/Users/sapir/Downloads/depot_tools/bootstrap-3_8_0_chromium_8_bin/python/bin/python.exe C:/Users/sapir/Downloads/depot_tools/chromium/src/build/vs_toolchain.py copy_dlls C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default Debug x64
Returned 1 and printed out:

Copying C:\WINDOWS\System32\msvcp140.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\msvcp140.dll...
Copying C:\WINDOWS\System32\vccorlib140.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vccorlib140.dll...
Copying C:\WINDOWS\System32\vcruntime140.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vcruntime140.dll...
Copying C:\WINDOWS\System32\vcruntime140_1.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vcruntime140_1.dll...
Copying C:\WINDOWS\System32\ucrtbase.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\ucrtbase.dll...
Copying C:\WINDOWS\System32\msvcp140d.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\msvcp140d.dll...
Copying C:\WINDOWS\System32\vccorlib140d.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vccorlib140d.dll...
Copying C:\WINDOWS\System32\vcruntime140d.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vcruntime140d.dll...
Copying C:\WINDOWS\System32\vcruntime140_1d.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\vcruntime140_1d.dll...
Copying C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64\ucrt\ucrtbased.dll to C:/Users/sapir/Downloads/depot_tools/chromium/src/out/Default\ucrtbased.dll...

See //BUILD.gn:66:1: which caused the file to be included.
group("gn_all") {
^----------------
Traceback (most recent call last):
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/toolchain/win/setup_toolchain.py", line 304, in <module>
    main()
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/toolchain/win/setup_toolchain.py", line 257, in main
    vc_lib_um_path = FindFileInEnvList(env, 'LIB', ';', 'user32.lib')
  File "C:/Users/sapir/Downloads/depot_tools/chromium/src/build/toolchain/win/setup_toolchain.py", line 211, in FindFileInEnvList
    file_name, env_name, '\n'.join(parts))
AssertionError: user32.lib is not found in LIB:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\ATLMFC\lib\x64
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\lib\x64
C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\lib\um\x64
C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64
C:\Program Files (x86)\Windows Kits\10\lib\10.0.19041.0\um\x64
Check if it is installed.

what i need to do ??

A: You have not installed the debugging tools for Windows. It's quiet clear from this message
You must install Windows 10 SDK version 10.0.19041.0 including the "Debugging Tools for Windows"

because the GN build system is searching for those files when generating build files when executing the command gn gen out\YourBuildFolder. You should install Debugging Tools for Windows and looks like the Chromium version that you are using requires Windows 10 SDK version 10.0.19041.0.


text:
Q: install a package moved to /var/cache/apt/archives manually? I installed wkhtmltopdf, by sudo apt-get install wkhtmltopdf. Its version is 0.9.9.
http://wkhtmltopdf.org/downloads.html says its latest stable version is 0.12.2.1. So I download its deb for Ubuntu 14.04.
I want to use apt to install the downloaded deb for reasons stated in https://unix.stackexchange.com/a/159114/674 and related replies, so I  move it to /var/cache/apt/archives, but still how can I install it using apt?
$ mv /tmp/wkhtmltox-0.12.2.1_linux-trusty-amd64.deb /var/cache/apt/archives

$ sudo apt-get install wkhtmltox-0.12.2.1_linux-trusty-amd64.deb
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package wkhtmltox-0.12.2.1_linux-trusty-amd64.deb
E: Couldn't find any package by regex 'wkhtmltox-0.12.2.1_linux-trusty-amd64.deb'

$ sudo apt-get install wkhtmltox
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package wkhtmltox

$ sudo apt-get install wkhtmltopdf still installs the older version. Thanks.

A: Quick Summary
To install a manually downloaded .deb package and also automatically download and install the packages it depends on from your configured repositories:

*

*You can run sudo apt-get -f install after installing your .deb with dpkg -i.

*Or use gdebi to install a .deb package and automatically resolve its dependencies (apt-get will not do this, but gdebi and its graphical frontends will).

See below for details.
Why apt-get Won't Do This
apt-get checks your configured software sources (repositories) and automatically downloads and installs packages. Except in the case where a configured repository is inaccessible, this does not enable an apt-get install command to succeed that would not otherwise succeed. If the package isn't in one of your repositories, apt-get will not know to install it even if the .deb file happens to be in /var/cache/apt/archives.
Thus:

*

*If you have a package already downloaded, and it is the same package apt-get would automatically download and install, then you can put it /var/cache/apt/archives and apt-get will not have to download it.

*If you have a package already downloaded which is not the same package apt-get would automatically choose, but which is nonetheless available in a configured repository, then you can put it in /var/cache/apt/archives and force apt-get to attempt to install it instead of the package it prefers. For example:
sudo apt-get install abiword=3.0.1-1

*Neither of those situations applies to your case. The specific package version is not provided by any of the configured repositories, because it is instead an alpha testing version from the upstream project's download page. Because you have no repository that provides that version of that package, you cannot install your manually downloaded .deb file with apt-get.
Way 1: Install with dpkg and Resolve Dependencies with apt-get
Fortunately, it doesn't look like you need to install this package with apt-get. It appears your actual goal is

*

*to install the manually downloaded .deb package, which isn't provided by your repos (which dpkg can do, but apt-get cannot), and also

*to install any its dependencies that are provided by its repos (which dpkg cannot do, but apt-get can).

You can do this in two separate steps:

*

*Install the package with dpkg.
sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

*That created missing dependencies. apt-get can fix missing dependencies automatically.
sudo apt-get -f install

That should also automatically finish configuring the original package. (So you will not likely need to run sudo dpkg --configure -a yourself.)
Way 2: Use gdebi to Both Install and Resolve Dependencies
While apt-get won't attempt to automatically install an arbitrary .deb file and its dependencies, there is a tool made for this purpose: gdebi . From man gdebi:

gdebi  lets you install local deb packages resolving and installing its dependencies. apt does the  same,  but  only  for  remote  (http,  ftp) located packages.

To use gdebi in a terminal, run gdebi package.deb as root, e.g.:
sudo gdebi wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

gdebi also has graphical frontends. You'll probably want to use gdebi-gtk, the GTK+ frontend:
gksudo gdebi-gtk wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

But if you're running Kubuntu (or otherwise using KDE) you might prefer gdebi-kde, the KDE frontend (provided by the gdebi-kde  package):
kdesudo gdebi-kde wkhtmltox-0.12.2.1_linux-trusty-amd64.deb

The graphical frontends may also be called without arguments (e.g., gksudo gdebi-gtk), in which case you may click File > Open to browse for and select the .deb file from within the GUI.

A: To install a locally stored .deb package use dpkg. Try:
sudo dpkg -i /path/to/your/package.deb

apt takes care of the dependency problems which dpkg can not.
There is an interesting project dpkg-offline which is currently under development. To quote from the README of the project,
This tool will download a set of .deb packages needed to install all of the given <packages-to-download>, with their dependencies satisfied, on an installation done from <base-iso>.

You can check out the development version of the tool here. I did not try it, so don't know how (un)stable it is.
Here is a tutorial from the dev branch in Launchpad on how to install and use dpkg-offline.
Bonus There is going to be a show and tell event on this package in the Ubuntu Online Summit on 2015-05-06 at 15:00.

A: apt-get can't install a deb package, use dpkg:
sudo dpkg -i wkhtmltox-0.12.2.1_linux-trusty-amd64.deb


text:
Q: $24$ students arrive in random order to collect shirt, $3$sizes available $24$ students arrive in random order. $12$ are size $S$ and $12$ are size $M$. There are $24$ T-shirts provided: $10$ are size $S,$ $10$ are size $M,$ and $4$ are size $L.$ A student takes their correct size if it is available, or failing that the next size up. They go without if that is also not available. What is the probability that all students get T-shirts?
[Someone else posted this problem and I was busy working on the solution when they deleted it. It is quite an interesting problem, so I decided to repost it.]

A: Everyone gets a shirt unless the medium shirts are gone before all of the small people have had a chance to collect a shirt.
Worst case scenario.  The first $10$ people to arrive are mediums, $4$ people go home without shirts.
We only have to look at the shirt sizes of the last $4$ people who show up.
By the time the $20^{th}$ person arrives all of the mediums will be gone.
If any small people are in the last $4$ to arrive one of them doesn't collect a shirt.
The chance that the last $4$ are all mediums is $\frac{12\choose4}{24\choose4} = 0.0466$

A: All "mediums" are sure to get T-shirts.
All "smalls" will get suitable T-shirts only if any $4$ of the "mediums" are at the end,
which has the same probability as any $4$ of the mediums being at the start,
since all permutations are equi-probable.
Thus $Pr = \frac{12\cdot11\cdot10\cdot9}{24\cdot23\cdot22\cdot21}$

A: Label the size $S$ students in order of arrival as $S_1,\dots,S_{12}$ and similarly the size $M$ students in order of arrival as $M_1,\dots,M_{12}$. The $M$ students are bound to get a shirt, but $S_{11},S_{12}$ may find that all available $S$ and $M$ shirts have been taken. At least one of them goes without a shirt iff $M_9$ arrives before $S_{12}$.
If the last four students to arrive are all size $M,$ then all earlier students must have got a shirt, because the other $8$ size $M$ would only take $8$ of the size $M$ shirts leaving $2$ for the $12$ size $S$ students. So the last four students all take size $L$ and every student gets a shirt.
If $S_{12}$ arrives in the last four, then $M_9$ must already have arrived, so $S_{12}$ fails to get a shirt.
There are ${24\choose12}$ possible arrival patterns, all equally likely. The number with the last four arrivals being $M$ is ${20\choose12}$. So the required probability is $\frac{15}{322}$.


text:
Q: Is there a way to append/remove a resource to a binary at execution time? Is it possible to append/remove a ressource file to a binary at execution time?
I have an application written with go, which saves/searches data from a database file, and i would like this database file to be embedded to the binary, and updated by the application itself.
This way the application would be self contained with its database.

A: Technically, this is possible, but this is a bad idea. Your application could be run by users not having write permissions to your binary.
If you're talking about a portable app, your best option might be using a file in the same directory the binary is located, otherwise - use the user's home directory according to the conventions of the OS you're running on. You can use the os/user package to find the home directory.

A: Modifying the executable, this is generally a very bad idea.
Several issues pop right into my head, such as:

*

*Does the current user have sufficient permissions?

*Is the file locked during execution?

*What about multiple running instances of the application?

Even if you manage to do just that, think of what anti-virus and firewall applications will say to it: most when they detect the change will flag the executable and/or contain it, or deny running it, or some may even delete it. Rightfully, as this is what many viruses do: modify existing executables.
Also virus scanner databases maintain reports where files (their contents) are identified based on the hash of their content. Modifying the executable will naturally change the file content hash, thus render the file unknown / suspicious to these databases.
As mentioned, just write / cache data in separate file(s), preferably in user's home folder or in the application folder (next to the executable, optionally in sub-folders). Or make the cache file / folder a changeable option (command line flags).