text:
Q: Insert from array<> java into table sql where not exists i want insert data from array this array it's contains variable of class java getters and setters
So i can insert that but when i execute another timen it will be added for second time so i have repitition
for that i want do insert if where not exist to not have repitito of same data
this the code but its the same tha sam data are inserted for next time
for(Service srv:service){
    srvDataLst.add(srv.getvlan());

PreparedStatement pst=conn.prepareStatement(
        "INSERT INTO tout (VLAN,client,JR,vrf,address) "
    + "SELECT DISTINCT '"+srv.getvlan()+"', ?, ?, ?, ? "
    + "   FROM dual "
    + "   WHERE NOT EXISTS (SELECT * FROM tout WHERE 'VLAN'='"+srv.getvlan()+"')"
    + " ");
        pst.setString(1,convertNullToEmptyString(srv.getdesc()));
    pst.setString(2,convertNullToEmptyString(srv.getjr()));
    pst.setString(3,convertNullToEmptyString(srv.getvrf()));
    pst.setString(4,convertNullToEmptyString(srv.getaddress()));
    pst.executeUpdate();

Thank you


text:
Q: How to exclude specific file types from the following .htaccess rewrite rule? How can you exclude specific files types (xml and txt) from the following rewrite rule?
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://website.com/$1/ [QSA,L,R=301]

A: What about :
RewriteCond %{REQUEST_URI} !\.(xml|txt)$

redpajama_set_name: RedPajamaStackExchange


text:
Q: DateTime has wrong value after submit I have a dropdown list with dates, the values are as such:
<select name="DayDate" id="DayDate" data-val-date="The field DayDate must be a date." data-val="true" style="display: inline-block;" class="input-validation-error">
    <option value="07/11/2013">donderdag 11 juli 2013</option>
    <option value="07/10/2013">woensdag 10 juli 2013</option>
    <option value="07/09/2013">dinsdag 9 juli 2013</option>
</select>

@Html.DropDownListFor(m => m.DayDate, Model.Days.Select(r => new SelectListItem
{
    Text = r.Date.Value.ToString("D"),
    Value = r.Date.Value.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)
}))

But when I submit I get as a date 7th of November, 7th of October or 7th of September!
The Thread culture is set to NL-nl and this has to remain this way.
So I thought of removing CultureInfo.InvariantCulture but then the model won't accept the date input data-val will be false, with this error: The field DayDate must be a date.
The following is set in the web.config
<globalization culture="nl-NL" uiCulture="nl-NL" />
How can I get the correct dates passed on?

A: Solved it by adding this piece of Javascript:
$.validator.methods.date = function (value, element) {
    return true;
};


text:
Q: Why is intrinsic carrier density only equal to hole - or electron concentration? If carriers can be holes or free electrons, why isn´t the intrinsic carrier concentration equal to the sum of the free electron concentration and the hole concentration in the semiconductor?

A: I dont get what you mean .In semiconductors the conductivity of the semiconductor $$\sigma$$ is equal to:
$$\sigma  = en_{e}\mu _{De}+en_{h}\mu _{Dh}$$
we take into account both the drift of electrons and holes


text:
Q: How to run Asp.Net Core Application packaged as a Linux docker container with code coverage? Our App runs in a linux docker container deployed to an Azure App Service.
We have a QA pod for which we would like to collect the code coverage data. To the best of my understanding it means:

*

*Running kestrel from within a coverage tool. We use built-in .NET coverage collector when we run our unit tests during the CI builds. It is unclear how to leverage it here, if at all possible. We could probably use OpenCover for this, but the details are unclear.

*The coverage report needs to be persisted somewhere for us to pick up and publish on our on-prem SonarQube server. It is unclear how to cause this report to be generated without stopping the app service.

We do all this in order to augment the coverage figures from unit tests with those from automated E2E tests.


text:
Q: How to beat the Twinscythe? I need to complete the exploration quest Windy Heights West - Exploration but the boss of this area is a Twinscythe which, when I face it, kills two of my team each turn, using it's Drainsickle attack. So after three turns, it's Game Over.
What techniques or materias can I used to win this battle and clear this exploration quest?

A: There are a couple things you can do to give yourself a better chance at passing this quest.
First, it might help if you had a tank character in your party, especially if they have draw attacks (or even better, provoke, which can be learned by Golem). Add in a couple of extra buffs to lower his attack (full break or power break) and buff your defenses (cheer) for extra survivability. With any luck, your tank can sustain a few hits.
Next, it'd probably be beneficial to have a character that can inflict some status effects. Twinscythe is susceptible to a couple of status effects that are pretty common and can greatly lower or eliminate incoming damage (blind and paralysis, respectively). If these status effects are applied strategically (apply one right as the other is about to end), you may not even need a tank, as you might be able to simply avoid all damage. The application and timing of good status effects is a bit random, so relying on this may take a few tries until it lands just right.
Finally, figure out your best course of action for dealing damage with the characters you have available. As he is weak to fire, bringing in a couple mages may be helpful. Getting elemental links on firagas can bring his health down pretty quick. Also, he is susceptible to poison, which is great because it does a percentage of damage (10% of max health) per turn. Bio Blaster is a relatively easy ability to create, and currently boasts the highest success rate of poison being applied (50%) in the game.


text:
Q: C++ kafka consumer - Segmentation fault (core dumped) I wrote C++ consumer for kafka messages using cppkafka library (wrapper for librdkafka). I have problem while running program. Sometimes there is problem with Segmentation fault (core dumped) before topic assigned, but sometimes it runs without any errors. Below You can find my main() code.
bool running = true;

int main() {
string topic = "topic";
string stop = "STOP";
int m_count = 0;

signal(SIGINT, [](int) { running = false; });

Configuration config = {
        { "metadata.broker.list", "kafka-1:19092"},
        {"group.id", topic},
        {"fetch.wait.max.ms", 10},
        {"enable.auto.commit", false},
        {"auto.offset.reset", "latest"}
};

Consumer consumer(config);

consumer.set_assignment_callback([](const TopicPartitionList& partitions) {
    cout << "Got assigned: " << partitions << endl;
});

consumer.set_revocation_callback([](const TopicPartitionList& partitions) {
    cout << "Got revoked: " << partitions << endl;
});

consumer.subscribe({ topic });

cout << "Consuming messages from topic " << topic << endl;

auto ms = std::chrono::microseconds(10);

while (running) {

    Message msg = consumer.poll();
    if (msg) {
        if (msg.get_error()) {
            if (!msg.is_eof()) {
                cout << "[+] Received error notification: " << msg.get_error() << endl;
            }
        }
        else {
            m_count ++;
            cout << msg.get_payload()<<" OFSET: "<< msg.get_offset() <<" TIME: "<<getMs() - msg.get_timestamp().get().get_timestamp().count()<< endl;
            consumer.commit(msg);
        }
    }

}

}


text:
Q: RaspberryPi - psutil 2.1.1 install error I installed psutil on my RPi from sudo apt-get install python-psutil but it gave me v0.5.1
I want to use v2.1.1 since it has the virtual_memory() command where v0.5.1 does not.
While attempting to upgrade psutil from PIP, sudo pip install --upgrade psutil it starts installing then quits with this error:
pi@raspbmc:~$ sudo pip install --upgrade psutil
Downloading/unpacking psutil from https://pypi.python.org/packages/source/p/psutil/psutil-2.1.1.tar.gz#md5=72a6b15d589fab11f6ca245b775bc3c6
  Downloading psutil-2.1.1.tar.gz (216kB): 216kB downloaded
  Running setup.py (path:/tmp/pip_build_root/psutil/setup.py) egg_info for package psutil

    warning: no previously-included files matching '*' found under directory 'docs/_build'
Installing collected packages: psutil
  Found existing installation: psutil 0.5.1
    Can't uninstall 'psutil'. No files were found to uninstall.
  Running setup.py install for psutil
    building '_psutil_linux' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c psutil/_psutil_linux.c -o build/temp.linux-armv6l-2.7/psutil/_psutil_linux.o
    In file included from /usr/include/linux/kernel.h:4:0,
                     from /usr/include/arm-linux-gnueabihf/sys/sysinfo.h:25,
                     from psutil/_psutil_linux.c:21:
    /usr/include/linux/sysinfo.h:8:2: error: unknown type name '__kernel_long_t'
    /usr/include/linux/sysinfo.h:9:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:10:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:11:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:12:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:13:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:14:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:15:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:18:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:19:2: error: unknown type name '__kernel_ulong_t'
    /usr/include/linux/sysinfo.h:21:22: error: '__kernel_ulong_t' undeclared here (not in a function)
    psutil/_psutil_linux.c: In function 'init_psutil_linux':
    psutil/_psutil_linux.c:475:5: warning: overflow in implicit constant conversion [-Woverflow]
    error: command 'gcc' failed with exit status 1

I tried uninstalling python-psutil using sudo apt-get remove --purge python-psutil then doing sudo pip install psutil but comes back with the same error. Same story with sudo easy_install psutil
Next I tried to make sure I had python-dev and libevent-dev installed. python-dev was already installed and updated but libevent-dev was not. so I updated it and tried sudo pip install psutil again to no avail (same error).
Am I missing something?


text:
Q: Set fixed height to a bootstrap solution Got a huge project going on, we're 70% into it, using tweeter bootstrap 3. Problem is, we got a lot of content that extends downward way beyond 1200px causing a vertical scroll bar to show. Client came back and asks for fixed height (800px or 1200px). Is there  a way to set a general height from which bootstrap can inherit without us going to each single screen and re-design for this new screen setting ? (we might be looking at 3 or 4 months of re-do). (Thanks in advance!!)

A: Probably depends if you have a single 'template' type page that all pages inherit from, or if they all use a top level div with same class, for example with the .container class.  If so, you could set a max-height and overflow:hidden; on that element/class, but that may also introduce some side effects.  For example:
.rootLevelClassName {
   max-height: 800px;
   overflow: hidden;
}

I didn't verify that myself, but it should get you close.

A: If all the files share the same bootstrap css, you can download the bootstrap file from here, then set the height of the body element to 1200px or whatever the client desires and link the custom bootstrap file to your files. From there you can refactor your code to use percentages to make everything fit within the body which is fixed at 1200px.


text:
Q: how to change CONSTRAINT in this table for my project Hi i make a table from this tutorial MySQL Foreign Key On Delete and this work good for my project
user table :
CREATE TABLE `User` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

UserStaff Table :
CREATE TABLE `UserStaff` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`UserId` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`Id`),
KEY `UserId` (`UserId`),
CONSTRAINT `UserStaff_ibfk_1`
FOREIGN KEY (`UserId`)
REFERENCES `User` (`Id`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

my question is : whate is UserStaff_ibfk_1 ?
can i change it to example_name or not
thanks


text:
Q: How to stop a thread when application is closed I am spawning a thread in the Form_load method and would like to close this thread when the application is closed.
private void Form1_Load(object sender, EventArgs e)
        {

          new Thread(() =>
            {
            try
            {
                // Set the TcpListener on port 6101.
                Int32 port = 6101;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (isServerRun)
                {
               //     Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also use server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
             //       Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                        ReceiveCommand(data);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);

                    }

                    // Shutdown and end connection
                    client.Close();
                }

                MessageBox.Show("STOPPING");
                server.Stop();

            }
            catch (SocketException ett)
            {

            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }

        }).Start();
    }

        }

For that i am setting a  variable to false and the loop in the spawned function should exit.
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            isServerRun = false;  // with isServerRun as false the while
        }

loop should quit in the spawned thread function.
But still the Spawned thread does not quit

A: static bool isCancellation = false;
static object gateway = new object();

lock (gateway)
{
    isCancellation = true;
}

for (int i = 0; i < 1000; i++)
{
    Thread.SpinWait(5000000);

    lock (gateway)
    {
        if (isCancellation)
        {
            break;
        }
    }
}


text:
Q: Adding a scrollbar to a canvas with figures tkinter I am trying to add a scrollbar to a canvas to view a collection of figures that otherwise would not fit into the screen, or the allocated space in said canvas.
I have found information on how to do this with labels and buttons, and I was able to reproduce the operation. However, with figures this does not seem to work.
Below I paste the code of the example I am working on. It plots a large figure with 2 stacked subplots. The scrollbar is not active.
Can anybody help me please
import tkinter as tk
from tkinter import ttk
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

class Example(tk.Tk):

    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)

        tk.Button(self,bg='red',text="one").grid(row=0,column=0,sticky='we', padx=5, pady=10)

        tk.Button(self,bg='blue',text="two").grid(row=1,column=0,ipadx=200,sticky='we', padx=5, pady=5)

        tk.Label(self,bg='green',text="label").grid(row=2,column=0,sticky='we',padx=5, pady=5)

        first_frame= tk.Frame(self, pady=5, padx=5)
        first_frame.grid(row=3,column=0)

        canvas=tk.Canvas(first_frame,bg="orange",height=300,width=480)
        canvas.pack(side="bottom", fill="both", expand=True)

        scrollbar = ttk.Scrollbar(canvas, orient="vertical", command=canvas.yview)
        scrollbar.pack(side="right", fill="y")

        canvas.configure(yscrollcommand=scrollbar.set)

        scrollbar.bind("<Configure>",lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

        second_frame=tk.Canvas(canvas)

        canvas.create_window((0, 0), window=second_frame, anchor="ne")

        # Random data
        np.random.seed(3)
        x = 0.5 + np.arange(8)
        y = np.random.uniform(2, 7, len(x))

        # Plot 2 stacked figures
        fig, ax1= plt.subplots(2,figsize=(5,50))

        ax1[0].step(x, y, linewidth=2.5)

        ax1[0].set(xlim=(0, 8), xticks=np.arange(1, 8),
                ylim=(0, 8), yticks=np.arange(1, 8))

        ax1[1].step(x, y, linewidth=2.5)

        ax1[1].set(xlim=(0, 8), xticks=np.arange(1, 8),
                ylim=(0, 8), yticks=np.arange(1, 8))

        # Draw into canvas
        canvas_fig = FigureCanvasTkAgg(fig,canvas)
        canvas_fig.get_tk_widget().pack(side="bottom", fill="y")
        scrollbar.config(command=canvas_fig.get_tk_widget().yview)

app=Example()
app.geometry("480x320")
app.title("Scrollfigure")

app.mainloop()

A: There are issues in your code:

*

*scrollbar should be a child of first_frame instead of canvas

*canvas need to be packed on side left instead of bottom

*<Configure> event should be bound on second_frame instead of scrollbar

*anchor="nw" instead of anchor="ne" in canvas.create_window(...)

*canvas_fig should be child of second_frame instead of canvas

*scrollbar.config(command=canvas_fig.get_tk_widget().yview) should not be executed

Below is the updated code:
import tkinter as tk
from tkinter import ttk
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

class Example(tk.Tk):

    def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)

        tk.Button(self,bg='red',text="one").grid(row=0,column=0,sticky='we', padx=5, pady=10)
        tk.Button(self,bg='blue',text="two").grid(row=1,column=0,ipadx=200,sticky='we', padx=5, pady=5)
        tk.Label(self,bg='green',text="label").grid(row=2,column=0,sticky='we',padx=5, pady=5)

        first_frame= tk.Frame(self, pady=5, padx=5)
        first_frame.grid(row=3,column=0)

        canvas=tk.Canvas(first_frame,bg="orange",height=300,width=480)
        canvas.pack(side="left", fill="both", expand=True) ### side="left" instead of "bottom"

        scrollbar = ttk.Scrollbar(first_frame, orient="vertical", command=canvas.yview) # child of first_frame instead of canvas
        scrollbar.pack(side="right", fill="y")

        canvas.configure(yscrollcommand=scrollbar.set)
        #scrollbar.bind("<Configure>",lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

        second_frame=tk.Canvas(canvas)
        # bind on second_frame instead of scrollbar
        second_frame.bind("<Configure>",lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

        canvas.create_window((0, 0), window=second_frame, anchor="nw") ### anchor="nw" instead of "ne"

        # Random data
        np.random.seed(3)
        x = 0.5 + np.arange(8)
        y = np.random.uniform(2, 7, len(x))

        # Plot 2 stacked figures
        fig, ax1= plt.subplots(2,figsize=(5,50))

        ax1[0].step(x, y, linewidth=2.5)
        ax1[0].set(xlim=(0, 8), xticks=np.arange(1, 8),
                ylim=(0, 8), yticks=np.arange(1, 8))

        ax1[1].step(x, y, linewidth=2.5)
        ax1[1].set(xlim=(0, 8), xticks=np.arange(1, 8),
                ylim=(0, 8), yticks=np.arange(1, 8))

        # Draw into canvas
        canvas_fig = FigureCanvasTkAgg(fig, second_frame) # used second_frame instead of canvas
        canvas_fig.get_tk_widget().pack(side="bottom", fill="y")
        #scrollbar.config(command=canvas_fig.get_tk_widget().yview)

app=Example()
#app.geometry("480x320")
app.title("Scrollfigure")

app.mainloop()


text:
Q: Uploading to Teams with C# and Powershell I'm writing a form that will upload any file in a folder to a Microsoft Teams share. My code already manage to upload the files, but keep showing me the log in form of microsoft 365 for each file, instead asking only the first time.
this is the code:
private void Upload()
    {
        Runspace runspace = RunspaceFactory.CreateRunspace();
        runspace.Open();

        PowerShell psinstance = PowerShell.Create();

//fill some vars and connect (once, hopefully)

            psinstance.AddScript("$SharepointURL = '" + LINK-TO-THE-DESIRED-TEAM + "'");
            psinstance.AddScript("$OutPath = '" + SOURCE-DIRECTORY + "'");
            psinstance.AddScript("Connect-PnPOnline -SPOManagementShell -url $SharepointURL -cleartokencache");

//upload each file in the directory
            psinstance.AddScript("$Files = Get-ChildItem -path $OutPath");
            psinstance.AddScript("foreach ($File in $Files){ Add-PnPFile -Folder '" + DESIRED-CHANNEL-DIRECTORY + "' -Path $File.FullName }");

//execute the script
            Collection <PSObject> results = psinstance.Invoke();

//get possible errors
            Collection<ErrorRecord> Errors = psinstance.Streams.Error.ReadAll();

            runspace.Close();
            }

The same powershell code, if executed in the powershell console, works like a sharm. This is driving me crazy, can you help me?


text:
Q: IIS 10 can't load pictures with port 80, but can load with port 8080 Thanks:
If use port 80:

Error message:

If use port 8080, everything works:

Update ————————————————————

Update ————————————————————
If I visit iisstart.png:

Use Telerik Fiddler:


text:
Q: How can i run test with selenium web driver on linux, using geckodriver? I have an project, that works correctly with a chrome webdriver on Windows OS, and Linux OS. I added support geckodriver on windows and it's works fine. But i can't add support geckodriver on linux for my java-selenium autotests purpose.
My setup is:
OS: Fedora Linux 36 (Workstation Edition) x86_64
Firefox Browser 106.0.1 (64 bits) in the /usr/bin/firefox directory. I know it because of this command:
[bans@bans-note ~]$ which firefox
/usr/bin/firefox

And it is really there:
[bans@bans-note ~]$ ls /usr/bin |grep firefox
firefox

And browser is executable. After this command browser has been started
[bans@bans-note bin]$ ./firefox

This is the place in the code where i prepare driver for my tests:
case "linux_firefox":{
    System.setProperty("webdriver.gecko.driver", PATH_LINUX_FIREFOX_DRIVER);
    System.setProperty("webdriver.firefox.bin", PATH_LINUX_FIREFOX);
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    firefoxOptions.addArguments("--headless");
    firefoxOptions.addArguments("--no-sandbox");
    driver = new FirefoxDriver();

    break;
}

PATH_LINUX_FIREFOX_DRIVER - constant where i has stored the path to geckodriver. Gecodriver is there.
PATH_LINUX_FIREFOX - constant where i has stored the path to firfox. Firefox binary is there.
When I run the test with the setup on linux and firefox(gecko), I get an error
java.lang.IllegalStateException: Specified firefox binary location does not exist or is not a real file: /usr/bin/firefox

    at com.google.common.base.Preconditions.checkState(Preconditions.java:504)
    at org.openqa.selenium.firefox.Executable.<init>(Executable.java:43)
    at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:123)
    at common.CommonActions.createDriver(CommonActions.java:65)
    at tests.base.BaseTest.<init>(BaseTest.java:15)
    at tests.TestLogin.positive.LoginTest.<init>(LoginTest.java:12)
    at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
    at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
    at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

Process finished with exit code 255

Please help me run my tests with geckodriver!

*

*
case "linux_firefox":{

                FirefoxOptions options = new FirefoxOptions();
                options.setBinary(new FirefoxBinary(new  File(PATH_LINUX_FIREFOX)));
                DesiredCapabilities capabilities = DesiredCapabilities.firefox();
                capabilities.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options);
                capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
                System.setProperty("webdriver.gecko.driver", PATH_LINUX_FIREFOX_DRIVER);
                driver = new FirefoxDriver(capabilities);

                break;
}

*I was reinstalling the browser.

*I installed firefox snap version.


text:
Q: Sorting a ListView by tag in C# I have a list view with some columns listViewItems. When I use the Sort method listViewItems.Sort(); it sorts by column text by default. This is the code I use:
private void OnColumnClick(object sender, ColumnClickEventArgs e)
        {
            int sortColumn = 0; --I only want to sort if you click this column header, not others
            if (e.Column == sortColumn)
            {
                if (listViewItems.Sorting == SortOrder.Ascending)
                {
                    listViewItems.Sorting = SortOrder.Descending;
                }
                else
                {
                    listViewItems.Sorting = SortOrder.Ascending;
                }
            }
            listViewItems.Sort();

However, my items have a Tag, accessible by listViewItems[0].Tag;
I would like to use that tag to sort the list (in my case tag is an int), but I don't know how to do it nor find information about something similar. Sort method doesn't accept any parameters. I tried to create a column sorter, but it also expects a column.
ListViewColumnSorter lvwColumnSorter;
lvwColumnSorter = new ListViewColumnSorter();
listViewItems.ListViewItemSorter = lvwColumnSorter;
lvwColumnSorter.SortColumn = ?;

Any ideas?
Thanks in advance.

A: var items = ListView.Items.Cast<ListViewItem>().OrderBy(x => x.Tag).ToList();
ListView.Items.Clear();
ListView.Items.AddRange(items.ToArray());


text:
Q: React load image from folder cause auto reload app This is the my project folder structure

*

*backend

*

*index.ts

*frontend(react)

*

*assets

*

*logo.png

*index.jsx

*index.html

*node_modules

*uploads

*

*myimage1.png

*myimage2.png

*myimage3.png

*myimage4.png

*myimage5.png

*default-image.png
index.jsx
data = [
 {msg:'firstimage',name:'myimage1'},
 {msg:'secondimage',name:'myimage2'},
 {msg:'thirdimage',name:'myimage3'},
 {msg:'fourthimage',name:'myimage4'},
 {msg:'fifthimage',name:'myimage5'},
]

 data.map((item) => (
 let img_path = '';
  try{
               img_path = require(`../uploads/${item.name}.png`)
  }
  catch(err){
               img_path = require(`../default-image.png`)

  }

 )

Above code work fine but whenever new image is uploaded to uploads folder it cause the react app to restart and break the app.

A: Move uploads folder to inside assets folder


text:
Q: How to use sun.awt.geom.Curve? I'v got a library, which uses sun.awt.geom.Curve class. I found no such class in standard JRE. How to use it? May be it is possible to replace this class with some public one?

A: Classes in sun.* packages are part of the implementation of the runtime and should not be used directly because they may change from one release to the next without a warning. You can see the documentation and source code of sun.awt.geom.Curve from OpenJDK for example here: http://www.docjar.com/docs/api/sun/awt/geom/Curve.html
Whether it's possible to replace it with something else depends on what the code does with it.


text:
Q: 'setRestAPIKey' method not available in LicenceManager class LicenceManager.getInstance().setRestAPIKey("your_rest_api_key");
LicenceManager.getInstance().setMapSDKKey("your_java_script_key");

I have compiled the latest maps sdk 2.3.0. Here .setRestAPIKey() and .setMapSDKKey() methods are not working. Inside the LicenseManager.class I found .setMapmyIndiaBeaconToken() method.

A: Instead of using LicenceManager use `MapmyIndiaAccountManager' class.
The full implementation is
MapmyIndiaAccountManager.getInstance().setMapSDKKey("your_java_script_key");
MapmyIndiaAccountManager.getInstance().setRestAPIKey("your_rest_api_key");


text:
Q: Solve equation $5x^2+3x - 4 = 0$ in $\mathbb{Z}/17\mathbb{Z}$ I tried to derive full square but haven't managed to get anything useful from it. The question is: what is (more or less) general method for solving such equations?

A: In this field, the discriminant is a square:
$$\Delta=9-4\cdot 5\cdot -4=89\equiv 4\mod 17,$$
hence the roots are
$$x_0,x_1=(-3\pm 2)\cdot 10^{-1}=\begin{cases}-5\cdot -5\equiv 8\\
-1\cdot-5=5\end{cases}$$
Completing the square:
First multiply the equation by $5^{-1}=7$.  You obtain:
$$x^2+4x+6=(x+2)^2+2=(x+2)^2-7^2,$$
whence $x=-2\pm 7$.


text:
Q: Shellsort, 2.48^(k-1) vs Tokuda's sequence Introduction
Shellsort is an interesting sort algorithm that I came across a while ago. The most amazing part is that a different gap sequences can significantly improve the speed of the algorithm. I did a few reading (not extensively) and it seem that Tokuda's sequence is recommendeded for practical applications.
Another interesting part is that the sequence of ratio 2.20~2.25 tends to be more efficient. So I did a small search thought the sequence of ratio from 2.20 to 2.50 and tried to search for which ratio that can performance averagely good. I come across this ratio: 2.48 that seem to averagely performance good in many different trials.
Then, I came up with sequence generator: 2.48k-1 (lets call it 248 sequence) and tried to compare it with Tokuda's sequence. It turned out that they averagely equal in speed. 248 sequences tends to use slightly more number of comparison.
Benchmark Methods

*

*Instead of using millisecond as a measurement, I use the number of comparision and number of swap.

*I did 100 trials each on the following array size (50,000; 100,000; 200,000; 300,000; 500,000; 1,000,000) and keep track of their number of comparison and number of swap.

*The following is my data (here in CSV format).

*Full Code: http://pastebin.com/pm7Akpqh
Questions
I know I might be wrong that is why I come here to seek for more opinion from more experienced programmers here. In case you don't get the question, here is my question in short:

*

*Does 2.48k-1 is as good as Tokuda's sequence?

*If it is as good as Tokuda's sequence, would it be more practical to use it since 2.48k-1 sequence is easier to generate than Tokuda's sequence.

248 Sequence:
  ROUNDUP ( 2.48(k-1) )
  eg: 1, 3, 7, 16, 38, 94, 233, 577, 1431, 3549, 8801, 21826, ...

Tokuda's Sequence
  ROUNDUP ( (9k - 4k) / (5 * 4k - 1) )
  eg: 1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, ...

As @woolstar suggested me to also test with edge cases such as reversed and sorted. As expectedly, 248 sequence is faster in edge cases because 248 sequence gap is larger so it moves the inverse faster.

Shellsort Implementation
public static int compare = 0;
public static int swap = 0;

public static bool greaterthan(int a, int b) {
    compare++;
    return a > b;
}

public static int shellsort(int[] a, int[] gaps) {
    // For keeping track of number of swap and comparison
    compare = 0;
    swap = 0;

    int temp, gap, i, j;

    // Finding a gap that is smaller than the length of the array
    int gap_index = gaps.Length - 1;
    while (gaps[gap_index] > a.Length) gap_index--;

    while (gap_index >= 0) {

        // h-sorting
        gap = gaps[gap_index];
        for (i = gap; i < a.Length; i++) {
            temp = a[i];
            for(j = i; (j >= gap) && (greaterthan(a[j - gap], temp)); j -= gap) {
                a[j] = a[j - gap];
            }

            // swapping
            a[j] = temp;
            swap++;
        }

        gap_index--;
    }

    return compare;
}

A: According to this reserach: (Ciura, Marcin (2001) "Best Increments for the Average Case of Shellsort". In Freiwalds, Rusins. Proceedings of the 13th International Symposium on Fundamentals of Computation Theory. London: Springer-Verlag. pp. 106–117) the dominant operation in shell sort for arrays with size with less than 108 elements should be the comparison operation, not swap:

Knuth's discussion assumes that the running time can be approximated as 9×number of moves,
  while Figures 3 and 4 show that for each sequence the number of key comparisons is a better measure of the running time than the number of moves. The asymptotic ratio of 9 cycles per move is not too precise for N ≤ 108, and, if some hypothetical sequence makes Θ(NlogN) moves, it is never attained. Analogous plots for other computer architectures would lead to the same conclusion.
Treating moves as the dominant operation leads to mistaken conclusions
  about the optimal sequences.

In this context the answer to your question is no: the 248 sequence is worse, because it uses more comparisons. You could consider also comparing your sequence with the Ciura's sequence presented in this article, as this research seems to prove that it's better than Tokuda's sequence.


text:
Q: User input to an array in Visualforce I have a Visualforce page that collects user input for 125 integer variables that are then used by the controller to create records.  I'd rather use an array instead of defining all those variables, but I can't seem to set a variable using
<apex:inputText value="{!inputValue[0][0]}" id="firstInputText"/>

I looked into apex:selectoptions but that doesn't look like I can use it since I need integer values from 0 to 20,000 rather than picklist-like values.
Any suggestions?

A: I'm not sure how you want it to display, but how about using an <apex:repeat> with a map?
Your class could look like this.
public Map<String,Integer> vals {
    get {
        if (vals == null) {
            vals = new Map<String, Integer> {
                'Value 1' => 0,
                'Value 2' => 0,
                'Value 3' => 0};
        }
        return vals;
    }
    set;
}

Then the page would be
<apex:repeat value="{!vals}" var="valKey">
        <apex:outputText value="{!valKey}" /> --
        <apex:inputText value="{!vals[valKey]}" /><br/>
</apex:repeat>


text:
Q: Correct tags in PUBXML not recognized by intellisense I've noticed that in my PUBXML file, the first element is underlined by a blue wave. When I removed it and tried to enter it, I noticed that intellisense didn't recognize it. I've checked with MSDN about PUBXML files and it seems to be correct.
I also noticed that when I removed the first tag in the <PropertyGroup>, the second (now becoming the topmost) immediately got underlined by the same blue wave. So my conclusion is that it's not the inner, underlined tags that's something is wrong with.
What could be the error? How to trouble-shoot it?
Below are the contents of the the file. Please note that it's the untampetered with version provided automatically by MS/VS and Azure publishing file download.
<?xml version="1.0" encoding="utf-8"?>
<!-- This file is used by the publish/package process of your Web project.
  You can customize the behavior of this process by editing this MSBuild
  file. In order to learn more about this please visit
  http://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project
  ToolsVersion="4.0"
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>MSDeploy</WebPublishMethod>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish>...</SiteUrlToLaunchAfterPublish>
    <LaunchSiteAfterPublish>False</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <MSDeployServiceURL>...</MSDeployServiceURL>
    <DeployIisAppPath>VisitMore</DeployIisAppPath>
    <RemoteSitePhysicalPath />
    <SkipExtraFilesOnServer>False</SkipExtraFilesOnServer>
    <MSDeployPublishMethod>WMSVC</MSDeployPublishMethod>
    <EnableMSDeployBackup>True</EnableMSDeployBackup>
    <UserName>Chamster</UserName>
    <_SavePWD>True</_SavePWD>
    <PrecompileBeforePublish>True</PrecompileBeforePublish>
    <EnableUpdateable>False</EnableUpdateable>
    <DebugSymbols>False</DebugSymbols>
    <WDPMergeOption>DonotMerge</WDPMergeOption>
  </PropertyGroup>
</Project>

A: The XML editor will put a blue squiggle under anything not defined in the xmlns you've specified.  However, this happens all the time - the MSBuild schema that VS ships with has relatively few properties considering that MSBuild lets you define arbitrary property names.  In fact, you'll find these squiggles even if you open a project file in most cases.
Just ignore the blue squiggles.


text:
Q: How to list pipes used by a process with a bash command Is there a  way to list pipes used by a running linux process (e.g. given its pid or process name) and to determine their used capacity?
Something like:
lspipes -l -p pid

resulting in something like:
[rw]  descriptor  size  name

where rw is the pipe end type and size is its used capacity
Or something similar

A: I don't really think there's such a command. You can try the following:
lsof -p <PID> | grep "FIFO"

Where <PID> stand for the process id. Probably there's a lsof switch to select only pipes and avoiding the grep, but I cannot find it in the man page right now.
It should give you something close to what you're looking for.

A: 1) ls -l /proc/pid/fd
This will list the pipes
lr-x------ 1 prabagaran prabagaran 64 Sep  5 23:01 14 -> pipe:[57729]
l-wx------ 1 prabagaran prabagaran 64 Sep  5 23:01 15 -> pipe:[57728]
lr-x------ 1 prabagaran prabagaran 64 Sep  5 23:01 16 -> pipe:[57731]
lr-x------ 1 prabagaran prabagaran 64 Sep  5 23:01 17 -> pipe:[57730]

2) lsof | grep 57731
wineserve 3641 prabagaran   76w     FIFO        0,8       0t0   57731 pipe
winedevic 3651 prabagaran   16r     FIFO        0,8       0t0   57731 pipe

These are the pipe information related to the given process id.


text:
Q: Rails: How to do COUNTA of Excel for selected columns? I have a Users table that I want to analyze by counting the number of cells that have data like COUNTA function of Excel, which counts the cells that have data:
        JOB           | ADDRESS | LOOKS | WEALTH
Matthew Tax Collector |         | 3     | 9
Mark                  | Galilee | 6     |

socio_count counts the cells that have data in address and job. personality_count counts the cells that have content in looks, wealth. Is there an easier way to do this in Rails? (because there are much more columns).
In Excel it would be
COUNTA(B2:C2) # outputs 1
COUNTA(D2:E2) # outputs 2

My Rails code is:
socio_count = 0
if @user.job.present?
  socio_count = socio_count + 1
end

if @user.address.present?
  socio_count = socio_count + 1
end

# more columns here..

@socio_count = socio_count # outputs 1

personality_count = 0
if @user.looks.present?
  personality_count = personality_count + 1
end

if @user.wealth.present?
  personality_count = personality_count + 1
end

# more columns here..

@personality_count = personality_count # outputs 2

A: Use .send.
%i(job address phone).each do |symbol|
  @user.send(symbol).present? and socio_count += 1
end

That's a bit more DRY. There are also ways to access an ActiveRecord column by name. And you should edit your post to explain Excel's COUNTA, for those who don't know it...


text:
Q: Show that $v + iu$ is the reflection of the point $u + iv$ across the line $u = v$ Show that $v + iu$ is the reflection of the point $u + iv$ across the line $u = v$
My attempt :I know that the reflection of the point $(x,y)$ across
the line $y = x $ is the point $(y, x)$
i,e  line of equation will be  $x-y=0$
But here im confused that how to show $v + iu$ is the reflection of the point $u + iv$

A: You pretty much have it. If you know that the reflection of $(x,y)$ across $x=y$ is $(y,x)$, then just note that we identify $a+bi$ with $(a,b)$ when we identify $\Bbb{C}\cong \Bbb{R}^2$. In particular, the reflection across $x=y$ sends $a+bi$ to $b+ai$.


text:
Q: What makes a system little-endian or big-endian? I'm confused with the byte order of a system/cpu/program.
So I must ask some questions to make my mind clear.
Question 1
If I only use type char in my C++ program:
void main()
{
    char c = 'A';
    char* s = "XYZ";
}

Then compile this program to a executable binary file called a.out.
Can a.out both run on little-endian and big-endian systems?
Question 2
If my Windows XP system is little-endian, can I install a big-endian Linux system in VMWare/VirtualBox?
What makes a system little-endian or big-endian?
Question 3
If I want to write a byte-order-independent C++ program, what do I need to take into account?

A: Question 1:

Can a.out both run on little-endian and big-endian system?

No. Because a.out is already compiled for whatever architecture it is targeting. It will not run on another architecture that it is incompatible with.
However, the source code for that simple program has nothing that could possibly break on different endian machines.
So yes it (the source) will work properly. (well... aside from void main(), which you should be using int main() instead)
Question 2:

If my WindowsXP system is little-endian, can I install a big-endian
  Linux system in VMWare/VirtualBox?

Endian-ness is determined by the hardware, not the OS. So whatever (native) VM you install on it, will be the same endian as the host. (since x86 is all little-endian)

What makes a system little-endian or big-endian?

Here's an example of something that will behave differently on little vs. big-endian:
uint64_t a = 0x0123456789abcdefull;
uint32_t b = *(uint32_t*)&a;
printf("b is %x",b)

*Note that this violates strict-aliasing, and is only for demonstration purposes.
Little Endian : b is 89abcdef
Big Endian    : b is 1234567

On little-endian, the lower bits of a are stored at the lowest address. So when you access a as a 32-bit integer, you will read the lower 32 bits of it. On big-endian, you will read the upper 32 bits.
Question 3:

If I want to write a byte-order independent C++ program, what do I
  need to take into account?

Just follow the standard C++ rules and don't do anything ugly like the example I've shown above. Avoid undefined behavior, avoid type-punning...

A: Little-endian / big-endian is a property of hardware. In general, binary code compiled for one hardware cannot run on another hardware, except in a virtualization environments that interpret machine code, and emulate the target hardware for it. There are bi-endian CPUs (e.g. ARM, IA-64) that feature a switch to change endianness.
As far as byte-order-independent programming goes, the only case when you really need to do it is to deal with networking. There are functions such as ntohl and htonl to help you converting your hardware's byte order to network's byte order.

A:
Can a.out both run on little-endian and big-endian system?

No, because pretty much any two CPUs that are so different as to have different endian-ness will not run the same instruction set. C++ isn't Java; you don't compile to something that gets compiled or interpreted. You compile to the assembly for a specific CPU. And endian-ness is part of the CPU.
But that's outside of endian issues. You can compile that program for different CPUs and those executables will work fine on their respective CPUs.

What makes a system little-endian or big-endian?

As far as C or C++ is concerned, the CPU. Different processing units in a computer can actually have different endians (the GPU could be big-endian while the CPU is little endian), but that's somewhat uncommon.

If I want to write a byte-order independent C++ program, what do I need to take into account?

As long as you play by the rules of C or C++, you don't have to care about endian issues.
Of course, you also won't be able to load files directly into POD structs. Or read a series of bytes, pretend it is a series of unsigned shorts, and then process it as a UTF-16-encoded string. All of those things step into the realm of implementation-defined behavior.
There's a difference between "undefined" and "implementation-defined" behavior. When the C and C++ spec say something is "undefined", it basically means all manner of brokenness can ensue. If you keep doing it, (and your program doesn't crash) you could get inconsistent results. When it says that something is defined by the implementation, you will get consistent results for that implementation.
If you compile for x86 in VC2010, what happens when you pretend a byte array is an unsigned short array (ie: unsigned char *byteArray = ...; unsigned short *usArray = (unsigned short*)byteArray) is defined by the implementation. When compiling for big-endian CPUs, you'll get a different answer than when compiling for little-endian CPUs.
In general, endian issues are things you can localize to input/output systems. Networking, file reading, etc. They should be taken care of in the extremities of your codebase.

A: The first thing to clarify is that endianness is a hardware attribute, not a software/OS attribute, so WinXP and Linux are not big-endian or little endian, but rather the hardware on which they run is either big-endian or little endian.
Endianness is a description of the order in which the bytes are stored in a data-type.  A system that is big-endian stores the most significant (read biggest value) value first and a little-endian system stores the least significant byte first.  It is not mandatory to have each datatype be the same as the others on a system so you can have mixed-endian systems.
A program that is little endian would not run on a big-endian system, but that has more to with the instruction set available than the endianness of the system on which it was compiled.
If you want to write a byte-order independent program you simply need to not depend on the byte order of your data.

A: 1: The output of the compiler will depend on the options you give it and if you use a cross-compiler. By default, it should run on the operating system you are compiling it on and not others (perhaps not even others of the same type; not all Linux binaries run on all Linux installs, for example). In large projects, this will be the least of your concern, as libraries, etc, will need built and linked differently on each system. Using a proper build system (like make) will take care of most of this without you needing to worry.
2: Virtual machines abstract the hardware in such a way as to allow essentially anything to run within anything else. How the operating systems manage their memory is unimportant as long as they both run on the same hardware and support whatever virtualization model is in use. Endianness means the byte-order; if it is read left-right or right-left (or some other format). Some hardware supports both and virtualization allows both to coexist in that case (although I am not aware of how this would be useful except that it is possible in theory). However, Linux works on many different architectures (and Windows some other than Ixxx), so the situation is more complicated.
3: If you monkey with raw memory, such as with binary operators, you might put yourself in a position of depending on endianness. However, most modern programming is at a higher level than this. As such, you are likely to notice if you get into something which may impose endianness-based limitations. If such is ever required, you can always implement options for both endiannesses using the preprocessor.

A: The endianness of a system determine how the bytes are interpreted, so what bit is considered the "first" and what is considered the "last".
You need to care about it only when loading or saving from some sources external to your program, like disk or networks.


text:
Q: Android Calendar object issue java.lang.IllegalArgumentException: no field 'serialVersionOnStream' of type int I have used Calendar object inside one of the model classes. I am getting the exception
0   java.lang.IllegalArgumentException: no field 'serialVersionOnStream' of type int
1       at java.io.EmulatedFields.findMandatorySlot(EmulatedFields.java:188)
2       at java.io.EmulatedFields.put(EmulatedFields.java:458)
3       at java.io.EmulatedFieldsForDumping.put(EmulatedFieldsForDumping.java:126)
4       at java.util.Calendar.writeObject(Calendar.java:1389)

A: I quickly looked the Android 5.1.1 source code, but did not find a reason for this. Probably a bug in some Android source file anyway. If you don't need the timezone information use a long millisecond timestamp instead of Calendar. You can get the milliseconds from a Calendar object by calling getTimeInMillis.
https://android.googlesource.com/platform/libcore.git/+/android-5.1.1_r34/luni/src/main/java/java/io/EmulatedFields.java
https://android.googlesource.com/platform/libcore.git/+/android-5.1.1_r34/luni/src/main/java/java/util/Calendar.java


text:
Q: How do you prove $| \int (f)| \leq \int (|f|)$? For an integrable function $f$ on $(a,b)$, how would you prove $| \int (f)| \leq \int (|f|)?$

A: Let $f$ be a complex measurable function on $(a,b)$. Choose a complex number $\alpha$ such that $\left|\alpha\right|=1$ and $\alpha \int f=\left|\int f\right|$. We now compute that:
$\left|\int f\right|=\alpha \int f = \int \alpha f\leq \int \left|f\right|$.
Exercise 1: Why does the inequality hold in the above proof? (Hint: observe that the first equality shows that $\int \alpha f$ is a real number.)
Exercise 2: The proof above tells you under what conditions equality holds in the inequality $\left|\int f\right|\leq \int \left|f\right|$. State these conditions. (Hint: equality holds in the inequality given if and only if $\int \alpha f = \int \left|f\right|$.)
I think that it is worth explaining the intuition behind the above proof. The case when $f\geq 0$ is trivial. Let us consider the case $f<0$. In this case, we wish to show that $\left|\int f\right|\leq \int \left|f\right|$. The key point is to use the case $f\geq 0$; we can apply the case $f\geq 0$ to $-f$ and conclude that $\left|\int (-f)\right|\leq \int\left|(-f)\right|=\int (-f)$.
Exercise 3: Deduce that $\left|\int f\right|\leq \int \left|f\right|$ if $f<0$.
In the general case, the complex number $\alpha$ above acts in a similar way to the transference of the case $f<0$ to the case $f\geq 0$.


text:
Q: Check if NaN without real variable I have a TIMER (JSFiddle), that takes a date and time and then counts the hours from the starting date / time the current date / time.
In my fiddle it just counts away from January 01, 2020 14:00:00, but on my website the user is able to change this date. – When he enters invalid information the timer outputs NaN.
When the users enters information, the timer is run again and the user get a new output. – When this happens, I would like to check, if the output is NaN, if so, I would like for another function to ben run, let's call it: timerError() – With this I will reset the timer and tell the user, that his input was invalid.
I know about isNaN(variable), but I don't really have a variable here, so don't know how to check, if the timer output is NaN…
This is my JS:
                // TIMER Styling START
                function styleChars(targetEl) {
                    const val = targetEl.textContent;
                    const chars = val.split('');
                    targetEl.innerHTML = chars.map(c => `<span class="digit">${c}</span>`).join('');
                }

                const target = document.querySelector('.value_timer');
                console.log(target);
                styleChars(target);
                // TIMER Styling END

                // TIMER START
                var timerDate = "January 01, 2020 14:00:00";

                    function setTimer() {
                        // Month Day, Year Hour:Minute:Second, id-of-element-container.
                        countUpFromTime(timerDate, 'countup1');
                    };

                    window.onload = setTimer();

                    function countUpFromTime(countFrom, id) {
                        let countDate = new Date(countFrom);
                        let now = new Date();
                        let timeDifference = (now.getTime() - countDate.getTime());

                        let value_timer = Math.floor(timeDifference / 1000 / 60 / 60);

                        let idEl = document.getElementById(id);
                        idEl.innerHTML = value_timer;
                        styleChars(idEl); // Pass element to styling function.

                        clearTimeout(countUpFromTime.interval);
                        countUpFromTime.interval = setTimeout(function () {
                            countUpFromTime(countFrom, id);
                        }, 1000);
                    }

                // TIMER END

A: The problem is that if timerDate is not a valid date string format, new Date(timerDate) will return an InvalidDate.
In your code, you need to check if countDate which is new Date(timerDate) is an Invalid Date. If so, handle the error accordingly.
You can check by verifying isNaN(countDate.getTime()). It should be true if the Date is invalid.
EDIT: I have created a Fiddle that makes your code compliant with the changes.


text:
Q: Simulate a bad TCP connection with iptables? I want to forward TCP connections on a certain port of the machine A to another port on the machine B (which is actually the same that originated the connection to machine A) and simulate random or deterministic packet drops.
How can I do it with iptables?

A: man what? right, man iptables:

statistic
This module matches packets based on
  some statistic condition.  It supports
  two distinct modes settable with the
  --mode option.

or

random
This module randomly matches a certain
  percentage of all packets.
  --average percent
      Matches the given percentage. If omitted, a probability of 50% is set.

A: If using FreeBSD is an option ipfw in FreeBSD has got some excellent features to mimic various types of connections. It can add latency, packet loss etc. Very useful for testing WAN performance of an application.
There are commercial products to do this as well. I can recommend Linktropy, we use it extensively to test our in-house applications. The mini2 model only costs a few hundred USD and is enough for most usecases.
http://www.apposite-tech.com/products/mini2.html


text:
Q: How can I make space between Bootstrap columns? I have a two column row in bootstrap. How do I create space between the columns. - My first col is 8, but I want to make it 7 and have 1 column as just space.
Here's my bootply:
http://www.bootply.com/mwGajBOEVe
Here's my HTML.

The apple tree (Malus domestica) is a deciduous tree in the rose family best known for its sweet, pomaceous fruit, the apple.

        The orange (specifically, the sweet orange) is the fruit of the citrus species Citrus × sinensis in the family Rutaceae.

Should I create empty columns to do this?

A: No, use offsets like this

.col-md-4

.col-md-4 .col-md-offset-4

.col-md-3 .col-md-offset-3

.col-md-3 .col-md-offset-3

.col-md-6 .col-md-offset-3

A: you can do like this:

Join our growing


text:
Q: put stream from tcpdump into an array - which python version should i use? i want to use python in combination with tcpdump to put the generated stream from tcpdump into a more readable way. There are some fields in the streams with interesting values.
I found some stuff here at stackoverflow regarding python and tcpdump but in my mind the best way is to put it in an array.
After this is done i want to read some fields out of the array, and than it can be cleared and used for the next network frame.
Can somebody give me some hints, how this can be done?

A: You can use the python libpcap library to capture network packets directly from python :).

A: You can try using Scapy sniffing function sniff, append the captured packets to a list and do your extraction process.


text:
Q: Cannot invalidate launchd kextcache from helper executable I've built an uninstaller that call helper executable with elevated permissions to remove my driver's launchd-plist, so that it won't come up again on the next boot cycle.
In order reflect the new stage of /Library/LaunchDaemons, I invalidate the kextcache using the following command  touch /Library/Extensions/ showed in this question.
However, when I do so from the helper executable right after the plist file was removed, it wouldn't succeed, and my driver still go up after reboot.
When I do it manually by typing the command touch /Library/Extensions right after the uninstaller helper finish, it does the trick.
here's how my code looks like in the first option (invalidate from the helper exec).
        remove(OSX_LAUNCHD_PLIST_PATH);
        pid_t pid = -1;
        char const * args[] = {"touch", "/Library/Extensions", NULL};
        posix_spawn(&pid, "/usr/bin/touch", NULL, NULL, (char **)args, NULL);
        waitpid(pid, &status, WNOHANG|WUNTRACED);

perhaps you could tell me why do I get different behaviour in each of the options.
UPDATE:
it seems like the cache invalidation requires to repeat this command more than once. This code worked to me, but i don't have a clue why ...
        for (int x=0 ; x < 2; x++ ) {
            char const * args[] = {"touch", "/Library/Extensions", NULL};
            posix_spawn(&pid, "/usr/bin/touch", NULL, NULL, (char **)args, NULL);
            waitpid(pid, &status, WNOHANG|WUNTRACED);
            char const * args2[] = {"touch", "/System/Library/Extensions", NULL};
            posix_spawn(&pid, "/usr/bin/touch", NULL, NULL, (char **)args2, NULL);
            waitpid(pid, &status, WNOHANG|WUNTRACED);
        }


text:
Q: Jquery Datatables class not being recognised by jquery in codeigniter Hi frds I am trying to access the class which I have given to an image in jquery data-tables but there is no response on the browser-side.
Controller:
function load_image(){

    $this->datatables
        ->select('image')
        ->from('details')
        ->add_column('preview', '<img class="preview" width="100" height="100" src ="assets/Data/adv_images/$1">', 'image');

    echo $this->datatables->generate();
}

Using this controller I am able to load the image in the data-table. The following piece of code is loading the data-tables on the browser. When I click on the Image there is no alert dialouge box on the screen. Using web-console I am able to see the image class preview.  Why I am not able to get the alert box on click.
$(document).ready(function() {

          $('#example').dataTable
          ({
            'bProcessing'    : true,
            'bServerSide'    : true,
            'sAjaxSource'    : '<?php echo base_url();?>load_image',
            'iDisplayStart'  : 0,
            'fnServerData': function(sSource, aoData, fnCallback , oSettings)
            {
              $.ajax
              ({
                'dataType': 'json',
                'type'    : 'POST',
                'url'     : sSource,
                'data'    : aoData,
                'success' : fnCallback,
                'cache'   : false
              });
            }
          });

        $('.preview').click(function(){
                        alert('hi');
                        })
        });

A: You set the click eventhandler before the datatable wih the preview image is loaded.
Use this instead:
$('#example').on('click', '.preview', function() {
    alert('hi');
});

See the documentation for details.


text:
Q: How to check if id already exists - codeigniter i am trying to check if an id in the database already exists and if it does not then only insert that id and not the other ones that exist
I have tried to do a where statement that checks if their is a id exists in the database but even if their are new information it does not insert it into the database
Im quite lost here
any guidance would be appreciated
ps i dont want to update a row i want to insert a new updated one that does not exist
$this->db->where('id',$id);
$q = $this->db->get('testing');

if($q)
{
    //Do nothing
}
else
{

    $this->db->set('id', $id);
    $this->db->set('message', $message);
    $query= $this->db->insert('testing');

}

A: $ql = $this->db->select('id')->from('testing')->where('id',$id)->get();

if( $ql->num_rows() > 0 ) {} else {
    $a = array('id' => $id, 'message' => $message);
    $this->db->insert('testing', $a);
}

This should do it.

A: You have a logic issue with your code that you need to fix.
In your code, you save the result from your query as $q = $this->db->get('testing'),
and $q will always evaluate to true regardless of the number of rows your return.
You need to check the number of rows using $query->num_rows() > 0 and then the rest
of you code will behave as you expect.
For more details, see: http://ellislab.com/codeigniter/user-guide/database/results.html

A: You should try like this:
public function record_exists(){
   $exists = $this->db->get_where('table_name', array('id' => $id));
   if($exists->num_rows() > 0 ){
       echo "Some message";
       return false;
   }else{
      // Insert your data into the database...
   }
}

A: Model
<?php
class Fruits_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    function check()
    {
        $query = null; //emptying in case

        $id   = $_POST['id']; //getting from post value
        $name = $_POST['name'];

        $query = $this->db->get_where('fruits', array(//making selection
            'id' => $id
        ));

        $count = $query->num_rows(); //counting result from query

        if ($count === 0) {
            $data = array(
                'name' => $name,
                'id' => $id
            );
            $this->db->insert('fruits', $data);
        }
    }
}

?>

A: You need to select the id's in your MYSQL table with the id you want to check and then count the rows. If the row count is 0 then the id doesn't exist.
     $query = mysql_query("SELECT * FROM     your_table WHERE id='$id'");
     $count = mysql_num_rows($query);
     If($count!=0){
     // id exists
     } else {
     // id doesn't exist
     }

A: normally 'id' field is set with auto_increment and set primary which is unique and not repeatable. So there is not problem to worry about existing.
However, in your case I think you are not using it as a 'unique field'.
Let me give you an example.
Here I have a table name 'fruits'
++++++++++++++++++++++++++++++++++++
ငfruit_id  | int (primary)
name      | text
id        |  int
++++++++++++++++++++++++++++++++++++++

in your model
function checkId($id)
{
   $query=$this->db->get_where('fruits',array('id'=>$id)); //check if 'id' field is existed or not

   if($query!=null)  // id found stop
   {
     return FALSE;
   }
   else // id not found continue..
   {
       $data = array(
             'fruit_id' => $fruit_id ,
              'name' => $name ,
             'id' => $id
        );
      $this->db->insert('fruits', $data);
   }
}

A: For Checking An Id Or any column value exist not in database CI have a validation rule for it.
See it live here: Validation Rule
Rule: is_unique
Returns FALSE if the form element is not unique to the table and field name in the parameter. Note: This rule requires Query Builder to be enabled in order to work.
Example: is_unique[table.field]
$this->form_validation->set_rules(
        'username', 'Username',
        'required|min_length[5]|max_length[12]|is_unique[users.username]',
        array(
                'required'      => 'You have not provided %s.',
                'is_unique'     => 'This %s already exists.'
        )
);

For More Advance use of validation, You can add all validation Setting Rules Using an Array.
        $this->form_validation->set_rules(
            'username', 'Username',
            'required|min_length[5]|max_length[12]|is_unique[users.username]',
            array(
                    'required'      => 'You have not provided %s.',
                    'is_unique'     => 'This %s already exists.'
            )
    );

    $config = array(
        'your_rule_name' => array(
                array(
                        'username', 'Username',
                        'required|min_length[5]|max_length[12]|is_unique[users.username]',
                        array(
                                'required'      => 'You have not provided %s.',
                                'is_unique'     => 'This %s already exists.'
                        )
                )
        ),
        array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required'
        )
);

$this->form_validation->set_rules($config);


text:
Q: Remove linebreaks before and after text I have the following text:

"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nSome text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text Some text\r\n \r\nSome other text Some other text Some other text Some other text Some other text Some other text\r\n \r\n\r\n\r\n\r\n".

How can I remove the \r\n before and after the text but keep them in the middle of the text?

A: You can use String.Trim method:

Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

str = str.Trim('\r','\n');

A: The String.Trim() method removes leading and trailing whitespace (including line breaks of any kind). Assuming that you would want to remove leading and trailing tabs and spaces also, you can simply use:
text = text.Trim();

A: You can use Environment.NewLine as argument to Trim() method to remove all the newline characters from the string.
Try This:
 string newStr = str.Trim(Environment.NewLine.ToCharArray());

EDIT: Environment.NewLine works based on the O.S platform under which you are running the application.


text:
Q: How to add a new column to BAM BizTalk tables which has 1 billion records We have all transactions of our application logged in BizTalk BAM tables. We perform billing activities every month using these tables.We get around a billion transactions every month in this table. We got a new requirement of adding a new column to BAM__Completed table after 6 years.
So our plan is to take backup of this table(which takes time to long time), drop the BAM tables and recreate the activity. But the application should be down until this activity is done and which is not acceptable here.
Is there any other procedure to simply add a new column to BAM tables with out taking BizTalk down?

A: I suggest you create a new activity to collect the data with this additional field to a new set of BAM tables. Then merge the old bam_completed table to the new bam_completed table.

A: you can archive the BAM data from bam primary import database to BAM Archive databse. They add a new column using new activity after that just import the data from archive database and delete the archive data. There is already sql job exists to archive the BAM database you just need to configure it –


text:
Q: angular in prod kill auto when i run npm run start i have an application in o2switch server, and i use a proxy middleware for api externe, when i run npm run start without pm2 just for test, it doesn't show error but kill automatically:

trees@0.0.0 start /home/user14212/front.test.com
ng serve --proxy-config proxy.conf.js

⠋ Generating browser application bundles...[HPM] Proxy created: [ '/api/*' ]  ->  https://back.test.com
⠏ Generating browser application bundles (phase: building)...Killed
i have tried many tricks but nothing


text:
Q: pyspark:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1055: ordinal not in range(128) I'm new in pyspark, I write a python code for reading csv as rdd.
But I concurred UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 1055: ordinal not in range(128).
Here is the solution that I tried but doesn't work:
PySpark — UnicodeEncodeError: 'ascii' codec can't encode character
import pandas as pd
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *

spark=SparkSession.builder.appName("hj").getOrCreate()
sc = SparkContext.getOrCreate()

lines = sc.textFile('/hello.csv')

lines = lines.filter(lambda row:row != header)
header = lines.first()
print(header)

I've typed in "export PYTHONIOENCODING=utf8" before spark submit, but it didn't work. Can anyone help me? thank you very much!


text:
Q: Count unique words in blog's article and save it in model I have blog with articles ( Article is model). Every article contains title and body. I need to add field, which contains list of unique words of that article and occurrence in the article. For example, article " Hello my name is John, hello", field "words" should looks like:

{"hello": 2, "my": 1, "name":1, "is":1, "john":1}

Additionally, i should have endpoint, which returns ALL words from ALL articles and their occurrence.
How I want to implement it:
Add field "unique_words" (type JSONField) and default value "please wait, word's occurrence are being calculated...". Then add post save signals which via Celery will do all calcuration and update field "unique_words" with data like this
{"hello": 2, "my": 1, "name":1, "is":1, "john":1}

Also I add endpoint, which will retrieve unique_words from all articles and summarize them.
Is it best solution?  Could you please recommend something better?


text:
Q: UICollectionView - Image is getting set randomly I am using collectionView in my App. I am setting image for the cell backgroundView in didSelect delegate. But When i select one cell indexPath the image is getting set for 3 cell indexPath. When i scroll the collectionView the images are getting changed randomly? Please Help me. thanks in advance.
- (void)viewDidLoad
{
    [super viewDidLoad];

    [collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:uio];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:       (NSInteger)section
{
     return 50;
}

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collection dequeueReusableCellWithReuseIdentifier:uio
 forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
   return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
 {
    NSLog(@"index %@",indexPath);
    UICollectionViewCell *cell = [collection cellForItemAtIndexPath:indexPath];

    cell.backgroundView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"download.jpg"]];

 }

A: That's because you reuse your cell. An option would be to have an dictionary variable to say that your cell has been selected and reset the image if it has not been.
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"index %@",indexPath);
    UICollectionViewCell *cell = [collection cellForItemAtIndexPath:indexPath];

    cell.backgroundView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"download.jpg"]];

    [selectedDictionary setObject:[NSNumber numberWithBool:YES] forKey:[NSNumber numberWithInteger:indexPath.row]];
}

Then in your cellForItemAtIndexPath method you would check that value
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    UICollectionViewCell *cell = [collection dequeueReusableCellWithReuseIdentifier:uio
 forIndexPath:indexPath];
    BOOL selected = [[selectedDictionary objectForKey:[NSNumber numberWithInteger:indexPath.row]] boolValue];

    if(selected){
        cell.backgroundView =[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"download.jpg"]];
    }else{
        cell.backgroundView = nil;
    }

    cell.backgroundColor = [UIColor whiteColor];
   return cell;
}

Of course if you use some kind of object as model, it would appropriate to have a selected variable in here, you won't need a nsdictionary any more.

A: The Problem is dequeueReusableCellWithReuseIdentifier.
When you scroll UICollectionview then cell are reused that is problem
add Collectionview inside scrollview.
Try this Inside:
Scroll_View  is Your Scroll View
collection is Your Collectionview
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.Scroll_View.contentSize = CGSizeMake(self.view.frame.size.width, collectionView.contentSize.height);
    CGRect fram_For_Collection_View = self.collection_view.frame;
    fram_For_Collection_View.size.height = collectionView.contentSize.height;
    self.collection.view.frame = fram_For_Collection_View;
}

A: Your -collectionView:didSelectItemAtPath: is adding a new image view to the cell. Nothing is removing that image view when the cell is reused. So, when you say:
UICollectionViewCell *cell = [collection dequeueReusableCellWithReuseIdentifier:uio

forIndexPath:indexPath];
in your -collectionView:cellForItemAtIndexPath:, you're may get back some cell that already has one or more image views.
My suggestion would be to add the image view to the cell in the cell prototype, perhaps in your storyboard or in the cell's initializer. Have your -collectionView:cellForItemAtIndexPath: set the image for that image view to the correct image for the given path.

A: What's happening is that UICollectionView reuses cells. So in didSelectItemAtIndexPath: you set the cell background, but then the UICollectionView reuses that same cell as needed (and you're not resetting the cell.backgroundView in cellForItemAtIndexPath:).
The way to fix this is to maintain an NSIndexSet of selected cells. In didSelectItemAtIndexPath: you can add the index of the item that was selected, and then force a reload of that item by calling reloadItemsAtIndexPaths. Then, in your cellForItemAtIndexPath: check the index set to see if the selected index is included, and if so, set the backgroundView of the cell.

A: I had the same issue few days ago & I posted a question here. Here is the answer I got & it works for me.
Collection View Cell multiple item select Error
And also if you are using a custom cell you can add this code to the init method of that cell & it will work too.
        CGFloat borderWidth = 6.0f;
        UIView *bgView = [[UIView alloc] initWithFrame:frame];
        bgView.layer.borderColor = [UIColor redColor].CGColor;
        bgView.layer.borderWidth = borderWidth;
        self.selectedBackgroundView = bgView;


text:
Q: How can I read a file from the command line using scanner It wont prompt the user to enter file? Please help me
public static void main (String args []){
if (0 < args.length) {
     File inFile = new File(args[0]); // Make sure the file exists, can read, etc...
     while (!inFile.exists()) {
      Scanner console = new Scanner (inFile);
      System.out.println ("Input file:"); //prompt user to input file
         String inFileName = console.nextLine();
         System.out.println ("Input file:"); //prompt user to input file
         inFileName =inFileName.trim(); //get rid of whitespace
           System.out.println(inFileName);
         inFile = new File (inFileName);
      }

A: The old way :
BufferedReader reader = new BufferedReader( new InputStreamReader( System.in)); String userInput = reader.readLine();

The new way :
Console console = System.console();
if( console != null) { String userInput = console.readLine();

A: For Scanner you need to use.
Scanner console = new Scanner(System.in);

A: I suppose you can do the expected task with few lines of code.
public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        System.out.println("Input file : ");
        String inFile = userInput.next();
        System.out.println("Input file is " + inFile);
    }


text:
Q: Painting plane with 2 colors (2 points separated by 10 cm different colors ) Can you paint a plane using 2 colours, so that any 2 points which are separated by 10 cm will have different colours?

A: No you can't, because there are three points that are vertexes of an equilateral triangle with a side of $10\,\rm cm$ and you can't have all 3 vertex colored differently.


text:
Q: ¿Cómo insertar valores de dos radio button con PHP y MySQL? lo que pasa es que tengo un pequeño problema al momento de guardar valores de dos radio button en una base de datos MySQL. Al momento de guardar los datos en la bd, me aparece un mensaje llamado "on" en las filas, ¿Que querrá decir eso? Porqué no se están guardando los datos?
formulario.php
***

Planificación de la Faena

                  <form action="php/form1_faena.php" method="POST">

                          Tipo de Personal:

                          <input type="radio" name="radiogroup1" id="ravi" class="radio-button">
                          Personal de Instalación
                          <input type="radio" name="radiogroup1" id="ravi1" class="radio-button">
                          Personal Contratista

                          Tipo de Instalación:

                          <input type="radio" name="radiogroup2" id="ravi2" class="radio">
                          Instalación desenergizada

                          <input type="radio" name="radiogroup2" id="ravi3" class="radio">
                          Instalación energizada

                          <input type="text" placeholder="Planta Perteneciente" class="company" name="planta">

                          <input type="text" placeholder="Puesto de Trabajo" class="puesto" name="puesto">

                          <input type="text" class="fecha" id="datetime" placeholder="Seleccionar Fecha y Hora" name="fecha">

                          <select class="trabajo" name="tipo">
                              <option>Seleccionar el tipo de trabajo</option>
                              <option>Bomba de agua</option>
                              <option>Ventilador de aire</option>
                              <option>Mantenimiento de Maquinarias</option>
                          </select>

                          <select class="ubicacion" name="ubicacion">
                              <option>Seleccionar Ubicación</option>
                              <option>Caldera</option>
                              <option>Turbinas</option>
                              <option>Molinos</option>
                          </select>

                          <input class="button" type="submit" value="Registrar" name="insert" >

                  </form>

form1_faena.php
***<?php
include 'conexion_be.php';

    $tipo_personal = $_POST['radiogroup1'];
    $tipo_instalacion = $_POST['radiogroup2'];
    $planta = $_POST['planta'];
    $puesto = $_POST['puesto'];
    $fecha = $_POST['fecha'];
    $tipo_trabajo = $_POST['tipo'];
    $ubicacion = $_POST['ubicacion'];

    $query = "INSERT INTO planificacion_faena(tipo_personal, tipo_instalacion, planta, puesto_trabajo, fecha, tipo_trabajo, ubicacion) VALUES('$tipo_personal', '$tipo_instalacion', '$planta', '$puesto', '$fecha', '$tipo_trabajo', '$ubicacion')";

    $ejecutar = mysqli_query($conexion, $query);

    if ($ejecutar) {
        echo '';
    }else{
        echo '';
    }

?>******

Como se ve en la imagen, aparece el mensaje que mencioné anteriormente, los otros valores si se guardan, pero no los que corresponden a los dos radiobutton.

A: Necesitas ponerle el value a tu radiobuttons
<input type="radio" name="radiogroup1" id="ravi" class="radio-button" value="Contratista">
<input type="radio" name="radiogroup1" id="ravi1" class="radio-button" value="Instalación">


text:
Q: bootstrap container margin is modified when I don't need it I don't understand what's going on, I have a container class applied to a div, margins work perfectly, but when the content within the div exceed the height of the viewport (scroll bar shows up) the container modifies automatically left and right margins... so when navigating through my HTML files I can notice this particular HTML has different margins values...
To replicate this behaviour you need to add an extra lorem300 to the div.

Turnos Octubre

En esta seccion se detallan los turnos a cumplirse durante Octubre

                Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni, assumenda quaerat sequi, dignissimos voluptates vero odio omnis quas, quisquam doloremque consequatur dicta veritatis quibusdam recusandae. Odit velit tenetur nam quam blanditiis, sed quis facere doloribus obcaecati a iure accusamus est nemo soluta unde repellendus deserunt voluptatibus quas consequatur iusto porro. Ut, voluptate maiores. Sunt eos culpa, amet error sint repellat sed temporibus, quia harum perferendis nam. Doloribus quia laboriosam minus nobis nesciunt nisi? Deleniti ab numquam et facere aliquam, quaerat explicabo. Eius totam est temporibus sed! Vel error, illo eligendi officia assumenda nulla tenetur iste, nobis atque magni veniam in delectus autem id inventore deserunt repudiandae ab, consectetur molestias. Quasi tempora placeat facere, reiciendis dicta accusantium debitis corporis? Aperiam vero, velit dolor, dignissimos, optio ea fuga quidem obcaecati ad autem aspernatur odio suscipit ab eveniet atque. Sit esse quibusdam omnis nihil corrupti magni sapiente dolore debitis, nesciunt quis. Tempora atque quisquam, deleniti voluptatem repellendus dignissimos quibusdam veritatis magnam laborum asperiores fugiat maxime quas numquam eos consequatur autem. Tenetur amet quia, repudiandae beatae facilis exercitationem deserunt aliquid, voluptatum iusto quisquam eveniet quam! Expedita pariatur itaque in voluptatum consequuntur facilis asperiores unde, quasi, assumenda commodi, delectus ullam harum. Rem aspernatur voluptatum expedita, assumenda, eligendi dolorum amet iure, error veniam corrupti sit repellat eius odio sed suscipit incidunt ut beatae molestias labore? Repudiandae vel iure sequi ducimus tempore, vero enim nemo sapiente laboriosam assumenda id! Assumenda eius, ad quos nesciunt aliquid possimus tenetur, quibusdam ratione nostrum sequi nisi. Nesciunt tempore fuga itaque ipsam debitis, atque iure ex earum cum totam sunt excepturi labore numquam corrupti, expedita harum praesentium iste assumenda quos porro? Quo asperiores, earum velit, praesentium ipsum consequatur perferendis ullam, illum atque voluptate a. Fugit exercitationem facere repellendus voluptatem maiores impedit deleniti ducimus, officia, numquam soluta similique aliquam modi assumenda deserunt ullam.


text:
Q: How to select this element with jQuery? I have this piece of HTML code.

姓名

{{ i.mem_name }}

组别

{{ i.mem_group }}

年级

{{ i.mem_year }}

<button class="btn btn-danger btn-sm deleteNode" onclick="delNode(this)">Delete</button>

And I write js as follows,
function delNode(btn) {
    var mem_item = $(btn).parent().parent();
    var mem_name = $(mem_item).children("div.mem_name").text();
    alert(mem_name);
    console.log(mem_name);
    mem_item.hide()
}

I want to get the text value of div.mem_name, but somehow it just does not work:(

A: The children function only travels down the immediate children of the element. You can use find to search down the tree of children. This should work:
var mem_name = $(mem_item).find("div.mem_name").text();

This is from the jQuery children() documentation:

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

Similarly, your parent().parent() call can be replaced with closest() or parents():
var mem_item = $(btn).parents(".member-item");

A: You can use .closest and .find together
Script :
$(document).ready(function(){
            $(".deleteNode").click(function(){
                var mem_name = $(this).closest('.row').find('.mem_name').text();
                alert(mem_name);
                console.log(mem_name);
            });
        });

HTML :

姓名

name

组别

mem_group

年级

mem_year

<button class="btn btn-danger btn-sm deleteNode" >Delete</button>

JSFIDDLE DEMO


text:
Q: Remember Page Session So I'm looking for the best advice on how to tackle a problem. I wanted to allow my members to be able to stayed logged in on devices when they checked "Keep me logged in". But after researching I found out that cookies would do it, but it's not secure.
So my second idea was instead just remember the page they were on and go back to it after logging back in. Simple enough. More secure(theoretically).
But the only way I can think of is by making a table in the database that records the current page the member goes to, and updates it each time the go to a new one.
Is this the best way to approach the solution, or are there any better ways? I'm open to all suggestions, and could not find any solutions elsewhere in the forums. (I'm using PHP and MYSQLi)

A: try to use one of the function in this guide.
DOM Storage Guide
i never tested it but i what think you need is the localstorage.
or this Using IndexedDB

A: Your best bet is to use a combination of cookies and session to do this. Or even secure cookies. Check out this link.
https://en.wikipedia.org/wiki/Secure_cookie


text:
Q: Is TCP PACING enabled by default on linux? I want to ask a basic question:
Is TCP PACING enabled by default on Linux? I'm using Ubuntu right now, kernel 4.4.0.
I saw that it can be enabled/disabled using TC-FQ, but is it enabled by default using TC only, or the default is disabled?

A: Short answer: for kernel 4.4.0 TCP PACING is enabled by default and is set to ~34.36Gb/s per socket. Since kernel 4.13.0-rc1, TCP PACING is disabled by default. On both cases, since TSO is enabled, TCP PACING would have no effect when pacing rate is set to the default value.
TCP PACING is set for a socket using the sock_setsockopt() function (net/core/sock.c). The flag for doing so is SO_MAX_PACING_RATE, and the handling code is as follow:
case SO_MAX_PACING_RATE:
        sk->sk_max_pacing_rate = val;
        sk->sk_pacing_rate = min(sk->sk_pacing_rate,
                     sk->sk_max_pacing_rate);
        break;

On socket creation the relevant fields are set to ~0U in sock_init_data() (net/core/sock.c):
sk->sk_max_pacing_rate = ~0U;
sk->sk_pacing_rate = ~0U;

So the default values for pacing rate and max pacing rate is max unsigned int value, which is (2^32 - 1), or 4,294,967,295 Bytes per second, which are 34.36Gb/s.
It is possible, however, to get to higher rates even with a single socket by using TCP segmentation offload (TSO). The TSO takes the pacing rate into consideration, but isn't really bounded by the default rate. In tcp_tso_autosize() function (net/ipv4/tcp_output.c) the pacing rate might reduce the size of the TSO session, but since the default value is ~4.3GB and even after shifting right by 10 you still get ~4MB, it is much bigger than the typical TSO session.
static u32 tcp_tso_autosize(const struct sock *sk, unsigned int mss_now)
{
    u32 bytes, segs;

    bytes = min(sk->sk_pacing_rate >> 10,
            sk->sk_gso_max_size - 1 - MAX_TCP_HEADER);

    /* Goal is to send at least one packet per ms,
     * not one big TSO packet every 100 ms.
     * This preserves ACK clocking and is consistent
     * with tcp_tso_should_defer() heuristic.
     */
    segs = max_t(u32, bytes / mss_now, sysctl_tcp_min_tso_segs);

    return min_t(u32, segs, sk->sk_gso_max_segs);
}

I tried actually hitting the 34Gb/s limitation, but unfortunately, without TSO CPU utilization on TX side limit the single socket BW to ~23Gb/s.
A patch by Eric Dumazet tcp: internal implementation for pacing was introduced on kernel 4.13.0-rc1. This patch enhances TCP PACING abilities. For once, it allow for pacing without using TC-FQ. It also disables pacing entirely if the sk_pacing_rate field is set to 0 or ~0U (default). See the patch cover and code for more details.


text:
Q: connection issues with AWS DocumentDB via nodejs mongodb package I have created a DocumentDB with SSL enabled and I am using mongodb package using NodeJS to connect this DB using a Bastion Host. The issue is that if I put a hardcoded string inside the MongoClient.connect function, I am able to successfully connect the DB. The hardcoded code would look like as shown below.
let MongoClient = require('mongodb').MongoClient;
let client = MongoClient.connect(
   'mongodb://User:PWD@DBURL:27017/DBNAME?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false',
    {
      tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
    },
    function(err, client) {
        if(err)
            throw err;

        console.log("1111111  2222222!!");
        //Specify the database to be used
        db = client.db('DBNAME');
        //Specify the collection to be used
        col = db.collection('COLNAME');
        console.log("1111111 connected to db!!");

       client.close();
    });

Now as that's not an ideal situation to put the hardcoded values in the code. I am trying to read the values from environment variables and trying to put the whole URL into a string variable and passing this variable into that function such as shown below.
const DBURL = "mongodb://"+user+":"+pwd+"@"+dbURL+":"+port+"/"+dbName+"?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false";
let client = MongoClient.connect(DBURL,
    {
      tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
    },
    function(err, client) {

Now this one timesout to connect the DB.
Any suggestions on it or should I use any other packages to connect DocumentDB via NodeJS, do let me know.

A: Something like this works for me:
const { MongoClient } = require('mongodb')

const DOCUMENTDB_CONNECTION_STRING = `mongodb://${process.env.DOCDB_USER}:${process.env.DOCDB_PASS}@${process.env.DOCDB_ENDPOINT}/${process.env.DOCDB_DBNAME}?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`

const client = MongoClient.connect(
    DOCUMENTDB_CONNECTION_STRING, {
        tlsCAFile: `rds-combined-ca-bundle.pem` //Specify the DocDB cert
    },
    function(err, client) {

Is this what you are looking for?


text:
Q: "The given path's format is not supported" on form load, I am making an application for school. It has four buttons and one of which opens a logs window. It gets all of the text files in each folder and displays them in a DataGridView. All of this is on a mapped network drive on a domain controller. When the form with the table loads it throws "The given path's format is not supported." This is my code:
Imports System.IO

Public Class Form2
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim dt As New DataTable
        dt.Columns.Add("Date/Time")
        dt.Columns.Add("Username")
        dt.Columns.Add("Room")
        For Each dir As String In Directory.GetDirectories("T:\(IncidentReport)\logs")
            Dim infoa As New IO.DirectoryInfo("T:\(IncidentReport)\logs\" + dir)
            Dim infob As IO.FileInfo() = infoa.GetFiles("*.txt")
            Dim infoc As IO.FileInfo
            For Each infoc In infob
                Dim log() As String
                log = File.ReadAllLines("T:\(IncidentReport)\logs\" + dir + "\" + infoc.Name)
                Dim row = dt.NewRow()
                row(0) = log(0)
                row(1) = log(2)
                row(2) = log(1)
                dt.Rows.Add(row)
            Next
        Next
        DataGridView1.DataSource = dt
    End Sub
End Class

Any ideas anyone? Bit stuck here...
(I've tried changing them to my "user area" on my domain user which I have 100% control on and there was no difference)

A: The Directory.GetDirectories() function returns FULL PATH strings:

Returns String[] An array of the full names (including paths) of
  subdirectories in the specified path, or an empty array if no
  directories are found.

So in your next line of code:
Dim infoa As New IO.DirectoryInfo("T:\(IncidentReport)\logs\" + dir)

You're concatenating a full path with another full path, which obviously won't work.
I'd approach it more like below, to side step these kinds of issues.  This re-work creates a DirectoryInfo from your main folder, then retrieves the subfolders with DirectoryInfo.GetDirectories().  From there, we iterate over FileInfo instances via DirectoryInfo.GetFiles().  Lastly, we get the full path filename with FileInfo.FullName:
Dim dt As New DataTable
dt.Columns.Add("Date/Time")
dt.Columns.Add("Username")
dt.Columns.Add("Room")

Try
    Dim folder As New DirectoryInfo("T:\(IncidentReport)\logs")
    For Each subFolder As DirectoryInfo In folder.GetDirectories
        For Each FI As FileInfo In subFolder.GetFiles("*.txt")
            Dim lines() As String = File.ReadAllLines(FI.FullName)
            If lines.Length >= 3 Then
                dt.Rows.Add(New Object() {lines(0), lines(1), lines(2)})
            End If
        Next
    Next
Catch ex As Exception
    MessageBox.Show(ex.ToString, "Error Reading Files")
End Try

DataGridView1.DataSource = dt

A: We can flatten this code considerably. Also, never pass up the chance to move code out of an the immediate event handler, or to save memory by enumerating items rather than loading them all in an array:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    DataGridView1.DataSource = LoadLogFiles("T:\(IncidentReport)\logs")
End Sub

Public Function LoadLogFiles(ByVal basePath As String) As DataTable
    Dim result As new DataTable()
    result.Columns.Add("Date/Time")
    result.Columns.Add("Username")
    result.Columns.Add("Room")

    Dim dir As New DirectoryInfo(basePath)

    For Each fileInfo In dir.EnumerateFiles("*.txt", SearchOption.AllDirectories)
        Dim row = result.NewRow()
        Dim column As Integer = 0

        'This is better if a log could have many lines and you only care about the first three.
        'If the files only have exactly three lines, just read to an array like you were.
        For Each line As String In File.ReadLines(fileInfo.Name).Take(3)
           row(column) = line
           column += 1
        Next

        result.Rows.Add(row)
    Next
    Return result
End Sub


text:
Q: How to add health check for topics in KafkaStreams api I have a critical Kafka application that needs to be up and running all the time. The source topics are created by debezium kafka connect for mysql binlog. Unfortunately, many things can go wrong with this setup. A lot of times debezium connectors fail and need to be restarted, so does my apps then (because without throwing any exception it just hangs up and stops consuming). My manual way of testing and discovering the failure is checking kibana log, then consume the suspicious topic through terminal. I can mimic this in code but obviously no way the best practice. I wonder if there is the ability in KafkaStream api that allows me to do such health check, and check other parts of kafka cluster?
Another point that bothers me is if I can keep the stream alive and rejoin the topics when connectors are up again.

A: You can check the Kafka Streams State to see if it is rebalancing/running, which would indicate healthy operations. Although, if no data is getting into the Topology, I would assume there would be no errors happening, so you need to then lookup the health of your upstream dependencies.
Overall, sounds like you might want to invest some time into using monitoring tools like Consul or Sensu which can run local service health checks and send out alerts when services go down. Or at the very least Elasticseach alerting
As far as Kafka health checking goes, you can do that in several ways

*

*Is the broker and zookeeper process running? (SSH to the node, check processes)

*Is the broker and zookeeper ports open? (use Socket connection)

*Are there important JMX metrics you can track? (Metricbeat)

*Can you find an active Controller broker (use AdminClient#describeCluster)

*Are there a required minimum number of brokers you would like to respond as part of the Controller metadata (which can be obtained from AdminClient)

*Are the topics that you use having the proper configuration? (retention, min-isr, replication-factor, partition count, etc)? (again, use AdminClient)