text:
Q: JDK11 to JDK12 Migration java.lang.NoSuchFieldException: modifiers Below function Hacks the "HttpURLConnection#methods" static field (through Java Reflection). I am using reflection to unit test my code functionality. I found out we can not change the static final fields in JDK12. I found one solution to use unsafe but I am not sure how can I get this function working in JDK12 using unsafe.
protected static void allowMethods(String... methods) {
    try {
        Field methodsField = HttpURLConnection.class.getDeclaredField("methods");

        Field modifiersField = Unsafe.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(methodsField, methodsField.getModifiers() & ~Modifier.FINAL);

        methodsField.setAccessible(true);

        String[] oldMethods = (String[]) methodsField.get(null);
        Set<String> methodsSet = new LinkedHashSet<>(Arrays.asList(oldMethods));
        methodsSet.addAll(Arrays.asList(methods));
        String[] newMethods = methodsSet.toArray(new String[0]);

        methodsField.set(null/*static field*/, newMethods);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
}

This is the stacktrace for the above code:
Caused by: java.lang.IllegalStateException: java.lang.NoSuchFieldException: modifiers
at pii.rest.call.RestUtils.allowMethods(RestUtils.java:75)
at pii.rest.call.JobAbort.<clinit>(JobAbort.java:39)
Caused by: java.lang.NoSuchFieldException: modifiers
at java.base/java.lang.Class.getDeclaredField(Class.java:2549)
at pii.rest.call.RestUtils.allowMethods(RestUtils.java:62)

Can anybody help me convert this function to use Unsafe so therefore it works with JDK12+. I have tried this until now:
final Field ourField = HttpURLConnection.class.getDeclaredField("methods");
final Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
final Unsafe unsafe = (Unsafe) unsafeField.get(null);
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");


text:
Q: i need to print numbers in pl sql in the given format? I need to print numbers in pl/sql in the given format?
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

also can you tell me how to print the next two commands in the same line in the output screen.
dbms_output.put_line(j);
dbms_output.put_line(j+1);

A: To print multiple outputs on the same line, use dbms_output.put instead of dbms_output.put_line.
CAVEAT When using dbms_output.put, you have to flush the buffer afterwards - otherwise, your output won't appear on the screen.
Your original question can be solved by using two for loops:
begin
  for i in 1 .. 10
  loop
    for j in 1 .. i
    loop
      dbms_output.put(to_char(j) || ' ');
    end loop;
    dbms_output.new_line;
  end loop;
end;

A: You could do this in plain SQL instead of PL/SQL as follows:
select to_char(sum(res) over(order by res)) as res
  from ( select sum(power(10, level - 1)) over(order by level) as res
           from dual
        connect by level <= 5 )

Result:
RES
--------------------
1
12
123
1234
12345

To_char() function is used just to align result to the left.

redpajama_set_name: RedPajamaStackExchange


text:
Q: directly calculate the MLE of marginal distribution of the observable variable in EM algorithm One thing I cannot understand for the EM (Expectation maximization) algorithm, for the observable variable $Y$ and latent variable $Z,$ why don't we directly take MLE (Maximal likelihood estimation) of $Y?$ Since $Y$'s marginal distribution is independent on $Z,$ then we are no need to know the observation of $Z.$
Is the marginal distribution of $Y:f(y|\Theta)$ not easy to calculated? At least for the given examples in the book, we know their marginal distributions.
for example:

*

*latent variable: $Z\sim Bernoulli(\pi),$
observably variable: $(Y|Z=1)\sim Bernoulli(p),\ (Y|Z=0)\sim Bernoulli(q),$
then we know $f(y|\pi,p,q) = \pi p^y(1-p)^{1-y} + (1-\pi)q^y(1-q)^{1-y}.$

*latent variable: $P(Z=i) = p_i,$
observably variable:  $(Y|Z=i)\sim n(\mu_i,\sigma^2_i),$ PDF noted as $n(y|\mu_i,\sigma^2_i).$
then we know $f(y|p_1\cdots p_n,\mu_1,\cdots\mu_n,\sigma^2_1\cdots,\sigma^2_n) = \sum\limits_ip_i\cdot n(y|\mu_i,\sigma^2_i).$
the marginal distributions of $Y$ are all known.

A: The fact that the likelihood can be numerically computed in a manageable $\text O(n)$ time does not imply that the derivation of the associated maximum likelihood is feasible by analytical or standard numerical means. For instance, this representation of the (log-)likelihood surface of a two parameter mixture model exhibits the presence of at least three local modes, likely to confuse numerical methods. EM provides at least the guarantee that the endpoint of the sequence is a local mode.


text:
Q: How can I save a valid image to Github using their API? I'm building a script that uploads an image to GitHub as a base64 string. But my image isn't showing up as an image in Github when I go to view the commit.
As I am making a big data submission to upload other files (Markdown), I can't use req.files so I'm sending the image via req.body.imageTest (at least in Postman). I'm building the image string from one of the links below.
Can anyone tell:

*

*What encoding are images served on GitHub web view?

*What encoding should I use to send my image to GitHub?

I see OctoKit only accepts utf-8 and base-64.
await octokit.git.createBlob({
    owner,
    repo,
    content: Buffer.from(req.body.imageTest).toString("base64"),
    encoding: "base64"
})

https://www.base64-image.de/
data:image/png;base64,[encoded data, 4252 characters]

https://www.browserling.com/tools/image-to-base64
[encoded data, 4252 characters]

Two links above are an upload of the same image but why are they different strings?
Here's the actual image if it helps:

The image on Github (should show up as image preview, instead is code) is:

A: Crafting a commit using an image is supported through the GitHub API, I think you just need to be careful with how you read the bytes and send them through.
Here's an example script that creates a new repository and creates a commit containing the example image:
const fs = require('fs')
const path = require('path')
const util = require('util')

const readFilePromise = util.promisify(fs.readFile)

// API client for working with GitHub data using promises
const { Octokit } = require("@octokit/rest");

const token = process.env["GITHUB_TOKEN"];

if (token == null) {
  console.error("Expected GITHUB_TOKEN environment variable to create repository. Exiting...")
  process.exit(-1)
}

async function run() {
  const octokit = new Octokit({
    auth: token,
    log: console,
  });

  // change these values to create the test repository under your account
  const owner = "shiftkey";
  const repo = "upload-an-image-test-repo";

  await octokit.repos.createForAuthenticatedUser({
    name: repo,
    description: "testing uploading an image through the GitHub API",
  })

  // ensure that you are reading the file from disk as binary before converting
  // to base64
  const imagePath = path.join(__dirname, 'example.png')
  const bytes = await readFilePromise(imagePath, 'binary')
  const buffer = Buffer.from(bytes, 'binary')
  const content = buffer.toString('base64')

  // TODO: updating file requires providing the SHA of existing blob
  //       this is not currently supported
  const result = await octokit.repos.createOrUpdateFile({
    owner,
    repo,
    message: "Adding an image to the repository",
    path: 'example.png',
    content,
  })

  console.log(`Created commit at ${result.data.commit.html_url}`)
}

run()
  .catch(err => {
    console.error(err, err.stack)
  })

This is how it looks on GitHub:

A:
Two links above are an upload of the same image but why are they different strings?

The first one is a data URI scheme - a way to embed binary data and metadata inline as a resource (e.g. inline images).
The format of a data URI is: data:[<media type>][;base64],<data>
The second one looks it's the base64-encoded contents of the file.
Looking at the diff from GitHub, it looks like you're using a data URI instead of just the binary data, which might explain why it's falling back to rendering the text (even if the file has a .png extension).

A: Clearly, github is stripping special chars on the content. I'm going to try without data:image/jpeg;base64, and see if that works.
This was my request payload.

This is what I see on server after blob creation.


text:
Q: Winform DataGridViewLinkColumn ReadOnly property not working In my VS2015 Winform app, there is one DataGridView control bound to a BindingSource that is bound to a SQL database. The Grid has four columns: ID, URL, Name, Type. The URL column is DataGridViewLinkColumn whose ReadOnly property, by default, is set to False. I can edit the Name and Type columns but URL columns shows as ReadOnly. Why? How can I make URL column editable?

A: As Reza stated:

DataGridViewLinkColumn is not editable.

Therefore, to edit a cell in such a column you'll have to convert it to a DataGridViewTextBoxCell as needed. For instance, if I have subscribed to DataGridView.CellContentClick to handle clicking on a link, then I would handle CellDoubleClick for the cell conversion:
private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = new DataGridViewTextBoxCell();
        this.dataGridView1.BeginEdit(true);
    }
}

Once you've entered your value and left the cell, you should then use CellValidated to verify that the new value is a URI before converting the cell back to a DataGridViewLinkCell:
private void DataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

        if (Uri.IsWellFormedUriString(cell.EditedFormattedValue.ToString(), UriKind.Absolute))
        {
            cell = new DataGridViewLinkCell();
        }
    }
}

Caveat:

*

*This only worked for me when the data for the "URL" column were strings and thus after binding, the column defaulted to a DataGridViewTextBoxColumn - forcing a manual conversion to link cells to begin with:
private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow r in dataGridView1.Rows)
    {
        if (Uri.IsWellFormedUriString(r.Cells["URL"].Value.ToString(), UriKind.Absolute))
        {
            r.Cells["URL"] = new DataGridViewLinkCell();
        }
    }
}

*Setting up the "URI" column as a DataGridViewLinkColumn from the beginning allowed for the conversion of cells to TextBox type successfully. But when converting back to link cells, debugging showed the conversion to happen, but the cell formatting and behavior failed.


text:
Q: How to sort values of keys? from api i get this strings:
"18% increased Area of Effect", "25% increased Area of Effect", "19% increased Area of Effect"
i want to make like this:
"(18%-25%) increased Area of Effect"
 const filtredArray = array.filter((item) => item.implicit_mods);
 let implicitsList = [];

 filtredArray.forEach((item) => implicitsList.push(item.implicit_mods));

 implicitsList.forEach((implisit) => {
   if (implisit) {
     implisit.forEach((implicit) => {
       if (implicit) {
         if (!/\d/.test(implicit)) {
           //implicits without number
           if (!uniqueImplicitMap.get(implicit)) {
             addToMap(uniqueImplicitMap, implicit);
           }
         } else {
           // implicits with number
           let value = implicit.match(/\d+/g);
           let replaceImplicit = implicit.replace(/\d+/g, '#');
           if (value.length >= 2) {
             addToMap(uniqueImplicitMap, replaceImplicit, [
               value[0],
               value[1],
             ]);
           } else {
             addToMap(uniqueImplicitMap, replaceImplicit, value);
           }
         }
       }
     });
   }
 });
}

function addToMap(map, key, value) {
 if (!map.get(key)) {
   if (value) {
     map.set(key, [value, value]);
   } else {
     map.set(key);
   }
 }
 if (map.get(key) && value) {
   if (value[0] > map.get(key)[0]) {
     map.get(key).splice(0, 1, value);
   } else if (value < map.get(key)[0] && value < map.get(key)[1]) {
     map.get(key).splice(1, 1, value);
   }
 }
}

i can do it if i have only one number in string
but if string like this:
"10% chance to gain Unholy Might for 3 seconds on Kill"
code break.
help me please

A: I do not completely understand your code. What I think you want is if you get a array of strings from the API like ["18% increased Area of Effect", "25% increased Area of Effect", "19% increased Area of Effect"], and you want to make that into (18%-25%) increased Area of Effect.
If so, you can just run a .map onto the array to find the percent with symbols, and get the percent. With that is is quite easy to generate a string with ES6 template literals.
Example Code
JS Fiddle for snippet.

// Select elements on HTML
const
    before = document.querySelector(".previous"),
    before2 = document.querySelector(".previous2"),
  after = document.querySelector(".after"),
  after2 = document.querySelector(".after2");

// Sample API text
const beforeText = ["18% increased Area of Effect", "25% increased Area of Effect", "19% increased Area of Effect"];
const before2Text = ["10% chance to gain Unholy Might for 3 seconds on Kill", "18% chance to gain Unholy Might for 3 seconds on Kill", "26% chance to gain Unholy Might for 3 seconds on Kill"];

// Display before paresed strings
before.innerText = beforeText.join(" -=- ");
before2.innerText = before2Text.join(" -=- ");

// Display parsed strings
after.innerText = parser(beforeText);
after2.innerText = parser(before2Text);

function parser(arrText) {
    const PERCENT_REGEX = /[0-9]{1,2}%/;

  // Get percents of strings.
    const percents = arrText.map(elem => {
    const percentStr = elem.match(PERCENT_REGEX)[0];
    return parseInt(
        // Remove percent symbol
        percentStr.substring(0, percentStr.length - 1), 10
     );
  });

  const chanceToDoWhat = arrText[0].replace(PERCENT_REGEX, "");
  return `(${Math.min(...percents)}%-${Math.max(...percents)}%)${chanceToDoWhat}`;
}
Before Parse:

Before Parse 2:

After Parse:

After Parse 2:


text:
Q: Costs of AWS EC2 I'm wanting to host a simple blog on AWS via Docker containers.  I've gone the route of creating an EC2 instance via this link https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#LaunchInstanceWizard:
I created an instance of type Amazon Linux AMI and it's a t2.micro.
How do I know if this is a low-cost way to host my blog?  What are the fees?  How do I know that I have 1 year free trial?
The reason I ask is because I looked at this on the docker site and then when clicking the Get Started with AWS link on that page, it brought me to a page that started talking about large costs...is this for larger servers that is not related to the free 1 year EC2 instance I'm trying to run for a simple blog?
I'm just looking for a cheap AWS instance to host my blog, maybe a few dollars a month with very small amount of traffic and want to make sure I'm doing this right in terms of creating and setting up my server since I do want to use docker to deploy my blog in a container.

A: I suggest you go with t2.nano instance which will cost you just $5/month + nominal data xfer cost. Later if you find the instance size not sufficient, you can upgrade the instance to t2.micro to t2.small to m3.medium etc., just by clicking few buttons.
Use this calculator: SIMPLE MONTHLY CALCULATOR to find the approximate cost.


text:
Q: Subtleties of Inheritance Let's say SList is a super class of TailList.
If I execute the following codes,
SList s;
TailList t = new TailList();
s = t;

is this same as doing SList s = new TailList();?
Now, is static type of t still TailList?

A: The object will be instantiated as TailList, and the assignment won't change that. (It would be a neat trick if the language could change the implementation class on assignment ;) )
For example, you can always go
TailList t = new TailList();
Object o = t;

Does that make it more clear? The object is still the same implementation class. It' not going to change to an Object, even though we're referencing it that way.
You could always do a System.err.println(s.getClass().getName()) and see.
BTW this is actually polymorphism rather than inheritance, because you're referencing the object as a class higher in the hierarchy. Inheritance would be if you called t.slistMethod() without overriding it.

A: When you execute SList s = new TailList();, what happens is the following:

*

*new TailList() is invoked, creating a new object which the constructor of TailList is run for. When the constructor finishes, an anonymous TailList reference is returned.

*The anonymous TailList reference is assigned to s.

Since a TailList is inheriting from SList, you can also refer to it by that. The reference to the object doesn't change the object itself.
Imagine I put a trash bin somewhere, and then tell someone who doesn't know of that object being a trash bin that I put a "container" at that location. The trash bin is indeed a container, but that person only knows that it's a container. This doesn't change the fact that it's a trash bin, but the other person can't safely assume that he can put trash in there, or that it is scheduled to be emptied at any time, therefore he wouldn't know to invoke this functionality on the "container" that he is refering to.
So for instance, let's say we have the following code:
String s = "Hello there";
Object o = s;

o is now refering to a String object, but is treating it as an "object", it doesn't know that it has a length, or that it contains characters, even though it does.
s on the other hand, while still refering to the same object that o is refering to, knows that this object is a String, and can use String functionality on that object.
If we wanted to, we could assume that o is a String by a mechanism called "casting":
String s2 = (String)o;

We now refer to the object referenced by o as a String. All of this changes nothing for the object itself, it's all a mere change in reference. As if, for the previous analogy, the person who was told about the mysterious "container", will assume that the container is more specifically a "trash bin". We could also make a wrong assumption, that the container is a packaging container
Integer i = (Integer)o; // throws ClassCastException

Fortunately, when we assume wrongly in Java, we get a ClassCastException, unlike in real life where if you put your items into a trash bin while refering to it as a packaging container your belongings will be thrown to garbage.
Or perhaps, what is confusing you is that first assignment. Well, new TailList() part of SList s = new TailList(); by itself is a static invocation of the constructor of TailList, and it will always return a TailList reference. The assignment that comes afterwards will still refer to the TailList object that was constructed by the invocation.

TL;DR
Yes, it's the same thing.

A: In statically typed object-oriented languages, both objects and variables have an associated type.
The type of a variable (the 'static type') is specified by the programmer when declaring the variable. It never changes.
The type of the object referenced by the variable (the 'runtime type') must be either the same or a subtype of the variable's declared type. An object never changes type, but the variable may be assigned a different object of a different type.
The first snippet declares two variables, s of type SList and t of type TailList. It creates an object of type TailList and stores a reference to it in both variables.
The second snippet declares a variable s of type SList, creates an object of type TailList, and stores a reference to it in s.
The end result in both cases is that s contains a reference to an object of type TailList. The difference is that in the first snippet there is an additional reference to the object stored in variable t (which still has a static type of TailList).

A: Is
TailList t = new TailList();
SList s = t;

The same as
SList s = new TailList();

Yes, except there's no separate reference of type TailList held to the new object, so you'll only be able to access methods from SList (unless you cast).


text:
Q: Lego-EV3: How to fix EOFError when catching user-input via multiprocessing? Currently, I am working with a EV3 lego robot that is controlled by several neurons. Now I want to modify the code (running on
python3) in such a way that one can change certain parameter values on the run via the shell (Ubuntu) in order to manipulate the robot's dynamics at any time (and for multiple times). Here is a schema of what I have achieved so far based on a short example code:
from multiprocessing import Process
from multiprocessing import SimpleQueue
import ev3dev.ev3 as ev3

class Neuron:
    (definitions of class variables and update functions)

def check_input(queue):
    while (True):
        try:
            new_para = str(input("Type 'parameter=value': "))
            float(new_para[2:0])  # checking for float in input
            var = new_para[0:2]

            if (var == "k="):  # change parameter k
                queue.put(new_para)
            elif (var == "g="):  # change parameter g
                queue.put(new_para)
            else:
                print("Error". Type 'k=...' or 'g=...')
                queue.put(0)  # put anything in queue
        except (ValueError, EOFError):
            print("New value is not a number. Try again!")

(some neuron-specific initializations)

queue = SimpleQueue()
check = Process(target=check_input, args=(queue,))
check.start()

while (True):
    if (not queue.empty()):
        cmd = queue.get()
        var = cmd[0]
        val = float(cmd[2:])

        if (var == "k"):
            Neuron.K = val
        elif (var == "g"):
            Neuron.g = val

    (updating procedure for neurons, writing data to file)

Since I am new to multiprocessing there are certainly some mistakes concerning taking care of locking, efficiency and so on but the robot moves and input fields occur in the shell. However, the current problem is that it's actually impossible to make an input:
> python3 controller_multiprocess.py
> Type 'parameter=value': New value is not a number. Try again!
> Type 'parameter=value': New value is not a number. Try again!
> Type 'parameter=value': New value is not a number. Try again!
> ... (and so on)

I know that this behaviour is caused by putting the exception of EOFError due to the fact that this error occurs when the exception is removed (and the process crashes). Hence, the program just rushes through the try-loop here and assumes that no input (-> empty string) was made over and over again. Why does this happen? - when not called as a threaded procedure the program patiently waits for an input as expected. And how can one fix or bypass this issue so that changing parameters gets possible as wanted?
Thanks in advance!


text:
Q: I got error while using ''image_gallery_saver'' in flutter this is the error:
''
The android Gradle plugin support only kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':image_gallery_saver' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.72
"
BUT my $kotlin_version is 1.6.10

i tried the plugin with an other app , and it's works

A: This is one of the known issue in this library. For some reason its not working with "android.tools.gradle" version 7.3.1.
You might have to downgrade the version to 7.2.2 or lower.
In your build.gradle replace

classpath 'com.android.tools.build:gradle:7.3.1'

with

classpath 'com.android.tools.build:gradle:7.2.2'

and try if it's working.
This solution is mentioned in there git repo here https://github.com/hui-z/image_gallery_saver/issues/220


text:
Q: Error fetching data from database I have two tables
CREATE TABLE `reg_data` (
  `date` varchar(10) NOT NULL,
  `session` varchar(10) NOT NULL,
  `time` time default NULL,
  `temp_air` float NOT NULL,
  `rel_humid` float NOT NULL,
  `soil_temp_5` float NOT NULL,
  `soil_temp_20` float NOT NULL,
  `soil_temp_30` float NOT NULL,
  `soil_temp_60` float NOT NULL,
  `air_pressure` float NOT NULL,
  `anem_reading` float NOT NULL,
  `dry_temp` float NOT NULL,
  `wet_temp` float NOT NULL,
  PRIMARY KEY  (`date`,`session`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

and
CREATE TABLE `reg_data3` (
  `date` varchar(10) NOT NULL default '',
  `time` time NOT NULL,
  `rainfall` float default NULL,
  `evep` float default NULL,
  `max_temp` float default NULL,
  `min_temp` float default NULL,
  `sunshine_hrs` float default NULL,
  PRIMARY KEY  (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

I want to join these two tables using date ='".$full." passed from $full=$month.'/'.$day.'/'.$year;.
My query is:
$sql ="(select A.date,A.rainfall,A.evep, A.max_temp, A.min_temp, A.sunshine_hrs,B.run , B.velocity From reg_data3 A  ,velocity B where A.date=B.date ORDER by A.date) WHERE date ='".$full."' ;

What is wrong with this query?

A: Try getting rid of the parentheses in your query and put date = '". $full . "' after your first WHERE clause with an AND.
You also need to specify which table's date column to use for date = '". $full . "', so change that to A.date = '". $full . "'
$sql ="select A.date,A.rainfall,A.evep, A.max_temp, A.min_temp, A.sunshine_hrs,B.run , B.velocity From reg_data3 A,velocity B where A.date=B.date AND A.date ='".$full."' ORDER by A.date;

I would also suggest formatting your query and using explicit joins instead of implicit ones:
$sql = "
    SELECT
        A.date,
        A.rainfall,
        A.evep,
        A.max_temp,
        A.min_temp,
        A.sunshine_hrs,
        B.run,
        B.velocity
    FROM
        reg_data3 A
        INNER JOIN velocity B
            ON A.date = B.date
    WHERE
        A.date = '". $full ."'
    ORDER BY
        A.date   /* this is pointless...they're all going to be the same date */
";


text:
Q: Spell checking in German texts - strange behavior This questions is about spell checking in German within Mathematica.
I have encountered some strange behaviour of Mathematica's spell-checker. Words within the dictionary are sometimes marked as misspelled even though they are correct (see attached image). This affects other words not just ones containing German umlauts.

Are there any ideas what one can do to fix this?


text:
Q: Issue with input-group in a td cell I am trying to put an bootstrap datepicker under a td cell, I used the html code below:

    <input type="text" class="form-control datePicker">

And the result looks like this:

A: Try the following snippet. Follow the tag structure as follows. And you need to add form-group class in order to make it similar look.

$(function() {
  $('#datetimepicker1').datetimepicker();
});

<link rel="stylesheet" type="text/css" media="screen" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href="./css/prettify-1.0.css" rel="stylesheet">
<link href="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet">

      Sample cell

        <input type='text' class="form-control" />

          <input type='text' class="form-control" />

A:

You can try this

    <link rel="stylesheet" type="text/css" media="screen" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
            <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
            <link href="./css/prettify-1.0.css" rel="stylesheet">
    <link href="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" rel="stylesheet">

                        <input type='text' class="form-control" />

Demo


text:
Q: What term best describes the "mentality" with which an API is designed? As someone whose mother tongue is not English, I'm sometimes having a hard time having the correct feeling towards the meaning of some words. This is one of those situations.
I'm looking for a term that refers to how an API (an application programming interface) is designed. For example imagine a piece of text with such statements:

*

*For every *_new function, there is a *_delete function.

*All functions creating shared objects take a name parameter as the first argument.

*All int *error arguments used for returning error code are optional and come last in the argument list.

How do you refer to the text containing these statements? For example, is it the style definition of the API? Are these the conventions of the API?

A: They are referred to as "Coding standards" in the software engineering world.

A: You might be looking for design template or design pattern.
Design patterns are not frequently associated with interfaces, but the term does come up, as with the "facade design pattern".
From wikipedia:

A facade is an object that provides a simplified interface to a larger body of code, such as a class library.

Simplification comes from creating reusable and familiar patterns that meet the necessary functional requirements.
You may like to know that "design patterns" is not localized to just software development. It was codified as an architectural concept by Christopher Alexander, and his ideas were published in "The Timeless Way of Building" in 1979. This book is literally about the architecture of buildings and construction, but lays a foundation for applying the concept to other fields of design.
Incidently, while on the subject of architecture, the word archetype, comes to mind as well (although the words are not related directly).

Archetype: the original pattern or model of which all things of the same type are representations or copies

But I don't think you will see "archetype" used as frequently in this case.

A: if you wanted to describe an implementation as being proper example of a given style you could use "idiomatic".
"That is an idiomatic example of a RESTful archtitecture"
Merriam Webster

1: of, relating to, or conforming to idiom
2: peculiar to a particular group, individual, or style

A: The list shown 'specifies' a series of realities of the API; ie it is a 'specification'. There is no room for discussion, it states a series of facts about 'specific' things. Specification language is a very standardised and accepted form of English intended to be as clear as possible for the purpose of imparting important information. It is almost an attempt to write computer code in plain English :-)
What makes it easy to recognise in a good example is what is missing:
no colloquialisms, first- or second-person modes or humour; no decoration or variety (the same sentence format is factored out and used to achieve the same purpose each time it is needed); no sarcasm, irony or exaggeration (care is taken to minimise assumptions by the reader, e.g. abbreviations are expanded locally or adjacent, punctuation is avoided where possible because misreading it can affect the meaning). The words 'Required' and 'Shall' may be used to give a special authority to some statements.


text:
Q: GDB: How to print the real object and all members of a pointer? How can I print the real object and values of a pointer and its values in GDB?
Assume I have a pointer to a base class test, and then assign it an instance of test2, how do I make this visible in GDB?
If I place a breakpoint at delete (line 20) of the following snippet an do:
break 20
Set print object on
run

Then I get:
(gdb) print *myTest
$1 = {p = 1, q = 2}
(gdb) display *myTest
1: *myTest = {p = 1, q = 2}

But what I expect (want to know) is the class type, and also the output  of r.
(gdb) print *myTest
$1 = {p = 1, q = 2, r = 3} **OF TYPE Test2**
(gdb) display *myTest
1: *myTest = {p = 1, q = 2, r = 3} **OF TYPE Test2**

How to get something like this?
SNIPPET:
class test {
   private:
        int p = 1;
   protected:
        int q = 1;
};

class test2 : public test {
   private:
       int r = 3;
   public:
       test2() {
           q = 2;
       }
};

int main() {
   test* myTest = new test2();
   delete myTest;
   return 0;
}


text:
Q: How to find what physical server my physical disk in a S2D windows cluster is attached I have a mirrored S2D cluster setup, one of my drives has an IO error as evidenced below. How do I find what physical server in the cluster this drive is attached to? I've ran all sorts of commands and can't find this information.
PS C:\Windows\system32> Get-PhysicalDisk

FriendlyName                    SerialNumber    CanPool OperationalStatus           HealthStatus Usage            Size
------------                    ------------    ------- -----------------           ------------ -----            ----
ST3320413AS                     W2A749LZ        False   OK                          Healthy      Auto-Select 298.09 GB
SanDisk SSD PLUS 120 GB         181424801962    False   OK                          Healthy      Journal     111.75 GB
SAMSUNG SSD PM851 2.5 7mm 128GB S1CTNSAF829417  False   OK                          Healthy      Journal        119 GB
ST31500541AS                    6XW09SL5        False   OK                          Healthy      Auto-Select   1.36 TB
ST1000DM003-1ER162              Z4Y43R31        False   OK                          Healthy      Auto-Select  931.5 GB
ST1000DM003-1CH162              S1DFPS7G        False   OK                          Healthy      Auto-Select  931.5 GB
WDC WD30EZRX-00MMMB0            WD-WCAWZ2490999 False   {Transient Error, IO Error} Unhealthy    Auto-Select   2.73 TB
ST2000DM006-2DM164              Z4Z8A7A8        False   OK                          Healthy      Auto-Select   1.82 TB
SanDisk SSD PLUS 120 GB         181424800647    False   OK                          Healthy      Journal     111.75 GB
ST1000DM003-1ER162              Z4Y43A3E        False   OK                          Healthy      Auto-Select  931.5 GB
ST2000DM006-2DM164              Z4Z89YEP        False   OK                          Healthy      Auto-Select   1.82 TB
ST1000DM003-1ER162              W4Y17MW5        False   OK                          Healthy      Auto-Select  931.5 GB
SAMSUNG SSD PM851 2.5 7mm 128GB S1CTNSAF719804  False   OK                          Healthy      Journal        119 GB

A: After some research because I wanted to know myself, you can use
Get-PhysicalDisk -SerialNumber 'WD-WXL1AC73EVDU' | Get-PhysicalDiskStorageNodeView
The command will return something like this:
   StorageNodeObjectId: {1}\\CLUSTOR\ROOT/microsoft/windows/storage/providers_v2\SPACES_StorageNode.ObjectId="{c5edeb90-e0c3-487e-bcb7-6c166cd5db95}:SN:Server1"

DiskNumber            : 2011
IsPhysicallyConnected : False
HealthStatus          : Healthy
OperationalStatus     : OK
IsMpioEnabled         : False
LoadBalancePolicy     :
PathId                :
PathState             :
StorageNode           : MSFT_StorageNode (ObjectId = "{1}\\CLUSTOR\ROOT/microsoft/windows/sto...)
PhysicalDisk          : MSFT_PhysicalDisk (ObjectId = "{1}\\CLUSTOR\ROOT/microsoft/windows/sto...)

   StorageNodeObjectId: {1}\\CLUSTOR\ROOT/microsoft/windows/storage/providers_v2\SPACES_StorageNode.ObjectId="{c5edeb90-e0c3-487e-bcb7-6c166cd5db95}:SN:Server2"

DiskNumber            : 2011
IsPhysicallyConnected : True
HealthStatus          : Healthy
OperationalStatus     : OK
IsMpioEnabled         : False
LoadBalancePolicy     :
PathId                :
PathState             :
StorageNode           : MSFT_StorageNode (ObjectId = "{1}\\CLUSTOR\ROOT/microsoft/windows/sto...)
PhysicalDisk          : MSFT_PhysicalDisk (ObjectId = "{1}\\CLUSTOR\ROOT/microsoft/windows/sto...)

IsPhysicallyConnected : True on SN:Server2 being the important part.
I think there has to be another, easier way (or I hope so), but it should be enough for your purpose.

A: I know this is old but this is a quick copy/paste I used
$a = @()
Get-PhysicalDisk |  where { $_.SlotNumber -ne $null} |
ForEach-Object {
    $d=$_| Get-PhysicalDiskStorageNodeView |  where { $_.IsPhysicallyConnected } | select StorageNodeObjectId
    $f=$d.StorageNodeObjectId -match '.*SN:(.*)"'
    $a += [pscustomobject]@{
        Server = $Matches.1;
        SlotNumber=$_.SlotNumber;
        DeviceId = $_.DeviceId;
        OperationalStatus = $_.OperationalStatus;
        HealthStatus=$_.HealthStatus;
        SerialNumber=$_.SerialNumber;
        Name=$_.FriendlyName;
    }
}
$a | Sort-Object -property Server,SlotNumber | Format-Table


text:
Q: Bootstrap 4 dropdown with search How to implement the data-live-search="true" in bootstrap 4 dropdown?
Below link contained a good explanation, however it was for Bootstrap 3.
Bootstrap 3 select

A: As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.
Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).

A: I could not find a standard control and had 0 intention to use a library such as bootstrap select so I custom made this widget. Bootstrap 4 allows you to add forms inside your dropdown which is what I have used here. I added a search box, used an input event to capture the text entered by the user inside the box, If the phrase entered by the user starts with the items inside the box, I show the items else I hide them. I also handle the click event on any item to change the text of the dropdown button

//Initialize with the list of symbols
let names = ["BTC","XRP","ETH","BCH","ADA","XEM","LTC","XLM","TRX","MIOTA","DASH","EOS","XMR","NEO","QTUM","BTG","ETC","ICX","LSK","XRB","OMG","SC","BCN","ZEC","XVG","BCC","DCN","BTS","PPT","DOGE","BNB","KCS","STRAT","ARDR","SNT","STEEM","USDT","WAVES","VEN","DGB","KMD","DRGN","HSR","KIN","ETN","GNT","REP","VERI","ETHOS","RDD","ARK","XP","FUN","KNC","BAT","DCR","SALT","DENT","ZRX","PIVX","QASH","NXS","ELF","AE","FCT","POWR","REQ","AION","SUB","BTM","WAX","XDN","NXT","QSP","MAID","RHOC","GAS","LINK","GBYTE","MONA","SAN","ENG","ICN","BTCD","SYS","XZC","VEE","POE","TNB","PAY","DGD","WTC","PAC","ZCL","GNO","LEND","CVC","RDN","BNT","NEBL","GXS","ACT","DBC","ENJ","STORM","STORJ","GAME","VTC","COB","UKG","SKY","CND","SMART","NAV","CNX","XBY","MED","CMT","RPX","PLR","CTR","BAY","BLOCK","ANT","R","UBQ","SNM","MCO","AST","MANA","SNGLS","ITC","RCN","FLASH","AMB","DATA","EDG","ATM","XPA","DNT","RLC","PART","ADX","ST","TRIG","EMC2","WABI","BRD","ETP","BURST","XSH","DTR","BCO","WINGS","FUEL","ZEN","NULS","EMC","MOON","PPP","MGO","XCP","SRN","1ST","TNT","PPC","MOD","LBC","THC","LA","DCT","MLN","UTK","SPANK","RISE","CLOAK","XAS","EDO","CDT","DPY","QRL","WGR","MTL","GTO","AGRS","GVT","PRL","VIA","ADT","GRS","COSS","AEON","GRID","YOYOW","SHIFT","HST","VOX","MTH","INK","FTC","XSPEC","NYC","NLG","CFI","PRE","TRST","VIB","LUN","BNTY","SLS","GUP","EVX","SNOV","DLT","UNITY","JINN","MER","ECN","PURA","MINT","NLC2","POT","ZSC","TKN","HMQ","NMC","WRC","VIBE","AMP","DIME","PEPECASH","BITCNY","RVT","PPY","PASC","DAT","PRO","TIX","ION","BCPT","BLK","TAAS","COLX","NET","DMD","IOC","AIR","MDA","PAYX","MNX","STX","BITB","SIB","IXT","XEL","NMR","LRC","DRT","GRC","LMC","CRW","ELIX","HEAT","MSP","EXP","FAIR","XMY","SLR","OMNI","NEU","GOLOS","MUE","BTX","PHR","FLIXX","ONION","DIVX","HVN","PBL","OAX","XWC","MUSIC","ECC","BOT","ATB","DOVU","EAC","ARN","PKT","NEOS","ART","KICK","LKK","XRL","RADS","VRC","OK","VOISE","CREDO","POLL","SPRTS","TIPS","LINDA","PST","FLDC","NSR","PLBT","LOC","RBY","NXC","DBET","ZOI","HUSH","TGT","CAG","SBD","ALIS","PTOY","ECOB","XLR","COVAL","MYST","SWT","BIS","AVT","SNC","GCR","GAM","PINK","PRG","XNN","BLUE","QAU","BCAP","IFT","INCNT","POSW","FLO","IOP","XST","DNA","DTB","TIME","GEO","BMC","ORME","PIX","OTN","MYB","SPF","QWARK","OCT","ENRG","CRED","CLAM","ESP","CARBON","HDG","NIO","GMT","WILD","SOAR","WCT","PND","CAT","STAK","ODN","RMC","ABY","CURE","ICOS","BSD","BITUSD","OBITS","BBR","FRST","XPM","BET","XVC","SEQ","BCY","TX","DOPE","CSNO","CANN","XMCC","SUMO","WISH","OXY","SPR","BTM","TFL","BQ","DICE","LEO","OPT","UNO","NVST","SPHR","SNRG","XUC","PRIX","DBIX","PFR","PLU","NTRN","ATMS","SSS","SYNX","ALQO","PTC","BWK","1337","HYP","2GIVE","ETT","SEND","UFR","ZNY","RUP","MEME","DOT","DRP","GLD","REAL","GBX","BELA","TCC","VSX","CRC","BRX","VRM","CRB","SXC","LUX","ITNS","XAUR","AUR","UNIT","QRK","INXT","UFO","B2B","IXC","AC","START","KORE","BRK","BTDX","SCL","XBC","PIRL","IND","TZC","RIC","ARC","BUZZ","QVT","ZEIT","NVC","INN","BDL","HBT","HGT","HWC","REX","NOTE","EXCL","BLITZ","PURE","NOBL","MTNC","VIVO","FYP","BBT","CHC","XTO","ERO","APX","EDR","USNBT","VSL","CRAVE","EBST","ASTRO","TOA","FOR","ADST","CHIPS","VTR","BTCZ","BPL","ERC","808","PZM","PDC","TRUST","XMG","ZEPH","DYN","LIFE","PUT","BON","ADC","BUN","XCN","UNIFY","SMART","TRC","CREA","MAG","EGC","CVCOIN","EQT","WDC","ANC","GOOD","HOLD","FRD","ATS","B3","ELTCOIN","LDOGE","HUC","TKS","DGPT","FJC","SWIFT","ATL","XFT","REC","ONG","XGOX","PKB","MXT","ELLA","CFT","KRB","AHT","MBRS","DNR","PING","RKC","RNS","DCY","EBTC","YOC","GIM","MZC","MCAP","ZRC","BLU","ETBS","EFL","FST","NET","FLT","CTX","ARC","GCC","XCPO","CBX","TTC","MOIN","PBT","HAT","GUN","BASH","NKA","IFLT","LINX","EBET","FLIK","DP","EPY","BLAS","DFT","MEC","ENT","SMC","OCL","RAIN","STA","KLN","GRE","V","UIS","ALT","EFYT","GRWI","XLC","FYN","STU","CMPCO","DAXX","CFD","DAR","MRT","UNB","OTX","LANA","KEK","PIPL","ZET","ZER","BYC","NDC","LGD","TRUMP","BTA","ADL","XPTX","INFX","ERC20","KURT","NUKO","DGC","FCN","BRO","INSN","XPD","VISIO","TRCT","FC2","CDN","ABJ","SGR","BBP","ZENI","HTC","DAI","WHL","RC","STRC","Q2C","TRI","ATOM","I0C","SIFT","SMLY","TES","MAC","ZCG","NETKO","KLC","ADZ","PROC","ICOO","DSR","TIT","XBL","CRM","LOG","ELE","PIGGY","SAGA","UTC","EMV","MNE","JNS","MCRN","CCT","CJ","ACC","CPC","TOKEN","WGO","XIOS","NYAN","BTCS","PASL","SIGT","MNC","AU","SKIN","TROLL","BITS","CNT","XCXT","GB","FUCK","HBN","8BIT","YTN","ROC","42","MAX","B@","USC","SOON","SDRN","BTB","BPC","KOBO","RIYA","HODL","ORB","NTO","CCN","TRK","PXC","HPC","DEM","DIX","CNO","VIDZ","GAIA","DSH","RBT","ONX","OPAL","BRIT","CV2","HAL","RED","4CHN","C2","TKR","BUCKS","XPY","DRXNE","XHI","POS","ARI","TRDT","LBTC","SDC","BTCRED","CORG","WTT","TAG","ETG","ALTCOM","XJO","EVIL","KUSH","XRA","PCOIN","VOT","BCF","DDF","FNC","AMMO","BOLI","PAK","CCO","MARS","VLT","RLT","BIGUP","SPACE","MONK","CUBE","XCT","EGAS","PR","SUPER","RBX","UNY","TEK","LCP","EMD","GAP","BLC","ITI","NTWK","UNIC","JET","CCRB","GRIM","TSE","LTB","CAT","EOT","ICOB","CHESS","BTSR","COAL","MAD","888","AMS","KRONE","POST","MOJO","XGR","VAL","BITBTC","KAYI","WYV","ZZC","BSTY","DFS","MNM","PXI","EL","SLG","BERN","BTWTY","HERO","EBCH","CRX","DALC","QTL","SWING","STV","EUC","KED","TGC","VUC","MAR","ECASH","STARS","ERY","ZUR","ETHD","CMT","BAS","EREAL","SOIL","HNC","BRAT","GTC","IMS","CNNC","SHDW","BNX","ARG","SRC","GLT","BTG","PX","XVP","NRO","MAO","IETH","MOTO","XRE","MTLMC3","ICN","UNITS","HONEY","AERM","PHS","EVO","CACH","FUNC","SPEX","CON","HXX","HMP","XCO","EAGLE","611","ECO","DUO","GP","FLAX","XCRE","REE","ZMC","BITSILVER","CPN","SCORE","GPU","ACOIN","USDE","BUMBA","CXT","XCS","$$$","ARCO","RPC","MST","SPT","BLN","FIRE","JIN","SFC","BIP","TAJ","QCN","GPL","XBTS","RBIES","NEVA","RUPX","BOAT","VPRC","BENJI","MAY","SONG","OFF","ALL","CWXT","E4ROW","300","ASAFE2","BTPL","FUZZ","BSTAR","IMX","MSCN","LUNA","ICON","CTO","WBB","PLACO","COXST","SLEVIN","CTIC3","UET","CF","DRS","EXN","PEX","ARGUS","TYCHO","PIE","BITEUR","URC","PRX","PRC","PLNC","DOLLAR","BTQ","ROOFS","WOMEN","ATX","BRAIN","SOCC","GEERT","XBTC21","QBC","ZYD","LTCU","RIDE","VLTC","MILO","VIP","DIBC","LTCR","ACP","FXE","CRDNC","VRS","ELS","JS","AGLC","KNC","LIR","ZNE","LVPS","JOBS","HVCO","CTIC2","SANDG","XRC","CRTM","MGM","IBANK","NODC","P7C","VOLT","CREVA","TSTR","SLFI","NANOX","GSR","XNG","HMC","EBT","DGCS","DMB","ABN","ECA","PHO","GCN","VTA","PGL","RUSTBITS","YASH","INPAY","FIMK","ITT","CRYPT","FUNK","SHORTY","BLOCKPAY","POP","CASINO","LNK","LOT","MBI","METAL","ITZ","BXT","STS","AMBER","MRJA","BTCR","UNI","WAY","BRIA","SCRT","BLZ","GLC","GRT","BITZ","NEWB","AIB","MUT","SH","J","FRC","ISL","FLY","SLING","CYP","RMC","TALK","ICE","FRK","MEOW","WMC","SAC","VC","BITGOLD","YAC","ANTI","WORM","LEA","DLC","BOST","VEC2","WARP","GCC","URO","DES","FLVR","QBK","DBTC","BVC","MND","DRM","STEPS","BLRY","JWL","TOR","GBT","ARB","PULSE","ADCN","RSGP","G3N","EGO","BIOS","CASH","MRNG","MTM","IMPS","ORLY","BSC","DLISK","SCS","CRT","OS76","PONZI","CESC","XOC","TAGR","ALTC","CAB","SDP","BIOB","FRAZ","GBC","CCM100","LEX","CONX","SOJ","ULA","PIZZA","OCEAN","CALC","APW","ATMC","NAS","GNX","SMT","BIX","GTC","BCD","MOT","QLC","SPHTX","TSL","HTML","AMM","CAT","QBT","PRO","HPY","ACE","BCX","INF","CAPP","NGC","SHND","SBTC","ENT","MKR","DIM","B2X","FRGC","LLT","CMS","VIU","DEW","WC","UGT","XTZ","MDS","CLUB","IRL","AI","CMS","BIG","HBC","HTML5","FIL","IGNIS","EAG","GBG","BTCA","XID","ESC","BCDN","PAYP","TOK","IFC","LBTC","UQC","VASH","KBR","BSR","BTE","EXRN","XIN","GRX","UBTC","CPAY","MAGE","PLAY","KARMA","MAGN","SAFEX","ANI","SFE","QBT","FDX","SBC","ZENGOLD","TIE","GBRC","GAIN","STAR","PEC","BEST","MGC","TER","DAV","PCN","PYLNT","SHA","NEOG","PLC","ACES","WAND","SISA","MARX","SUR","MONEY","COUPE","FLAP","SIGMA","TOP","BOS","SJCX","DMC","TURBO","MSD","MINEX","ETT","MTX","CYC","VULC","ACC","THS","GAY","WIC","XSTC","LTG","BTCS","SCT","FONZ","BT1","SKR","WOW","ZBC","FAZZ","UR","DON","DAY","TRIA","HDLB","WINK","BT2","CMP","IQT","SAK","BITOK","FUDD","PLX","PRN","PNX","BTCM","MCI","EUSD","FRN","EDRC","ELITE","EVC","UAHPAY","RYZ","SKC","DUTCH","EVR","XTD","NTC","TELL","HIGH","WSX","YES","ZSE","FFC","LEPEN","RCN","HALLO","BXC","INDIA","EGOLD","COR","BLX","ASN","PRES","NAMO","UNRC","OX","GOLF","FID","APC","CYDER","GLS","GRN","RUNNERS","REGA","BTC2X","BTBc","ANTX","SND","PCS","UNC","TODAY","GMX","ABC","CHEAP","DISK","WA","PRIMU","MCR","X2","ELC","PDG","HYTV","BSN","ACN","POKE","AKY","DEUS","CASH","LAZ","SKULL","RUPX","CC","HNC","MONETA","ROYAL","QORA","MAVRO","BIRDS","FAP","TCOIN","EBIT","KASHH","LDCN","XOT","CME","BLAZR","GARY","IBTC","LKC","NBIT","SPORT","DBG","STEX","YEL","BUB","IPY","TEAM","AXIOM","PRM","ELTC2","BITCF","GML","SNAKE","UTA","9COIN","HYPER","AV","XVE","10MT","FUTC","XQN","LTH","RUBIT","BIT","TLE","SHELL","XDE2","FBL","CBD","FRWC","DASHS","DUB","MMXVI","OMC","FC","PSY","OP","TOPAZ","RICHX","SWP","TCR","HCC","TRICK","BAC","IVZ","XAU","MEN","OPES","XID","VOYA","MBL","BET","BAT","RBBT","BGR","EGG","DCRE","TESLA","TERA","RHFC","GUC","ADK","XRY","EMB","CSC","OCOW","BTU","XYLO","STC","QC","FRCT","MDC"]

//Find the input search box
let search = document.getElementById("searchCoin")

//Find every item inside the dropdown
let items = document.getElementsByClassName("dropdown-item")
function buildDropDown(values) {
    let contents = []
    for (let name of values) {
    contents.push('<input type="button" class="dropdown-item" type="button" value="' + name + '"/>')
    }
    $('#menuItems').append(contents.join(""))

    //Hide the row that shows no items were found
    $('#empty').hide()
}

//Capture the event when user types into the search box
window.addEventListener('input', function () {
    filter(search.value.trim().toLowerCase())
})

//For every word entered by the user, check if the symbol starts with that word
//If it does show the symbol, else hide it
function filter(word) {
    let length = items.length
    let collection = []
    let hidden = 0
    for (let i = 0; i < length; i++) {
    if (items[i].value.toLowerCase().startsWith(word)) {
        $(items[i]).show()
    }
    else {
        $(items[i]).hide()
        hidden++
    }
    }

    //If all items are hidden, show the empty view
    if (hidden === length) {
    $('#empty').show()
    }
    else {
    $('#empty').hide()
    }
}

//If the user clicks on any item, set the title of the button as the text of the item
$('#menuItems').on('click', '.dropdown-item', function(){
    $('#dropdown_coins').text($(this)[0].value)
    $("#dropdown_coins").dropdown('toggle');
})

buildDropDown(names)
.dropdown {
  margin: 20px;
}

.dropdown-menu {
  max-height: 20rem;
  overflow-y: auto;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

    <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdown_coins" data-toggle="dropdown" aria-haspopup="true"
        aria-expanded="false">
        Coin
    </button>

        <form class="px-4 py-2">
            <input type="search" class="form-control" id="searchCoin" placeholder="BTC" autofocus="autofocus">
        </form>

No coins found

UPDATE 1
The code above uses show() and hide() inside a loop which is why the UI is slow when you clear everything you typed in case you didn't notice. Instead of that, use .css({display: 'none'}) and .css({display: 'block'})

A: As of version 1.13.1 there is support for Bootstrap 4:
https://developer.snapappointments.com/bootstrap-select/
The implementation remains exactly the same as it was in Bootstrap 3:

*

*add class="selectpicker" and data-live-search="true"to your select

*add data-tokens to your options. The live search will look into these data-token element when performing the search.

This is an example, taken from the site of the link above:
<select class="selectpicker" data-live-search="true">
  <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
  <option data-tokens="mustard">Burger, Shake and a Smile</option>
  <option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>

Live search for the search term 'fro' will only leave the third option visible (because of the data-tokens "frosting").
Don't forget to include the bootstrap-select CDN .css and .js in your project.
I am very glad to see this live search become available again, because it comes in very handy when presenting large dropdown lists to the user.

A: dropdown with search using bootstrap 4.4.0 version

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div
    = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i  -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  <button onclick="myFunction()" class="dropbtn">Dropdown</button>

    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    home
    contact

A: I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.

$('.dropdown').each(function(index, dropdown) {

  //Find the input search box
  let search = $(dropdown).find('.search');

  //Find every item inside the dropdown
  let items = $(dropdown).find('.dropdown-item');

  //Capture the event when user types into the search box
  $(search).on('input', function() {
    filter($(search).val().trim().toLowerCase())
  });

  //For every word entered by the user, check if the symbol starts with that word
  //If it does show the symbol, else hide it
  function filter(word) {
    let length = items.length
    let collection = []
    let hidden = 0
    for (let i = 0; i < length; i++) {
      if (items[i].value.toString().toLowerCase().includes(word)) {
        $(items[i]).show()
      } else {
        $(items[i]).hide()
        hidden++
      }
    }

    //If all items are hidden, show the empty view
    if (hidden === length) {
      $(dropdown).find('.dropdown_empty').show();
    } else {
      $(dropdown).find('.dropdown_empty').hide();
    }
  }

  //If the user clicks on any item, set the title of the button as the text of the item
  $(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
    $(dropdown).find('.dropdown-toggle').text($(this)[0].value);
    $(dropdown).find('.dropdown-toggle').dropdown('toggle');
  })
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

  <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Benutzer
    </button>

    <form class="px-4 py-2">
      <input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
    </form>

      <input type="button" class="dropdown-item" type="button" value="Test1" />
      <input type="button" class="dropdown-item" type="button" value="Test2" />
      <input type="button" class="dropdown-item" type="button" value="Test3" />

No entry found

A: You can consider using Popper.js to manage your popup.
It comes bundled with Bootstrap or you can use it
separately.
This is a very rough example and how you want to hide/show the popup
is your choice.

const popupReference = document.getElementById('popup-reference');
const popup = document.getElementById('popup')
const popper = Popper.createPopper(
  popupReference, popup, {
    placement: 'bottom-start',
    modifiers: [
          {
            name: 'offset',
            options: {
              offset: [0, 2],
            },
          },
        ],
  }
)
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

  <title>Hello, world!</title>

        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-search" viewBox="0 0 16 16">
  <path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>

      <input type="text" class="form-control" id="popup-reference" placeholder="Search..." aria-label="Search" value="Item">

      <button type="button" class="list-group-item list-group-item-action" aria-current="true">
    The first item
  </button>
      <button type="button" class="list-group-item list-group-item-action">A second item</button>
      <button type="button" class="list-group-item list-group-item-action">A third button item</button>


text:
Q: Unable to add particles.js I'm trying to create a single scrolling webpage consisting of three pages

$('a.page-scroll').on('click', function(event) {
  var $anchor = $(this);
  $('html, body').stop().animate({
    scrollTop: $($anchor.attr('href')).offset().top - 60
  }, 1000);
  event.preventDefault();
});
* {
  margin-top: 0;
  margin-bottom: 0;
}

#page1 {
  height: 1000px;
  background-color: #000;
  color: white;
}

#page2 {
  height: 1000px;
  color: white;
  background-color: #18121e;
  padding-top: 140px;
  border-top: 100px;
}

#page3 {
  height: 650px;
  color: white;
  background-color: #233237;
  background-size: cover;
  padding-top: 200px;
}

body {
  padding-top: 0px;
}

#page1 p {
  padding-top: 100px;
  font-size: 2.5rem;
}

#page1 p #highlight {
  color: pink !important;
}

#page2 h3 {
  padding-bottom: 80px;
  line-height: 1.5;
}

#page3 h3 {
  padding-bottom: 100px;
  line-height: 1.5;
}

.btn {
  color: white;
  background-color: #000 !important;
}

.btn:hover {
  color: gray;
}

@media screen and (max-width: 990px) {

  .btn ~ .btn {
    margin-top: 10px;
  }

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Rashid Naushad

About

Portfolio

Contact

Hi !

I'm a self taught web developer based in India.

 I'm an undergraduate student pursuing economics who just loves to code.

 I dream of combining my knowledge of programming, economics, and

financial markets for the betterment of the society.

 Languages and Frameworks:

 HTML5, CSS3, Bootstrap3,

 Javascript, jQuery, Angular.js, Meteor.js,

 Node.js, React,js,

 Python, php..

 Tools & expertise: Git, Responsive Web Design.

Here is my latest portfolio,
I'll be adding more as I learn and grow..

Think I can be of any help to you?
Wanna collaborate?
Shoot me a message, now!

    GitHub

    freeCodeCamp

    Gmail

I want to add background cover as particles.js for the first page .I tried doing as described in the GitHub particles.js, but failed miserably.
Where exactly am I going wrong?
Here is the JSFiddle.

A: In your jsfiddle you never actually invoked the particles method. Furthermore, text sitting on top of the particles needs to be absolutely positioned;
Here's your working functional example
Note that particles-js needs to be initialized and configured, here's what I used:
particlesJS("particles-js", {
  "particles": {
    "number": {
      "value": 80,
      "density": {
        "enable": true,
        "value_area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "nb_sides": 5
      },
      "image": {
        "src": "img/github.svg",
        "width": 100,
        "height": 100
      }
    },
    "opacity": {
      "value": 0.5,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 1,
        "opacity_min": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 3,
      "random": true,
      "anim": {
        "enable": false,
        "speed": 40,
        "size_min": 0.1,
        "sync": false
      }
    },
    "line_linked": {
      "enable": true,
      "distance": 150,
      "color": "#ffffff",
      "opacity": 0.4,
      "width": 1
    },
    "move": {
      "enable": true,
      "speed": 6,
      "direction": "none",
      "random": false,
      "straight": false,
      "out_mode": "out",
      "bounce": false,
      "attract": {
        "enable": false,
        "rotateX": 600,
        "rotateY": 1200
      }
    }
  },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "grab"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 140,
        "line_linked": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 40,
        "duration": 2,
        "opacity": 8,
        "speed": 3
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      },
      "push": {
        "particles_nb": 4
      },
      "remove": {
        "particles_nb": 2
      }
    }
  },
  "retina_detect": true
});


text:
Q: LogicException error: Passed array does not specify an existing static method here to ask is any error for my autoloader class/function with spl_autoload_register?
appreciate for helping.
here is my code
<?php

namespace system\core;

// if(!defined('IN_APP')){
    // exit('Access Denied');
// }

define('ROOT', $_SERVER['DOCUMENT_ROOT']);
define('DS', DIRECTORY_SEPARATOR);

if(function_exists('spl_autoload_register')){

    spl_autoload_register(array('core', 'autoload'));

}else{

    function __autoload($class){

        return core::autoload($class);

    }

}

A:createapp();

class core
{

    private static $_app;

    public static function createapp(){

        if(!is_object(self::$_app)){

            self::$_app = 'something';

        }

        return self::$_app;
    }

    public static function autoload($class){

        $class = trim(strtolower($class));

        if(strpos($class, '\\') !== false){

            $path = ROOT;

            $path .= DS . $class . '.php';

            $path = preg_replace('/[\\|\/]/i', DS, $path);

            require_once($path);

        }

    }

}

class A extends core {}

and i got this error
Fatal error: Uncaught exception 'LogicException' with message 'Passed array does not specify an existing static method (class 'core' not found)' in C:\xampp\htdocs\test\system\core.php:14 Stack trace: #0 C:\xampp\htdocs\test\system\core.php(14): spl_autoload_register(Array) #1 {main} thrown in C:\xampp\htdocs\test\system\core.php on line 14

after i read the error msg, it mean the class core not found? but the class is written in the same file???

A: You must set a fully qualified name. Because your class is in system\core namespace:
spl_autoload_register(array('system\core\core', 'autoload'));


text:
Q: Installing and Using System.Data.SQLite (An ADO.NET provider) I am a newbie in regards to System.Data.SQLite and .NET, so bear with me. I can't seem to get System.Data.SQLite even installed correctly. The self-installer completed and everything seemed to be kosher, but nothing seems to be working. In VC# Express, I tried to create a little sample program(http://pastebin.com/m8f7cec), but it's saying that it can't find System.Data.SQLite at the line: using System.Data.SQLite;. Also the Database explorer always errors out when I try to make a new connection, starting with, "Could not load file or assembly Microsoft.VisualStudio.Data"... I also don't know what to put in the Connection string. Can someone help just get this started? I am familiar with SQLite itself.
Thanks,
deftonix

A: All the installer does is put the proper libraries on your local machine, as well as enable the plug-ins within Visual Studio to allow you to explore your databases via Server Explorer.
You still need to Right Click on your "References" section in your project and add a reference to the library in order for it to work at runtime.

A: You need to add a reference within your project to the System.Data.SQLite dll.
For the connection string, try http://www.connectionstrings.com, it has the format for most common connections.

A: This is now available through NuGet (the question was asked 8 years ago when I'm guessing it was not in NuGet).
Add it with NuGet and that will download the DLL(s) and add it as a reference.


text:
Q: Assignment to entry in nil map when using http header with Echo golang here is my test using testing package and echo web http framework :
(webserver variable is a global echo instance)
func TestRunFunction(t *testing.T){
    req := new(http.Request)
    **req.Header.Set("Authorization","Bearer "+loginToken.Token)**
    rec := httptest.NewRecorder()
    c := WebServer.NewContext(standard.NewRequest(req, WebServer.Logger()), standard.NewResponse(rec, WebServer.Logger()))
    c.SetPath(path)
    if assert.NoError(t , RunFunction(c)){
        assert.Equal(t,http.StatusOK, rec.Code)
    }
}

Im trying to test some function that called by REST GET method, but I get this panic error :
panic: assignment to entry in nil map [recovered]
        panic: assignment to entry in nil map

The panic is on the line in bold (astrix in the code), when Im trying to set the header. What am I doing wrong?

A: The error is self explanatory: req.Header is nil; you cannot assign to a nil map.
The solution is to either:

*

*Initialize req.Header with a new instance of net/http.Header
req.Header = make(http.Header)

*Or, create the req variable with net/http.NewRequest, which does all the internal initializing for you:
req, err := http.NewRequest("GET", "https://example.com/path", nil)
if err != nil {
    panic(err)
}
req.Header.Set("Authorization","Bearer "+loginToken.Token)


text:
Q: How can I convert/copy SQL query result to JSON? I'm trying to figure out what would be my SQL query to result in this JSON format like this:
{
   "body": {
       "environments": {
           "lapilops": {
               "api_url": "1",
               "dlc_url": "1",
               "dlc_ver": "1,
               "site_url": "1",
               "photon_url": "1",
               "logcollection_url": "1",
               "env_name": "greatness"
           }
       }
   }
}

I have a table named lapilops and all the columns are included. My sql query is:
select *
from lapilops
where
Ticket = "1" AND
version = "1" AND
ios = "adr";

When I copy/convert the result as JSON format it turns to this:
{
    "data":
    [
        {
            "Ticket": 1,
            "version": "1",
            "os": "adr",
            "api_url": "1",
            "dlc_url": "1",
            "dlc_ver": "1",
            "site_url": "1",
            "photon_url": "1",
            "logcollection_url": "1",
            "env_name": "greatness"
        }
    ]
}

Do I need to add a table named "environments" and "body"?
I am running my SQL query and copying the result of the query in Sequel Pro.

A: You are going to be doing a lot with JSON_OBJECT that will not look pretty if you are going to do it in SQL. Could you read it into an application and use some library to serialize the data into a JSON format?


text:
Q: Ajax start image (loading image) shows for first ajax call but fails on subsequent ajax calls I am failry new to jQuery. I am trying to get a div (loading_div) to show during Ajax calls and then disappear when the ajax call finishes. This work fine for the first call but subsequent calls do not trigger the loading_div. I know this is a basic issue related to the DOM, and there is at least one similar question on stack about this, but its not really exactly the same. I have failed to modify the answer to suit my problem. Any help would be appreciated.
 $(function(){
   var $loading = $('.loading_div').hide();
   $(document)
    .ajaxStart(function () {
        $loading.show();
    })
    .ajaxStop(function () {
        $loading.hide();
    });
 });

Tried this...(altered the HTML see below)..but still no luck. I though adding the on() would help. Anyone?.....pulling my hair out at this point. To give some more background, this is an implementation of the load dots jQuery plugin. The plugin works and the first ajax call triggers the function below. Its just subsequent calls will not trigger it unless i refresh the page.
HTML
      <div class="loading_div">

      </div>

JQuery
$(function(){

    $(document).on("ajaxSend", function(){
    $('.loading_div').append($('#loadingdots'));
    })
    $(document).on("ajaxComplete", function(){
    $('.loading_div').remove($('#loadingdots'));
    });
  });

A: You need to use AjaxSend() and AjaxComplete(). The methods you are using are meant to run only the first ajax call.


text:
Q: Directory Symbolic Links do not appear in Start Menu/All apps on Windows 10 In windows 7 I had a folder in "C:\Users\myusername\AppData\Roaming\Microsoft\Windows\Start Menu\Programs" that was a symlink to a UNC path on a network share. That folder (and the programs inside it) was then available from the Start Menu->All Programs menu.
When I upgraded to Windows 10, that folder doesn't appear in Start Menu->All Apps. It doesn't seem to matter whether the symlink is to a local folder or a network share, or whether it's a symlink or a junction.
Any thoughts about how to accomplish this on Windows 10?


text:
Q: Foreign key fails on deletion because Hibernate doesn't remove association first I have a problem with constraint fail when I cascade-delete entity which references another entity.
I'm using Hibernate as my JPA Provider.
Domain model:

*

*Every Zone can have more Actions, but Actions are not shared between Zones (OneToMany).

*TeleportAction (one possible kind of Action) contains a set of Zones as targets. Every TeleportAction can have more Zones as targets and Zones and they can be used by multiple TeleportActions (ManyToMany).

How deletion works

*

*I call ZoneManager.deleteZone(zone)

*

*ZoneManager first loops through all Zones and their TeleportActions and removes deleted Zone from their targets.

*After that ZoneManager removes given Zone from it's list of Zones

*Then I delete Zone from DB with Hibernate via session.delete(zone). This operation propagates to Actions.

*List item

First ZoneManager.deleteZone(zone) is called, which works like this:
public void deleteZone(Zone removedZone) {

    // Remove this zone from all TeleportActions
    for (Zone zone : zones) {
        for (Action action : zone.getActions()) {
            if (action instanceof TeleportAction) {
                ((TeleportAction)action).removeTarget(removedZone);
            }
        }
    }

    // Finally remove zone
    zones.remove(removedZone);
}

then caller removes Zone from DB. I want Hibernate to automatically acknowledge that I've removed this Zone from Action targets.
session.delete(removedZone);

Error which I get
Hibernate: /* delete cz.iwitrag.greencore.gameplay.zones.Zone */ delete from gcore_Zone where id=?
[org.hibernate.engine.jdbc.spi.SqlExceptionHelper] SQL Error: 1451, SQLState: 23000
[org.hibernate.engine.jdbc.spi.SqlExceptionHelper] Cannot delete or update a parent row: a foreign key constraint fails (`309145_mysql_db`.`gcore_tpaction_targetzones`, CONSTRAINT `FK4rvpdg8xjyt6lk5281jbi78c5` FOREIGN KEY (`targetZone_id`) REFERENCES `gcore_Zone` (`id`))
[org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl] HHH000010: On release of batch it still contained JDBC statements
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
...

This error is caused because when I delete Zone, it is still target of some TeleportActions.
Even though I deleted this Zone from TeleportAction's targets in business code before calling session.delete(zone), Hibernate doesn't acknowledge it and doesn't remove this Zone from ManyToMany association.
Entities
Zone, which has List of Actions
@Entity
public class Zone {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true)
    @Cascade(CascadeType.ALL)
    @OrderColumn(name = "list_id")
    @JoinColumn(name = "zone_id")
    private List<Action> actions = new ArrayList<>();
...
}

Action, which is superclass of TeleportAction
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "actionType")
public abstract class Action {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
...
}

TeleportAction, which contains Set of Zones as teleport targets.
Please note that this relationship is different from Zone->Action relationship.
@Entity
@DiscriminatorValue("tp")
public class TeleportAction extends Action {

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "tpaction_targetzones", joinColumns = @JoinColumn(name="tpAction_id"), inverseJoinColumns = @JoinColumn(name="targetZone_id"))
    private Set<Zone> targets = new HashSet<>();
...
}

Question
How can I force Hibernate to automatically delete removed Zone from table tpaction_targetzones before it actually deletes Zone from database to avoid foreign key constraint error?


text:
Q: Display Custom Post Type Archive content with Shortcode So I've created a custom post type filled with Advanced Custom Fields only.
There is no "content".
I've created a single-custom.php, content-custom.php and archive-custom.php.
All looking nice and working perfect.
What I would like to achieve is to create a shortcode (I believe) for the archive-custom.php, so I can display the content of the archive-custom.php content on another part of my website, let's say on two different pages, with additional content.
At first i thought i create a short code for the custom post type it self by this example: Themed custom loop using shortcodes
But it's getting rather a very long short code. And everything I've solved before in content-custom.php, I have to start over in functions.php and "re-div-ify" it in the shortcode.

A: Most probably you need a bunch of divs etc duplicated in both archive-custom.php and the shortcode. Identify those divs, and move them into a new template file in your theme, e.g. in part-archive-custom.php.
Then, delete them from archive-custom.php and add a call to get_template_part('part-archive-custom'); instead.
Do the same inside your shortcode.


text:
Q: How to get values from nested json in php I have this json file
{
"success": true,
"data": {
    "total": "2",
    "returned": 2,
    "start": 0,
    "limit": 10,
    "transactions": [
        {
            "id": "16393567",
            "type": "Credit",
            "currency": "BTC",
            "amount": "0.00019449",
            "when": "2021-09-03 10:27:48",
            "rental": "3411209",
            "rig": "205363",
            "status": "Pending",
            "pending_seconds": "716202"
        },
        {
            "id": "16377905",
            "type": "Credit",
            "currency": "BTC",
            "amount": "0.00000203",
            "when": "2021-09-01 11:42:47",
            "rental": "3408621",
            "rig": "205363",
            "status": "Cleared",
            "pending_seconds": 0
        }
    ]
}

}
I am able to get values under data with this code
 $jsonCont = file_get_contents('temp.json');
 $content = json_decode($jsonCont, true);

 $rig_detail= $content['data']['total'];
 $rig_detail= $content['data']['returned'];
 $rig_detail= $content['data']['start'];
 $rig_detail= $content['data']['limit'];

My problem exists where I try and get data from "transactions" I have tried
 $rig_detail= $content['data']['transactions']['id'];

This however does not give me what I expected. What do I need to do to access the data within the transactions section?

A: the are more elements in $content['data']['transactions'], so it is an array.
Try something like this:
 $rig_detail= $content['data']['transactions'][0]['id'];


text:
Q: PHP MySQL problem Whenever I try to run a php script on my website hosted by hostgator, I get this error:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'pieboy13_(user name)' (1) in /home/pieboy13/public_html/quigley/WebContent/Scripts/register.php on line 6
  Error: Could not connect to server. Error Unknown MySQL server host 'pieboy13_(user name)' (1)

Where (Username) is my username.
What could cause this?

A: You are triying to connect to your username! Check your configuration for server url and make sure it points to your mysql server.

A: Things that can cause this:

*

*You are using the wrong hostname for the mysql server.

A: Looks like you might have put your database or username into the server argument.


text:
Q: How to change pageable messages of kendo grid in razor? I found in javascript but i could't manage to do it.
Can anyone say how "display" will be in razor?
pageable: {
    messages: {
        display: "{0} - {1} of {2} items", //{0} is the index of the first record on the page, {1} - index of the last record on the page, {2} is the total amount of records
        empty: "No items to display",
        page: "Page",
        of: "of {0}", //{0} is total amount of pages
        itemsPerPage: "items per page",
        first: "Go to the first page",
        previous: "Go to the previous page",
        next: "Go to the next page",
        last: "Go to the last page",
        refresh: "Refresh"
    }
}

Razor view
.Pageable(??)

A: Just to build up a little more on the previous answer.
.Messages(message => message.ItemsPerPage("ItemsPerPage"))
                    .Messages(message => message.Page("Page"))
                    .Messages(message => message.Of("Of"))
                    .Messages(message => message.Display("Display"))
                    .Messages(message => message.Empty("Empty"))
                    .Messages(message => message.First("First"))
                    .Messages(message => message.Last("Last"))
                    .Messages(message => message.Next("Next"))
                    .Messages(message => message.Previous("Previous"))
                    .Messages(message => message.Refresh("Refresh"))

A: Have a look at here.
   @(Html.Kendo().Grid(Model)
        .Name("grid")
        .Pageable(pager => pager
            .Messages(messages => messages.Display("Showing items from {0} to {1}. Total items: {2}"))
        )
        .DataSource(dataSource => dataSource
            .Ajax() // or Server()
            .Read(read => read.Action("Products_Read", "Home"))
        )
     )


text:
Q: Detect Utf -8 Encode and decode it in header response I want to get that amount of Content-Disposition key after receiving the respos and in webClient.ResponseHeaders.
So that I can extract the file name from it.
Content-Disposition values available:

"attachment; filename*=UTF-8''SC-FR-06-%D8%AF%D8%B1%D8%AE%D9%88%D8%A7%D8%B3%D8%AA%20%D8%AE%D8%B1%DB%8C%D8%AF.pdf; filename="SC-FR-06-%D8%AF%D8%B1%D8%AE%D9%88%D8%A7%D8%B3%D8%AA%20%D8%AE%D8%B1%DB%8C%D8%AF.pdf""

Now my first question is where does this UTF-8 encoder actually come from?
And the second question is I can not do anything if I decoder the UTF-8 encoder.

%D8%AF%D8%B1%D8%AE%D9%88%D8%A7%D8%B3%D8%AA%20%D8%AE%D8%B1%DB%8C%D8%AF

I'm Using .Net3.5 and Wpf.
please guide me


text:
Q: How to trigger Azure DevOps pipeline when pushing commits to bitbucket custom server? My company's repository hosted on bitbucket custom server which can be only accessed from intranet.
Therefore, I setup a self-host agent for Azure DevOps and this agent could do a git pull and build and release too.
It works and the problem is I have to manually click RUN pipeline to start, and somehow when I pushing commits to my bitbucket custom server it doesn't trigger the Azure DevOps to kick off a build or release.
Is there some other options I could let it automatically triggers the Azure pipeline to run? Webhooks or Hooks?

A: I afraid Azure devops pipeline cannot be automatically triggered from a bitbucket custom server. For azure devops server cannot communicate to the bitbucket server hosted in your intranet.
Webhooks or Hooks cannot trigger a build in azure devops pipeline either. Azure devops doesnot have this feature yet. There is an open issue about this.
Currently you might have to trigger your pipeline manually, or create an azure function as mentioned in above link to trigger your pipeline automatically.
Below are some documents about azure function you may find helpful:
Develop Azure Functions using Visual Studio
Continuous deployment for Azure Functions
Azure Functions HTTP trigger:The HTTP trigger lets you invoke a function with an HTTP request.
Best approach to call web api from azure function
Trigger Azure Pipelines build via API


text:
Q: R: Maximum Likelihood Estimation of a exponential mixture using optim I'm trying to get the parameters w, lambda_1, lambda_2 and p from a mixture bi-exponential model, using a loglikelihood function and the optim function in R. The model is the following

Here is the code
biexpLL <- function(theta, y) {
  # define parameters
  w <- theta[1]
  lambda_1 <- theta[2]
  a <- theta[3]
  lambda_2 <- theta[4]
  # likelihood function with dexp
  l <- w * dexp((y - a), rate = 1/lambda_1) + (1 - w) * dexp((y - a), rate = 1/lambda_2)

  - sum(log(l))
}
# Generate some fake data
w <- 0.7
n <- 500
lambda_1 <- 2
lambda_2 <- 0.2
set.seed(45)
biexp_data <- (w * rexp(n, 1/lambda_1) + (1 - w) * rexp(n, 1/lambda_2))
# Optimization
optim(par = c(0.5,0.1,0.001,0.2),
      fn=biexpLL,
      y=biexp_data)
#$par
#[1] -94789220.4     16582.9   -333331.7 134744336.2

The parameters are very different from the used in the fake data! What I'm doing wrong?

A: The original code is prone to warnings and errors since the parameters may go to invalid values easily.  For example, we need w in [0, 1] and lambda > 0.  Also, if a is larger than a data point, then the density becomes zero, hence infinite log likelihood.
The code below uses some tricks to handle these cases.

*

*w is converted to the range [0, 1] by the logistic function

*lambda are converted to positive values by the exponential function.

*Added tiny value to the likelihood to deal with cases of zero likelihood.

Also, the data generation process has been changed so that samples are generated from one of the exponential distributions with the given probability w.
Finally, increased the sample size since the result was not stable with n=500.
biexpLL <- function(theta, y) {
  # define parameters
  w <- 1/(1+exp(-theta[1]))
  lambda_1 <- exp(theta[2])
  a <- theta[3]
  lambda_2 <- exp(theta[4])
  # likelihood function with dexp
  l <- w * dexp((y - a), rate = 1/lambda_1) + (1 - w) * dexp((y - a), rate = 1/lambda_2)
  - sum(log(l + 1e-9))
}
# Generate some fake data
w <- 0.7
n <- 5000
lambda_1 <- 2
lambda_2 <- 0.2
set.seed(45)
n1 <- round(n*w)
n2 <- n - n1
biexp_data <- c(rexp(n1, rate=1/lambda_1),
                rexp(n2, rate=1/lambda_2))
# Optimization
o <- optim(par=c(0.5,0.1,0.001,0.2),
           fn=biexpLL,
           y=biexp_data)

1/(1+exp(-o$par[1]))
exp(o$par[2])
o$par[3]
exp(o$par[4])

On my environment I obtained the below.
The result seems reasonably close to the simulation parameters (note that two lambda values are swapped).
> 1/(1+exp(-o$par[1]))
[1] 0.3458264
> exp(o$par[2])
[1] 0.1877655
> o$par[3]
[1] 3.738172e-05
> exp(o$par[4])
[1] 2.231844

Notice that for mixture models of this kind, people often use the EM algorithm for optimizing the likelihood instead of the direct optimization as this.  You may want to have a look at it as well.

A: I have been able to get the parameters with the R package DEoptim :
library(DEoptim)

biexpLL <- function(theta, y)
{
  w <- theta[1]
  lambda_1 <- theta[2]
  lambda_2 <- theta[3]
  l <- w * dexp(y, rate = 1 / lambda_1) + (1 - w) * dexp(y, rate = 1 / lambda_2)
  log_Lik <- -sum(log(l))

  if(is.infinite(log_Lik))
  {
    return(10 ^ 30)

  }else
  {
    return(log_Lik)
  }
}

w <- 0.7
n <- 500
lambda_1 <- 2
lambda_2 <- 0.2
set.seed(45)
indicator <- rbinom(n = 500, size = 1, prob = w)
biexp_data <- (indicator * rexp(n, 1 / lambda_1) + (1 - indicator) * rexp(n,  1 / lambda_2))

obj_DEoptim <- DEoptim(fn = biexpLL, lower = c(0, 0, 0), upper = c(1, 1000, 1000), control = list(itermax = 1000, parallelType = 1), y = biexp_data)
obj_DEoptim$optim$bestmem

 par1      par2      par3
0.7079678 2.2906098 0.2026040


text:
Q: Rendering in backbone error I'm trying to render but i don't know perfectly javascript and compare this error:
Uncaught ReferenceError: wrapper is not defined.
I would render the result of collection's fetch in the same view.
     var HomeView = Backbone.View.extend({

 template: Handlebars.compile(template),

 events: {

  },

  initialize: function() {

      console.log("inhomeview");

      var amici = new Usercollection();
      amici.fetch({
      success: function() {
      amici.each(function(object) {

      console.log(object.toJSON());
      var wrapper=object.toJSON();

    });
   },
    error: function(amici, error) {
    // The collection could not be retrieved.
   }
       });

      this.render();

  },

   render: function() {

      var context=wrapper;
      var html =this.template(context);

      this.$el.html(html);

     return this;
     }

     });

    return HomeView;

      });

A: Perhaps you want to do something similar to this (please read comments in the code below):
var HomeView = Backbone.View.extend({

  template: Handlebars.compile(template),

  initialize: function() {
    // its better to pass collection into view and listen to its 'reset' event
    this.collection.on('reset', this.render, this)
  },

  render: function() {
    // convert collection to json and pass to template as "users"
    var html = this.template({users: this.collection.toJSON()});
    this.$el.html(html);
    return this;
  }

});

// This is how you should be using it later in your code:
// create collection and pass it in home view
var users = new Usercollection(),
    homeView = new HomeView({collection: users,
                             el: '#pagina'});
// fetch collection, this will trigger 'reset' event
// so your view will render itself
users.fetch();


text:
Q: Adding tags to files in VSCode I want to use VSCode as both a code editor and idea journal. And to apply a system like Zettelkasten, I would really like to see tags in the file itself, but I can't find any way to add them.
E.g. a note like
The dog walked to the park with a bone in his mouth

Could be labelled with #dog #walking #park

A: Trying to use a tool for things that it hasn't been designed for leads to a frustrating experience.
VSCode is a great code editor but it isn't a diary or an idea journal, even if you write in Markdown. I believe that you should keep these things separate because there are certain tools for this purpose. Please have a look at Obsidian, Foam, and Geeks Diary.

A: There is a plugin for VSCode : GitHub - chriswheeldon/vscode-ctags: A CTags extension for VSCode == CTags Support - Visual Studio Marketplace which seem to have many limitation.
I practice "notes-taking" this way inside Notepad++ (a 32bits version on win7-10 64bits), with the help of the excellent plugin SourceCookifier, which is written in C# language, and is implemented on Exuberant Ctags.
This plugin has limitations too : it "badly" supports Unicode ( Unicode chars display as "bad" ascii value/combination ex: é --> E9 , but doesn't raise any error : ugly for the Frenchman, but acceptable in comparison to the features it offers !).
Also, it constraints to the use of a 32bits Notepad++ version : I couldn't find any 64bits compiled version of this (old, orphan) plugin, and this is very sad !
This powerful plugin brings almost all programming language "basic" features like class, function, variable declaration, "jump to definition" inside code (ctrl+click), and can operate jump links threw a project folder. The Ctags results is displayed in a sidebar UI, as a list of lists.
It also lets the user to add definitions to a language (I added todo: bla bla bla to the languages I use), and we can create our own, named, "language" definitions, defined as a collection of regex expression, with one result per line : multi-line regex results are not supported.

*

*in:\b(TODO|DONE|FIX|NOTE): +?(.*)$ out:\1 : \2
will show the respective tag with full phrase (truncated by UI width)

*in:(#\w+) out:\1
will show the hashtag #tagged

*in:^def (\w+) *(\([^\)]+\)) *\:.* out:\1 \2
will show a python function definition, name and signature

One regex produces a list of results : list of lists ...
Good luck !


text:
Q: recyclerView fragment image not display using firebase Image is not load to the fragment if i remove the Glide image code it's run fine
but adding image run with error
I think i get the error because of the fragment but i don't understand what is it
  public void onBindViewHolder(AuthorListAdapter.MyViewHolder holder, int position) {
    holder.name.setText(authorList.get(position).getName());
    Glide.with(context).load(authorList.get(position).getImageUrl()).into(holder.image);
}

Here is the error:
 java.lang.NullPointerException: You cannot start a load on a not yet attached View or a  Fragment where getActivity() returns null (which usually occurs when getActivity() is called before the Fragment is attached or after the Fragment is destroyed).
  at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:27)
  at com.bumptech.glide.Glide.getRetriever(Glide.java:607)
  at com.bumptech.glide.Glide.with(Glide.java:638)
  at com.example.hardik.myapplication.AuthorListAdapter.onBindViewHolder(AuthorListAdapter.java:42)
  at com.example.hardik.myapplication.AuthorListAdapter.onBindViewHolder(AuthorListAdapter.java:22)
  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6508)
  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6541)
  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5484)
  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5750)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5589)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5585)
  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2231)
  at android.support.v7.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:556)
  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1518)
  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:610)
  at android.support.v7.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:170)
  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3719)
  at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3135)
  at android.view.View.measure(View.java:19759)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6124)
  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
  at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
  at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
  at android.view.View.measure(View.java:19759)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6124)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
  at android.view.View.measure(View.java:19759)
  at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
  at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
  at android.view.View.measure(View.java:19759)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6124)
  at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:719)
  at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:91)
  at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1361)
  at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:789)
  at android.view.View.measure(View.java:19759)
  at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1060)
  at android.view.View.measure(View.java:19759)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6124)
  at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
  at android.view.View.measure(View.java:19759)
  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6124)
  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
  at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
  at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
  at android.view.View.measure(View.java:19759)

Any help appreciated
Thank You

A: you can see in your log you get activity or context is null.
If you want to know why your activity is getting empty, then you can follow this answer. https://stackoverflow.com/a/43748449/8588259
then you can follow these steps,
1) write onAttach(Activity activity) in your fragment
@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}

2) pass this activity in your adapter
  val adapter = MyAdapter(activity)

3) now you can write glide code
  Glide.with(activity).load(imageUrl).into(view)

A: Try this
The issue itself occurs when getActivity() is called before the Fragment is attached or after the Fragment is destroyed.
So check getActivity() !=null and bind your image view
    if( getActivity()!= null ){

      Glide.with(getActivity()).load(authorList.get(position).getImageUrl()).into(holde
           r.image);
    }

    if( getActivity() != null ){

      Glide.with(getActivity()).load(authorList.get(position).getImageUrl()).into(holde
           r.image);
    }


text:
Q: What is the maximum entropy probability density function for a positive continuous variable of given mean and standard deviation? What is the maximum entropy distribution for a positive continuous variable, given its first and second moments?
For example, a Gaussian distribution is the maximum entropy distribution for an unbounded variable, given its mean and standard deviation, and a Gamma distribution is the maximum entropy distribution for a positive variable, given its mean value and the mean value of its logarithm.

A: I want to make @Glen_b's answer more explicit, here is an extra answer just because it wouldn't fit as a comment.
The formalism etc. is well explained in Chapter 11 and 12 of Jaynes' book.
Taking the uniform distribution as the base measure, the general solution, as @Glen_b already said, is a Gaussian
$$
f(x) \propto \mathcal{N}(x | -1/2 \lambda_1/\lambda_2, -1/(2\lambda_2))
$$
For the unbounded variable, you can explicitly solve for the Lagrange multipliers $\lambda_1$ and $\lambda_2$ in terms of the constraint values ($a_1, a_2$ in the Wikipedia article). With $a_1=\mu, a_2=\mu^2 + \sigma^2$, you then get $\lambda_1=\mu/\sigma^2, \lambda_2=-0.5 \sigma^2$, so the standard Gaussian $\mathcal{N}(x|\mu, \sigma^2)$.
For the bounded variable $x>x_{min}$, I (and mathematica) cannot solve for $\lambda_{1,2}$ explicitly anymore because of the error function term that appears when computing the partition function ($1/c$ in wikipedia). This means that that the $\mu$ and $\sigma^2$ parameters of the truncated Gaussian are not the mean and variance of the continuous variable you started with. It can even happen that for $x_{min}=0$, the mode of the Gaussian is negative! Of course the numbers all agree again when you take  $x_{min} \to -\infty$.
If you have concrete values for $a_1, a_2$, you can still solve for $\lambda_{1,2}$ numerically and plug in the solutions into the general equation and you are done! The values of $\lambda_{1,2}$ from the unbounded case may be a good starting point for the numerical solver.
This question is a duplicate of https://math.stackexchange.com/questions/598608/what-is-the-maximum-entropy-distribution-for-a-continuous-random-variable-on-0

A: One may simply use the theorem of Boltzmann's that is in the very Wikipedia article you point to.
Note that specifying the mean and variance is equivalent to specifying the first two raw moments - each determines the other (it's not actually necessary to invoke this, since we may apply the theorem directly to the mean and variance, it's just a little simpler this way).
The theorem then establishes that the density must be of the form:
$$f(x)=c \exp\left(\lambda_1 x + \lambda_2 x^2 \right)\quad \mbox{ for all } x \geq 0$$
Integrability over the positive real line will restrict $\lambda_2$ to be $\leq 0$, and I think places some restrictions on the relationships between the $\lambda$s (which will presumably be satisfied automatically when starting from the specified mean and variance rather than the raw moments).
To my surprise (since I wouldn't have expected it when I started this answer), this appears to leave us with a truncated normal distribution.
As it happens, I don't think I've used this theorem before, so criticisms or helpful suggestions on anything I haven't considered or have left out would be welcome.