text:
Q: Does TCP have to be used in a one to one send/receive fashion? I'm developing an embedded system that connects to a PC over ethernet using TCP sockets.  The PC will be the TCP client, and the embedded system the server.  If I understand it correctly, the classical communication model is that the client sends some data to the server, and the server responds every time.  The server never initiates communication.
What I'd like to do is send commands from the PC to the embedded system, without corresponding  responses.  The embedded system will then execute the tasks described by the commands.  If the embedded system has an error, or has some status message to report back, it will send these back, without being polled by the PC.
I've figured out everything but the receiving on the PC side.  I'm programming the PC app in C#.net  Can I set up a callback that fires whenever data has been received on the socket? Every example I've seen uses the receive method in a blocking fashion.

A: You can use asynchronous I/O on the socket stream. This is almost exactly what you're asking for - you start a receive operation and give it a callback to call when the receive is complete.
Check out the BeginReceive/EndReceive functions.
More info here: http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx

A: The long and short of this is yes, of course.
What you want to do is fire up a new thread for each client that connects that then raises events on an event/command thread. You're under no obligation to respond to a request other than (and this is handled by your operating system's TCP/IP stack) sending ACK when you receive a packet (don't worry about this part the OS does this for you and it's part of what makes TCP/IP reliable).
As long as the socket is active you should be able to send back responses to the client, so basically you need to keep the socket active for as long as any command is running.
Here's a list of examples from Microsoft that should show you how to do this. http://msdn.microsoft.com/en-us/library/bew39x2a.aspx#Y0


text:
Q: Heat generated on thin disc plate in magnetic field There are the eddy currents in thin circular copper plate thickness h and radius a, in a harmonic magnetic field which is perpendicular to plate and the effect of auto-induction is negligible. Now we must get average heat generated on it.
As I said, I have final equation, but how do you get to this eqution. Does anyone know solution from first step to this?
$$
\overline P=\frac{1}{16}\pi\gamma ha^4B_0^2\omega
$$

A: In macroscopic EM theory, we can calculate heat being evolved due to electric current in unit time in region $V$ by
$$
\int_V \mathbf  j \cdot \mathbf E\,dV.
$$
If you express electric field in terms of $B_0$ and $\omega$ and assume Ohm's law $\mathbf j = \frac{1}{\gamma}\mathbf E$ where $\gamma$ is resistivity, you should be able to derive formula similar or same to the one you wrote above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to stub and test protected members in a service? Pre-story: I am testing a service. Every n seconds it starts some processes and runs some jobs.
I want to cover the top level of this service (a class which is inherited from ServiceBase) with an integration test. My goal is to verify: 1. that I can start it, 2. that it sets all timers and 3. creates Job Management Objects to execute jobs (at least to see one execution on the timer).
In the future we want to increase the performance by moving different jobs into different threads, which will also increase complexity of the code.(this is another reason to test it now, while it is still pretty simple)
The question itself: How should I test a service? All methods and properties in this class are protected or private. And with RhinoMocks I can only stub public members.
Some more thoughts: There is a private member AppJobManagement in this class, which I want to stub. I don't want to use the real instance of this class, as it is connected to the database and may do a lot of unwanted changes when running.
I could make it public for stubbing.
But the next issue I have, is how can I assert that the service class works correctly? I will need again make public the methods under the test. And this is what I would like to avoid.
Any advice is highly appreciated!

A: You can create a public or internal constructor to take a dependency on AppJobManagement. If you can, change the reference to an interface for this class as it may make testing easier.
public class ServiceToBeTested : ServiceBase
{
    private IAppJobManagement _appJobManagment;

    public ServiceToBeTested()
    {
        _appJobManagment = new AppJobManagement();
    }

    internal ServiceToBeTested(IAppJobManagement appJobManagment)
    {
        _appJobManagment = appJobManagment;
    }
}

If the ServiceToBeTested has a number of protected methods you would like to mock/fake, you should consider another dependency. For example, instead of:
public void DoSomethingImportant(string foo)
{
    if (someCondition)
    {
        DoThisOneWay(foo);
    }
    else
    {
        DoThisDifferently(foo);
    }
}

protected void DoThisOneWay(string foo) {}
protected void DoThisDifferently(string foo) {}

You can use another object:
public interface IServiceWorker
{
    void DoThisOneWay(string foo);
    void DoThisDifferently(string foo);
}

public void DoSomethingImportant(string foo)
{
    if (someCondition)
    {
        _worker.DoThisOneWay(foo);
    }
    else
    {
        _worker.DoThisDifferently(foo);
    }
}

The IServiceWorker _worker would be easily mocked.
Update
Another pattern is to use a Factory class to generate these objects.
public interface IAppJobManagementFactory
{
    IAppJobManagement Create(string arg1, int arg2);
}

This too can be mocked.


text:
Q: disable update for wordpress plugin named Dropbox Folder Share I have found the following plugin. Dropbox Folder Share
which is licensed under the GNU General Public License.
In the plugin I have made some minor changes. mainly added my language. but i have also changed som other things.
How can I ensure that the plugin will not be updated. so I lose my changes

A: The nicest way to do it would be to hook into 'site_transient_update_plugins'.
function so_filter_plugin_updates( $value ) {
    unset( $value->response['dropbox-folder-share/dropbox-folder-share.php'] );
    return $value;
}
add_filter( 'site_transient_update_plugins', 'so_filter_plugin_updates' );

A hacky way to do it would be to change the version number in the plugin to something ridiculously high, like 9999.999.


text:
Q: Cron Job Parameters REST API I'm just looking to submit a cron job using the Apache Zeppelin RESTful API.  The question is probably pertaining to submitting RESTful API calls of any kind though.
I'm looking to submit a POST request with JSON that sets cron job parameters.  There is the capability to submit cron job, but there is no help with specific format of how.
Two things...
1.) Is there usually an API doc stored somewhere, that the RESTFul API devs would store somewhere, that would be a common practice location for this type of document?
2.) I'm looking to submit a cron job that runs a given notebook [noteId] once a day.  I want the service to parse my JSON correctly. Do my assumptions for the JSON request make sense? Any help would be appreciated.
POST http://[zeppelin-server]:[zeppelin-port]/api/notebook/job/[noteId] HTTP/1.1
HOST: http://[zeppelin-server]
Content-Type:application/json
Accept:application/json

{
  "credentials": {
    "name": "myZeppelinUserID",
    "password": "passw0rd"
     },
    "parameters": "0 0 * * *",
}

https://www.pantz.org/software/cron/croninfo.html
https://zeppelin.apache.org/docs/0.7.0/rest-api/rest-notebook.html#add-cron-job

A: So the credentials aren't needed, I can just use the curl command and send the POST message in a UNIX script.
curl  --header "Content-type: application/json" --request POST  http://127.0.0.1:9995/api/notebook/job/2D2A6B5A8/


text:
Q: Why does my code run correctly in JGRASP but in mindtap im getting "Getting Exception in thread "main" So Im taking an intro to Java class through Cengage MindTap and the goal for the assignment was to continuously prompt a user for a password until they enter at least 2 uppercase three lowercase and one number. My code works in JGrasp but when I go to run the checks on mindtap, it seems the program is failing on the second loop after an incorrect password was entered. Below is my code that works on JGrasp and the error I get is:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ValidatePassword.main(ValidatePassword.java:13)
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
boolean valid = false;
while (valid == false)
{
String password;
int lowerCase = 0;
int upperCase = 0;
int numbers = 0;
System.out.println("Enter a password: ");
Scanner keyboard = new Scanner(System.in);
password = keyboard.nextLine();

for(int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
if (Character.isUpperCase(c))
{
upperCase++;
}
if (Character.isLowerCase(c))
{
lowerCase++;
}
if (Character.isDigit(c))
{
numbers++;
}
}
if (upperCase >= 2 && lowerCase >= 3 && numbers >= 1)
{
System.out.println("Valid password");
valid = true;
//valid set to true to break the while loop and end program.
}
else
System.out.println("The password did not have enough of the following:");
if (upperCase < 2)
System.out.println("uppercase letters");

if (lowerCase < 3)
System.out.println("lowercase letters");

if (numbers < 1)
System.out.println("digits");

}
}
}


text:
Q: sudo python3 not working to gain root acces Hi so im trying to run root on a program im doing to run some neopixles and when I try running it it comes up with the error
File "work.py", line 1
Python 3.7.3 (default, Jan 22 2021, 20:04:44)
         ^

SyntaxError: invalid syntax
I am pretty new to this so I don't really know whats wrong any thoughts why this is happening?
https://learn.adafruit.com/neopixels-on-raspberry-pi/python-usage


text:
Q: Cannot Verify JWT Using x5c (x509) public Certificate UPDATED
I'm trying to verify a JWT access token programmatically using the x5c / x509 public key value below.  I can get this working by plugging the token and x5c values into external web sites but not programmatically using JavaScript / jsrsasign.  Any suggestions would be greatly appreciated.
Here is the the OIDC provider's public JSON Web Key Set.
    {
        "keys": [
            {
                "kty": "RSA",
                "kid": "server",
                "use": "sig",
                "alg": "RS256",
                "n": "gLZO9w1OT_SWO-KbqiU0k3HevHggiY70XbDqgE1YaqhD-MwFUWNudExzF3oB28NYWYg5v6CJY0F-pUNtgukDM6ARDlh0n4xIvBRlnUnCTCx7pYOjpfXbTv49tlXmh4-ddh8EeQBLrF92u5UYs0tnZd8843mvYWohUNH1X1hM08-hpk7xCiy4XdwbeSlH757D2d5E0J0dGtZ744-dB2ZRCw2Vms_mk4Yyny4ifx2j2gIhikbb7WGmsTR2sWrtuhgZ_EBNUvrD0O54xbhQNTTFQ1pi9UZxo_gYc5Gp5fLcSOK6SDBKXbDS5hhy1vFyoa0xdgFv-xpem7YzmkKqzfjC9w",
                "e": "AQAB",
                "x5c": [
                    "MIIDMDCCAhigAwIBAgIEFIopYzANBgkqhkiG9w0BAQsFADBaMQkwBwYDVQQGEwAxCTAHBgNVBAgTADEJMAcGA1UEBxMAMQkwBwYDVQQKEwAxCTAHBgNVBAsTADEhMB8GA1UEAxMYZmNpc2Rldi5pY2UuaWJtY2xvdWQuY29tMB4XDTE4MTAwMTE4MTYyOFoXDTI4MDkyODE4MTYyOFowWjEJMAcGA1UEBhMAMQkwBwYDVQQIEwAxCTAHBgNVBAcTADEJMAcGA1UEChMAMQkwBwYDVQQLEwAxITAfBgNVBAMTGGZjaXNkZXYuaWNlLmlibWNsb3VkLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIC2TvcNTk/0ljvim6olNJNx3rx4IImO9F2w6oBNWGqoQ/jMBVFjbnRMcxd6AdvDWFmIOb+giWNBfqVDbYLpAzOgEQ5YdJ+MSLwUZZ1Jwkwse6WDo6X1207+PbZV5oePnXYfBHkAS6xfdruVGLNLZ2XfPON5r2FqIVDR9V9YTNPPoaZO8QosuF3cG3kpR++ew9neRNCdHRrWe+OPnQdmUQsNlZrP5pOGMp8uIn8do9oCIYpG2+1hprE0drFq7boYGfxATVL6w9DueMW4UDU0xUNaYvVGcaP4GHORqeXy3EjiukgwSl2w0uYYctbxcqGtMXYBb/saXpu2M5pCqs34wvcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAdtN9znA9a6luPAQurcQn8kJBlllslRWsNPMhPWpMtYaMLx6JhmDICGbaYZBGUboedwnUaEk6tE2b+EVlUE/tnaKVJms2cmCCFExQQrTHmRfFI/Vi/esVqAnz1E2dB61LMnQ2AeebXAZ/C7hRt1uXVboXr5Zokppr4FRS9QsjSK4dhcXxhfglTKJOPZ4dkSexhe6hybpL8XdGhoyf2SyNXCy5iYX0zQ5BmJaLimOcJyasZ/A7/YgsVbQyAe6Ubno6/sIUuOZ+J+snZsBSLViqcftGVPUkIWamv/yNQcEJrDWa4C+sr+9Yb7uFjuj4gDY0jvGkGmu53g0K8Vks+IfAdQ=="
                ],
                "x5t#S256": "nTAGJuFFrm-vNBdkLVNmuePwTmlXr0T87IppgJPRT9k"
            }
        ]
    }

Here is the code I'm using to verify the access token with the x5c.  I'm under the impression I should be using the x5c value, but if there is another way that is fine with me.  Just need to verify the token with the above values under keys.
// break line every 64 characters.

x5cValue = x5cValue.replace(/(.{64})/g, "$1\n");

// base64 decode

var x5cValueAtob = atob(x5cValue);

// Add Begin / END certificate

x5cValue = "-----BEGIN CERTIFICATE-----\n" + x5cValueAtob + "\n-----END CERTIFICATE-----";

var decoded = KJUR.jws.JWS.verify(accessTokenJson, rawContent, ["RS256"]);

Should I be adding the BEGIN / END PUBLIC KEY strings to the x5c value before / after base64 decode? yes, thanks to Adam
Do I need to process the x5c value before verify?
Returned response - decoded: false
Thank you in advance.

A: I spent a day scratching my head and finally got it working like
public static PublicKey getPublicKey(String x5c) throws CertificateException, IOException {
    System.out.println(" x5c ="+x5c);
    String stripped = x5c.replaceAll("-----BEGIN (.*)-----", "");
    stripped = stripped.replaceAll("-----END (.*)----", "");
    stripped = stripped.replaceAll("\r\n", "");
    stripped = stripped.replaceAll("\n", "");
    stripped.trim();
    System.out.println(" stripped ="+stripped);
    byte[] keyBytes = Base64.decode(stripped);
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    X509Certificate cer = (X509Certificate) fact.generateCertificate(new ByteArrayInputStream(keyBytes));
    return cer.getPublicKey();

}

A: This answer may not help you to answer all your questions, but I have to write it to improve the solution security.

I'm under the impression I should be using the x5c value,
  Do I need to process the x5c value before verify?

From the security point of view - do not use the x5c certificate to validate the signature directly.  In that case anybody could just provide its own certificate and spoof any identity.
The purpose if the x5t / x5t#S256 header is to identify the signer - check you trust the certificate provided by x5c or x5t#S256 (or its issuer) under the specified iss, only then you should validate the signature. The x5t headers enables your service to validate token from multiple IdP (identity providers / token issuers) or enable renewing the signer's certificate without loosing trust of the serice providers.
If you trust only a single identity provider using a single certificate, you may just directly use the provider's certificate without doing anything with the provided header.
For the solution - seems Adam is right in the comments, I as well suggest you use the KEYUTIL to load/parse the certificate


text:
Q: 80s sci-fi/fantasy cartoon where bread is somehow rolled up and used like a bomb I have been trying to identify this for years with no success. I was born in the early 90s and watched this as a small child, most likely between the years 1996 and 2001.
What I remember: English language, but could have been dubbed. Western-style cartoon animation. It did not seem particularly dated at the time (at least to my eyes), so I would guess that it was produced sometime between the 1980s and when I viewed it, probably no earlier. I may have either watched it broadcast on cable (in the United States) or on a VHS tape. It may have been either a full animated movie, or a single episode of some series.
The setting seemed to be a mixture of sci-fi and fantasy. There were strong Star Wars vibes: I remember there being both a magical or technologically advanced sword-like weapon as well as an older mentor figure. I remember a lot of green -- possibly some scenes took place in a forest? As far as the plot, I remember almost nothing except for a scene where the 'good guys' are eating some kind of meal at what I believe to be the villain's lair/castle, when one of them rolls up some bread (or similar food) into a ball with his hands and somehow uses it to make a kind of bomb/smoke bomb that helps them escape. As I was very young, some of these details may be inaccurate.

A: Well, it was Highlander: The Animated Series.
Season 1, episode 2:

Clyde: My brother's life is in danger and all you can do is make breadballs! Aren't you going to help him?
Ramírez: Shhh, calm down. I need to concentrate.
Clyde: What's that? [Ramirez sprinkles some kind of powder onto the bread???]
Ramírez: You'll see.

Then he lights it up to blast their way out. Mystery solved.


text:
Q: How to Count the frequency of specific words for each column using R? I am using this dataset https://archive.ics.uci.edu/ml/datasets/Eco-hotel
I am trying to figure out how to count the frequency of certain words like "room" or "vacation" within each column. I have attempted following tutorials online, but unfortunately, I have had no luck.

A: Using the iris dataset as an example,
what you can do is:
library(tidyverse)

iris %>%
  summarize(across(everything(), ~ sum(str_detect(., 'setosa'))))

Of course, you'd need to change the seqrch term to what you need.
If you want to have dedicated columns for each of your search patterns, you could alternatively do sth. like:
df <- data.frame(x = sample(letters, 10, replace = TRUE),
                 y = sample(letters, 10, replace = TRUE))

df |>
  summarize(across(c(x, y), ~sum(str_count(., c("u"))), .names = "{.col}_u"),
            across(c(x, y), ~sum(str_count(., c("g"))), .names = "{.col}_g"))

Here I'M searching for letters "u" and "g", respectively.


text:
Q: Start and stop Kubernetes on Azure How do you restart Kubernetes on Azure manually?
According to this article, it's possible to restart either using Azure Portal or Azure CLI but I don't see any options for this in the portal or from the az aks documentation.
https://docs.microsoft.com/en-us/azure/aks/faq#are-security-updates-applied-to-aks-agent-nodes

"You have several options for rebooting nodes:
  Manually, through the Azure portal or the Azure CLI."

How do you reboot manually, either through portal or cli?

A: We can restart the worker nodes. Those worker nodes are shown in the VMs if you use VMs for deployment or we can restart the VMSS if you deployed workers as VMSS


text:
Q: The GET method is not supported for this route. Supported methods: POST in Laravel 7 Can anyone tell me the solution to this?
Below I have mentioned web.php, Domaincontroller.php and HTML form.
Please tell me did I make a mistake in it.
web.php
Route::get('/domains','Domaincontroller@ShowDomains');
Route::post('/add_domain','Domaincontroller@AddNewDomain');

Domaincontroller.php
public function AddNewDomain(Request $request){

    $this->validate($request, [
        'domain_name' => 'required',
        'domain_register_date' => 'required',
        'domain_expiry_date' => 'required',
        'domain_registrar' => 'required',
        'registrar_username' => 'required',
        'registrar_password' => 'required',
        'registrar_email' => 'required'

    ]);

    $domain = new Domain([
        'domain_name' => $request->get('domain_name'),
        'domain_register_date' => $request->get('domain_register_date'),
        'domain_expiry_date' => $request->get('domain_expiry_date'),
        'domain_registrar'  =>$request->get('domain_registrar'),
        'registrar_username' => $request->get('registrar_username'),
        'registrar_password' => $request->get('registrar_password'),
        'registrar_email' => $request->get('registrar_email')
    ]);

    $domain->save();

    return redirect()->route('domain.add_domain')->with('Domain has been added.');

}

}

HTML Form:
<form method="post" action="{{url('/')}" enctype="multipart/form-data">
     <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

A: Your form dont send to the right url
<form method="post" action="{{url('/add_domain')}" enctype="multipart/form-data">
     <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

A: You should define named routes first:
Route::post('/add_domain','Domaincontroller@AddNewDomain')->name('adddomain');

And then reference the route in your form action:
<form method="post" action="{{ route('adddomain') }}" enctype="multipart/form-data">
     <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Just a little further cleaning, you can just use @csrf instead writing the entire input field for the CSRF token:
<form method="post" action="{{ route('adddomain') }}" enctype="multipart/form-data">
    @csrf
    // Your other fields here
</form>


text:
Q: C++ use struct as some type Suppose I have this struct:
struct shape{
    int type;
    shape(){}
    shape(int _type){type = _type;}
};

Is it possible to use shape as an int directly? In this case, shape would assume the value of its type. For example:
shape s(2);
if     (s == 1) cout<<"this shape is a circle"<<endl;
else if(s == 2) cout<<"this shape is a triangle"<<endl;
else if(s == 3) cout<<"this shape is a rectangle"<<endl;
//...

In general, is it possible to use an struct so that it will assume a chosen value of one of its attributes? In shape's case, it was an int, but it could be a string or any other type.

EDIT: I tried the code suggested by @Jarod42 using string as type:
struct shape{
    string type;
    shape(){}
    shape(string _type){type = _type;}
    operator string() const {return type;}
};

And when I write
shape s1("circle");
string s2 = "circle";
if(s1 == s2){ ...

it says error: no match for 'operator==' (operand types are 'shape' and 'std::string), although with int as type, it works fine.

A: You might add operator int:
struct shape{
    int type;
    shape(){}
    shape(int _type) : type(_type) {}

    operator int() const { return type; }
};

A: In general you can use operator T where T is the type you want to cast to. If you want to force the use of static_cast<T>(my_shape), then you can add the keyword explicit in front:
struct shape
{
    int type;

    shape() = default;
    shape(int _type) : type{ _type } {}

    operator int() const { return type; }
    explicit operator float() const { return type; }

    operator std::string() const
    {
        switch (type)
        {
            case 1:
                return "circle";
            case 2:
                return "triangle";
            case 3:
                return "rectangle";
            default:
                break;
        }
        return "(unknown shape)";
    }
};

This will work with built-in types (int, float, double), standard types (std::string, std::complex), custom struct/class types, or even a pointer or a reference (if you have a static array of values, for example). You may want to consider whether you need these conversion operators (encapsulation is a whole other discussion), but this is conceptually how you would do it.
In this example, you may also want to introduce an enum for storing your type values:
struct shape
{
    enum type_t
    {
        circle = 1,
        triangle,
        rectangle
    };

    type_t type;

    operator std::string() const
    {
        switch (type)
        {
            case circle:
                return "circle";
            case triangle:
                return "triangle";
            case rectangle:
                return "rectangle";
            default:
                break;
        }
        return "(unknown shape)";
    }

    shape(type_t _type) : type{ _type } {}

    // rest of class as before
};

A: While using a cast operator is one way to do it, as shown by @Jarod42, I suggest making the operation a bit more explicit.

*

*Add a function to get the type.

*Use the function call and the returned value in the if-else statements.

struct shape{
    int type;
    shape(){}
    shape(int _type){type = _type;}
    int getType() const { return type;}
};

and then
shape s(2);
int type = s.getType();
if     (type == 1) cout<<"this shape is a circle"<<endl;
else if(type == 2) cout<<"this shape is a triangle"<<endl;
else if(type == 3) cout<<"this shape is a rectangle"<<endl;

A: If all you want to do in the end is compare the shape by string, then there is a simpler and much safer solution:
struct shape{
    std::string type;

    shape() {}

    bool operator==(std::string const& rhs) const {
      return type == rhs;
    }
};

// and if you want to be able to do string == shape.
bool operator==(std::string const& lhs, shape const& rhs) {
  return rhs == lhs;
}


text:
Q: populate textbox data when clicking one of the items in a listbox I have a listbox (for example: the data comes from A4:A100 via rowsource in the properties menu)
If someone clicks the top item in the list box (cell A4) then in the textbox I would like to show whatever is in the cell next to it (cell B4), the next textbox I would like to show whatever may be in cell C4 etc...
This is new to me so please go easy with your terminology - So far I have this:
Private Sub ListBox1_AfterUpdate()
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(ListBox1.Value, Range("A1:B1"), 4, False)

End Sub

Where am I going wrong?

A: Use this:
Private Sub ListBox1_AfterUpdate()
    Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Sheets("the_sheet_name").Range("A1:D100"), 2, False)
    Me.TextBox2.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Sheets("the_sheet_name").Range("A1:D100"), 3, False)
    Me.TextBox3.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Sheets("the_sheet_name").Range("A1:D100"), 4, False)
End Sub

It would be better if you use range names, because you can use it "globally" in the workbook, then you can used without the the_sheet_name part.
Private Sub ListBox1_AfterUpdate()
    Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Range("myRange"), 2, False)
    Me.TextBox2.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Range("myRange"), 3, False)
    Me.TextBox3.Value = Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Range("myRange"), 4, False)
End Sub

Where Range("myRange") is a name range inside Sheets("the_sheet_name") and with the range of Range("A1:D100")
And you can use the code Me.Textbox1.value =... in the the sub runtine ListBox1_AfterUpdate or ListBox1_Click or ListBox1_Change
Well, when you use a VlookUp, you say:
VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])

Mr. VloopUp, look for this value, inside this cells/columns, and return the value in the column number #, and the data is not ordened = False | is ordened = True
If you take the range("K1:N100") in the column K you don't know in what row you have the value you are looking for, that why you use VlookUp, and you say, return the column 1 or 2 or 3 or 4 (K-N), and if you want the value in the column O you need to set the range to range("K1:O100"), and ask to return the column 5, because, is not the number of the column in the sheet, is the number of the columns inside the range you selected.
See this for more info about VlookUp
Edit #2
As you ask in the comments, the way you can format the value returned from the VlookUp is with Format
a = Format(Application.WorksheetFunction.VLookup(Me.ListBox1.Value, Range("myRange"), 2, False), "dd-mmm-yyyy")

Where:
a : is a variable, where you can store, can be a String or Variant type
Format: Is the function, that perform the operation
"dd-mmm-yyyy" : Is the date format you want. And could be as you need. Ex:
mmmm >>> January
yyyy >>> 2016
dd   >>> 02
d    >>> 2
dddd >>> Monday
mmm  >>> Jan
mm   >>> 01
m    >>> 1

Have fun with that.
Here you can see more about Format.

A: you can avoid VLooking
Private Sub ListBox1_AfterUpdate()
Dim ws As Worksheet
Dim iRow As Long

Set ws = ThisWorkbook.Worksheets("textbox")
With Me
    iRow = Me.ListBox1.ListIndex + 4

    .TextBox1.Value = ws.Cells(iRow, 2)
    .TextBox2.Value = ws.Cells(iRow, 3)
    .TextBox3.Value = ws.Cells(iRow, 4)
End With

End Sub


text:
Q: SQL combine query into one I have several insert queries:
insert into table2 (age, name)
    select '0-19', 'abc'
    where not exists (select 1 from table2 where age is null  and name is null);

insert into table2 (age, name)
    select '20-29', 'zxy'
    where not exists (select 1 from table2 where age not in ( '0-19')  and name is null);

insert into table2 (age, name)
    select '30-39', 'egt'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29')  and name is null);

insert into table2 (age, name)
    select '40-49', 'aaa'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39')  and name is null);

insert into table2 (age, name)
    select '50-59', 'rtg'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39', '40-49')  and name is null);

insert into table2 (age, name)
    select '60+', 'ghg'
    where not exists (select 1 from table2 where age not in ( '0-19', '20-29', '30-39', '40-49', '50-59')  and name is null);

I  want to insert data if the relevant condition is met. You can see they separate query. Rewrite these queries into one query. Thank you
I can try to test with anyone can rework these queries regardless nvarchar or integer.

A: Not sure whether below helps.
SELECT
    CASE WHEN Age IN ("00-19")
     THEN ("0-19")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("20-29")
     THEN ("20-29")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("30-39")
     THEN ("30-39")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("40-49")
     THEN ("40-49")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("50-59")
     THEN ("50-59")
     ELSE ("NULL")
    END AS Age,
    CASE WHEN Age IN ("60-69")
     THEN ("60-69")
     ELSE ("NULL")
    END AS Age
FROM table2

I don't know whether above helps. Would encourage you to explain what you are trying to do as then everyone can help.

A: Updated Answer:  Create a table variable to store your ranges and then join the temp variable to the table you want to insert the missing values, for example:
-- your Table2
Declare @table2 TABLE (age varchar(10), name varchar(10))

-- a temp variable table to join in order to exclude the duplicates
Declare @data TABLE (age varchar(10), name varchar(10))

    -- add all the values you want to verify existence of
    INSERT INTO @data SELECT '0-19', 'abc'
    INSERT INTO @data SELECT '20-29', 'zxy'
    INSERT INTO @data SELECT '30-39', 'egt'
    INSERT INTO @data SELECT '40-49', 'aaa'
    INSERT INTO @data SELECT '50-59', 'rtg'
    INSERT INTO @data SELECT '60+', 'ghg'

    --  before the insert (all the missing values)
    SELECT d.age, d.[name]
        FROM @data d
            LEFT OUTER JOIN @table2 t ON d.age = t.age
        WHERE t.age IS NULL

    -- do the insert
    INSERT INTO @Table2
    SELECT d.age, d.[name]
        FROM @data d
            LEFT OUTER JOIN @table2 t ON d.age = t.age
        WHERE t.age IS NULL

    -- this should now be empty
    SELECT d.age, d.[name]
        FROM @data d
            LEFT OUTER JOIN @table2 t ON d.age = t.age
        WHERE t.age IS NULL

Version 1:
Can you show us the data that is stored in the table?  Doing range searches on an age that is stored as a string might work like you think it should.
For example:
'0-19'
Is the data stored as '5' in your table or '0-19'?  If it is stored as '5' then as others have already mentioned, it's a great idea to convert that data type to numeric data type (small int or int).
Here's an example, have you ever sorted values that are stored as string (varchar) however represent a number?  For example, if we had this set of values we expect the sort to come back as:
 1,2,3,100,200,300

However we get:
 1,100,2,200,3,300

In order to sort the string properly, you will have to pad to the right up to the longest length.
In this case 3 characters.
 001 002, 003, 100, 200, 300.

In a string, each character is evaluated.
If you look at the ASCII table (https://www.ascii-code.com/) you get an idea why.
NULL is ahead of the numbers.
1 = 49 0 0
100 = 49 48 48
2 = 50 0 0
200 = 50 48 48


text:
Q: Construction of the integers. While I know the typical method for constructing the set of integers as the set of equivalence classes on the relation (a,b)~(c,d) such that a+d=c+b, I was wondering why we don't use something like
$\mathbb{Z}=\mathbb{Z}^-\cup\mathbb{N}$
where
$\mathbb{Z}^-=\{z:(\forall n\in\mathbb{N}-\{\emptyset\})(\exists! z)(z+n=0)\}$
I'm still relatively new to set theory, so I'm having trouble seeing problems with this, but if I had to make a guess, it would be that it requires the members to explicitly be negative integers, which haven't yet been defined. Or maybe it is because it depends on a definition of addition between integers and naturals which can't be defined until we've properly defined the integers. Can anyone tell me if I would be right about either of these or lead me in the right direction?

A: One could well constrcut a set $\mathbb{Z^-}$ of negative integers in whichever reasonable way one likes and claim that an integer is anything which is either a positive natural number, zero, or a negetive integer. In other words, $n$ is an integers iff $n\in\mathbb{Z}:=\mathbb{N}\cup\mathbb{Z^-}$.
The reason why we don't follow this path is that if we did so, the rules for adding and multiplying
integers would split into many different cases (e.g., negative times positive equals positive; negative plus positive is either negative, positive,
or zero, depending on which term is larger, etc.) and to verify all the
properties would end up being much messier.


text:
Q: Any way to except empty field from $request->all() in laravel? I want to except empty value field from $request->all();

Array ( [first_name] => Dev 1 [password] => [last_name] => [phone] => 123456 [password_confirmation] => )

I got the array like this but I want to except field from above array like last_name, password which has no value.
Any way to do this without for loop.
I mean laravel provide any default method for that ?
Thanks

A: array_filter will remove empty elements:
$filtered = array_filter($request->all());


text:
Q: How to read/write bmp file in MFC? How to read/write bmp file in MFC?
I did following way.
To read the BMP file
Used fread()/fseek()/ftell() function
For writing
Used fwrite() function and it is working.
Please suggest any other way doing of reading /writing bmp file in MFC.
Client will send bmp file and server will read and save the image file.

A: If you're developing for Windows use the ATL/MFC CImage class - it is part of the shared MFC/ATL classes.
Here is a good tutorial on Bitmaps.


text:
Q: Python: error in module importation I'm trying to install basemap module for python (2.7).
I already add the path (~/local/lib64/python2.7/site-packages/mpl_toolkits/basemap) in PYTHONPATH, and in sys.path but I'm unable to import basemap module.

from mpl_toolkits import basemap
Traceback (most recent call last):
    File "testmap.py", line 17, in
      from mpl_toolkits import basemap
  ImportError: cannot import name basemap

I've also tried to do the same thing with a simple file:

def hello1():
print 'HelloWorld!'

I can't import this one either, so it doesn't seems to come from an error in basemap installation.


text:
Q: What makes this Laravel permissions-checking middleware fail? I am working on a blogging application in Laravel 8.
The application gives the users rights by assigning them roles. Every role has a set of permissions. There is a many-to-many relationship between roles and permissions.
In the user-rights view, I output each user's permissions successfully:
 @foreach ($user->role->permissions as $permission)
    {{ $permission->slug }}
 @endforeach

The goal
I am trying to restrict access to the Site settings section of the application, like this:
// Settings routes
Route::group(['prefix' => 'settings', 'middleware' => ['checkUserPermissions:edit-settings']], function() {
    Route::get('/', [SettingsController::class, 'index'])->name('dashboard.settings');
});

For this purpose, I have created the checkUserPermissions middleware:
class CheckUserPermissions
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */

    // Permissions checker
    public function hasPermissionTo($permission) {
        return in_array($permission, Auth::user()->role->permissions->toArray());
    }

    public function handle(Request $request, Closure $next, ...$permissions)
    {
      // Check user permissions
        foreach ($permissions as $permission) {
          if (!$this->hasPermissionTo($permission)) {
            $permission_label = join(' ',  explode('-', $permission));
            return redirect()->back()->with('error', 'You do not have permission to ' . $permission_label);
          }
        }

        return $next($request);
    }
}

The problem
Although the super admin does have the permission to edit settings, dd(in_array($permission, Auth::user()->role->permissions->toArray())) returns false.
That means that the restriction(s) apply when they should not.
NOTE
dd(Auth::user()->role->permissions->toArray()) returns:

Questions

*

*What causes this bug?

*What is the easiest fix?

A: In your custom middleware, you need to compare the permission to the slugs
return in_array($permission, Auth::user()->role->permissions()->pluck('slug')->toArray());

A: Since you're eager loading permissions, Eqloquent will return a collection of models. Inside of the Collection instance, there is a pluck method that will create a new collection of columns.
Using the toArray method, you will then end up with the expected array that your $permission will match to:
Auth::user()->role->permissions->pluck('slug')->toArray()

An alternative way would be to use PHP native methods (array_column) to achieve this. You could then return a list back to the view of all of the missing permissions as apposed to a single missing permission. This is untested but should just work out the box:
public function handle(Request $request, Closure $next, ...$permissionsToTest)
{

    $permissions = array_column(Auth::user()->role->permissions->toArray(), 'slug');

    $results = array_map(fn(string $permission): bool => in_array($permission, $permissions), $permissionsToTest);
    $failedResults = array_keys(array_filter($results, fn(bool $result): bool => !$result));
    $missingPermissions = array_map(fn(int $key): string => 'You do not have permission to ' . implode(' ', explode('-', $permissionsToTest[$key])), $failedResults);

    # Utilise the built-in "errors"
    return empty($missingPermissions) ? $next($request) : redirect()->back()->with('errors', $missingPermissions);
}

For a vanilla PHP mock-up example, See it 100% working over at 3v4l.org


text:
Q: What's the best practice for manually installing groovy on Ubuntu Lucid? What is the best practice if I wanted to download the latest binaries from Groovy website and install?

*

*Which location to copy it to? (/usr/share/groovy?)

*How add groovy to the PATH variable? (needs to be available for groovy shell scripts in cron jobs, so adding to .bashrc or .profile is not preferred)

A: Putting it in /usr/share/groovy and then create symlinks in /usr/bin to the groovy bins should be a good way of installing it.
If you want groovy-1.7.8, there is a debian package that probably works with ubuntu 10.04
http://groovy.codehaus.org/Download


text:
Q: ¿Existe actualmente alguna API para verificar existencia de RFCs en el SAT? Pues lo que dice la pregunta, yo actualmente estoy trabajando en una aplicación web empresarial, en la cual requerimos validar que el cliente tenga un RFC actual y que este valido o registrado en SAT.
Sé que hay validadores de CFDI pero no he encontrado alguna API de validación de existencia de RFCs.
¿Saben ustedes de alguna?.


text:
Q: my ajax call is returning html with json data I am having a weird problem, I am trying to populate the datatable using ajax call to my php program which internally gets data from database.
php:
<?php
require_once('config.php');
$query = mysql_query("select * from productdetails");
while($fetch = mysql_fetch_array($query))
{
        $output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output, JSON_FORCE_OBJECT);
?>

Html(ajax call):
$.ajax({
            url: 'process.php?method=fetchdata',
            data: "json",
            success: function(s){
            console.log($(s).text());
                    oTable.fnClearTable();
                        for(var i = 0; i < s.length; i++) {
                         oTable.fnAddData([
                                    s[i][0],
                                    s[i][1],
                                    s[i][2],
                                    s[i][3],
                                    s[i][4],
                                    s[i][5]
                                           ]);
                                        } // End For

            },
            error: function(e){
               console.log(e.responseText);
            }
            });

This generates the output as

  ( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\datatableone\process.php on line 2
  Call Stack
  #TimeMemoryFunctionLocation
  10.0010242552{main}(  )..\process.php:0
  20.0010242840http://www.php.net/function.mysql-connect' target='_new'>mysql_connect
  (  )..\process.php:2

  {"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}

But my required output should be: (only json)

{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas
  Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}

any suggestions please.
Thanks
Sai
Solution:
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";

try {
        $conn = new PDO("mysql:host=$servername;dbname=holt", $username, $password);
        $statement=$conn->prepare("SELECT * FROM productdetails");
        $statement->execute();
        $results=$statement->fetchAll(PDO::FETCH_ASSOC);
        $json=json_encode($results);
        echo $json;
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
?>

Thanks for suggestions.

A: As noted in the comments, you should turn off warnings, or better yet, write your code in a manner that doesn't produce warnings.
On turning off warnings:
Turn off warnings and errors on php/mysql
You can suppress errors inline with the @ symbol, which is the error control operator in php. Putting @ at the beginning of your mysql_connect() line should get rid of it, but you should switch to PDO!
On PDO (which I recommend and use):
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PDO protects you against SQL injection and allows queries to be sent to the database and constructed beforehand, and you send the inputs afterwards via "placeholders".


text:
Q: SNMP Walk vs MIB OID Listing (There is a question at the end of this story, stay with me!)
After much research I believe I've begun to understand the basics of SNMP. I always knew that an SNMP management system would consume data from a device (a potentially send data to devices too), but I had trouble understanding how to configure that setup.
I'm now using an SNMP management system, so it was time to figure it out. So I've delved into understanding MIBs and OIDs. As I see it, a vendor will put out an MIB for their product, which should contain product specific OIDs. The MIB is like a catalog of things that can be queried from the device, and the OIDs are the specific items that can be queried. (Please correct me if I'm misunderstanding.)
For instance, SonicWall may provide an MIB for a particular firmware for one of their Firwewalls. So if I wanted to monitor Max Connections available for that firewall, I would download the MIB from mysonicwall.com, import the MIB into an MIB Browser and look for an appropriate OID that corresponds to Max Connections. Then I can input that OID into my SNMP management system to monitor that metric.
All of this makes sense to me, hopefully I'm understanding it correctly. I find the process to be fairly clunky, especially when self describing API's exist nowadays, but hey SNMP was created in the 80s so I guess we work with what we have.
But where this understanding breaks down for me is when I perform and SNMP walk on my SonicWall. Doing the walk produces over 500 OIDs that are returned. But when I examine the MIB provided from SonicWall it only has a fraction of those OIDs listed. Is that because most of the OIDs discovered via the walk are not SonicWall specific, but rather generic industry standard OIDs?
Also, is there a decent way to get a report of ALL the data (be it sonicwall specific or industry standard) that my SonicWall can provide via SNMP? Like some tool I could punch in the data from the SNMP walk into and it can return what they all mean?
Also, if I have any holes in my understanding of SNMP, MIBs, and OIDs, I would welcome the feedback. Thanks!!!!

A: Okay, so here's what my SNMP research has turned up. I can't verify this is all 100% accurate, but I feel that I have a much better grasp on SNMP in general and hopefully this information will help someone who is just getting started.
First, SNMP seems to me to be a messy system. It was developed in the late 80s and there's just not a good alternative so I guess we work with what we've got.
SNMP is made up of 3 pieces: an SNMP management system, at least 1 network device, and a software agent on those network devices. For example, you might use Naigos or MaxFocus as an SNMP management system to query devices on your network like printers, switches, routers, etc. Those devices are all running little software components that were made by their manufacturers. Those software components basically produce a bunch of SNMP data based on how the device is functioning. For instance, a printer may produce data on it's toner levels, or a router might produce data on how many concurrent connections it currently is supporting. The SNMP management system can then query these devices for this info.
But how is it actually done? Well, some standards organizations put together MIBs back in the 80s to help with this. A MIB is basically a large data tree of SNMP attributes that can be queried. These standard MIBs cover a large amount of query-able attributes - from toner to network settings - but as you can imagine as new devices and technology has emerged they don't cover everything. So Manufacturers have produced product specific MIBs that help fill these gaps.
MIBs sound pretty great, but the reality is they seem to often be difficult to understand, and poorly written. Sometimes they are not written to proper spec so it becomes difficult to utilize them. That said, the general process for making use of a MIB to find out what items you can query on your device of choice (router, printer, etc) is this:

*

*Get yourself a free MIB Browser software. They are all crappy, but I find that NetTools Pro by Axence or the MIB Browser from ManageEngine are the least crappy.

*Most MIB browsers come with the "default" MIB files preloaded. But if you want to know what vendor specific items you can query on your devices you'll have to download a custom MIB file from your vendor. (Sonicwall, HP, etc) If your vendor does not offer MIB files, there are some online resources that host a bunch of MIB files. I think there's one called MIB Depot or something...

*Once you get your custom vendor specific MIB file downloaded, import it into your MIB browser.

*Now we perform what is called a "walk" against your SNMP device. To do this, you'll need to punch in the devices IP address, and it's community string. (The community string is really just a password or shared secret used for authentication. Why the creators of SNMP decided they needed to be different and call it a community string is beyond me...) I should also mention that the device you are querying needs to be set up to allow SNMP queries. This is usually done through the devices web interface, which is also typically where you set the community string.

*Once you get your MIB browser connected to your device then perform the "walk" function. Every MIB browser works a bit differently, so you'll need to play around a bit to see how it's walk function works. But in general it should return a list of OIDs from your device. These IDs correspond to an entry in the MIB files. Usually you can double click or highlight one of these OIDs and it will find the corresponding MIB item that will tell you what that OID is used for, e.g. toner levels, OS version, network connections, etc. Then you can punch in the OID number into your SNMP management system and begin monitoring that attribute!

So after all my research I find that SNMP appears to me at least to be a very flawed and cumbersome system. But from what I've read it seems that at the very least, once you get it configured it tends to be reliable and speedy. I hope this information helps someone else who is just delving into the world of SNMP! Here's a further reference that I found helpful:
http://www.allthingsmax.com/2014/02/take-snmp-walk-creating-new-snmp-checks.html
UPDATE: I will add another tip here. When walking a devices OID values there are two different types of values you can possibly retrieve: scalar and tabular.
Tabular is used for devices that need to provide the same type of value for several components. For instance a router may have 9 ports on it. Each port has a different physical address or MAC address. this is represented by a table in a MIB.
Scalar is used for values that don't require a tabular layout.
THE IMPORTANT PART: Scalar values are always appended with a .0 and tabular values are appended with a number representing a specific device value. For instance on a router port 1 would likely be appended with .1, port 2 with .2, and so on. Then when you enter the OID into your SNMP management system, you need to make sure to include this last numeric character. For instance, ifPhysAddress = .1.3.6.1.2.1.2.2.1.6, but without appending a tabular value it will do you no good. This is similar for scalar values which will always need a .0 appended. A decent MIB browser should show you these append values when walking the device. ManageEngine's MIB browser does a good job of this. It format's it like so:
--Scalar values:
sysUpTime.0
sysContact.0
sysName.0
--Tabular values:
ifPhysAddress.1
ifPhysAddress.2
ifPhysAddress.3
...


text:
Q: C# string array buffer I am building an application for my brother that takes string input form an external source, GPS plotter, which I would like to display in a multiline textbox. If someone were to leave this application running for an extended period I don't want the TextBox.MaxLength to be exceeded or memory allocation to become excessive.
I can't think of a good way to implement this. I need to display the last n rows in a textbox.

Edit: The marked solution is correct. Thanks Jon. I ended up making it generic. Below is what I used.
public class ArrayBuffer<T>
{
    private readonly int _maxLines;
    private int _writePosition;

    private readonly T[] _buffer;

    public ArrayBuffer(int maxLines = 100)
    {
        _maxLines = maxLines;
        _buffer = new T[_maxLines];
    }

    public T[] Push(T value)
    {
        _buffer[_writePosition++] = value;
        _writePosition %= _maxLines;
        return _buffer.Skip(_writePosition)
                             .Concat(_buffer.Take(_writePosition))
                             .Where(line => line != null).ToArray();
    }
}

Usage:
var myArrayBuffer = new ArrayBuffer<string>(50);
string[] bufferedStringArray = myArrayBuffer.Push("some string");

A: Assuming that an acceptable solution would be to display no more than the last N lines of output each time, you could keep a circular buffer of the last N lines of input. Whenever input arrives, the oldest lines in the buffer get deleted to make room for the new arrivals.
The parts that implement the buffer:
const int MAX_LINES = 10;
int writePosition = 0;
readonly string[] buffer = new string[MAX_LINES];

When new input arrives:
// input is an IEnumerable<string>
foreach (var line in input)
{
    buffer[writePosition++] = line;
    writePosition %= MAX_LINES;
}

When you want to display output:
var linesInDisplayOrder =  buffer.Skip(writePosition)
                                 .Concat(buffer.Take(writePosition))
                                 .Where(line => line != null);
var outputText = String.Join("\n", linesInDisplayOrder);


text:
Q: Benefits of using Join-Path over string concatenation What is the benefit of using Join-Path to create a file path instead of just doing something like the following?
$Folder\$FileName

A: Join-Path benefits:

*

*Uses the path-separator defined for the provider on which it's running

*Supports more than just filesystems (Certificates, registry, etc)

*Accepts multiple items to join.

*Accepts credentials

*Can resolve the result to a full path if it's relative

*Accepts arguments from the pipeline without a Foreach-Object intermediary


text:
Q: How to include .js files using angular.js I need to include javascript files dynamically using angular.js. Suppose i have the below project html view structure.
1-index.html.

     a)hod.html-hodcontroller.js
         i)home.html.-homecontroller.js
         ii)about.html.-aboutcontroller.js

     b)Princpal.html-princpalcontroller.js

         i)home.html-homecontroller.js
          ii)about.html -aboutcontroller.js

Let me to explain the above structure.I have one master page(i.e-index.html). hod.html and Princpal.html are the partial view to index.html page. Each home.html and about.html are the again partial view to hod.htmland Princpal.html so finally these are nested view.Here i am including all js files at a time in index.html page But here i need when any partial view will attach in index page only the that related .js files will attach in the index page not the all page.So please help me to do this using angular.js.

A: What you are trying to do is not the best way to create an angular app.
Usually you want all the code to be in one js file.
Of course when you develop they will be different files, so you should use
a task runner like Grunt or Gulp to do that for you.
I suggest that you use a Yeomen generator
with an angular generator
It will setup a working angular app for you with Grunt and other interesting stuff.


text:
Q: Unable to start a command line with spaces from C# The command line I need to execute is
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\devenv.exe" /Run "C:\unity\unity\MRTK Tutorial\Builds\MRTK Tutorial.sln"
This works from a windows command line without issues,
I formatted it into a string for visual studio
When running from C# this command never executes and the contents of result are ""
            System.Diagnostics.ProcessStartInfo procStartInfo =  new System.Diagnostics.ProcessStartInfo("C:\\Program Files(x86)\\Microsoft Visual Studio\\2019\\Enterprise\\Common7\\IDE\\devenv.exe", " /Run \"C:\\unity\\unity\\MRTK Tutorial\\Builds\\MRTK Tutorial.sln\"");

            // The following commands are needed to redirect the standard output.
            // This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput = true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();

A: You can try the following code to use c# to execute devenv.exe.
        var devEnvPath = @"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\devenv.exe";
        string SolutionFile = @"D:\Test\testconsole\testconsole.sln";
        ProcessStartInfo startInfo = new ProcessStartInfo(devEnvPath);
        startInfo.Arguments = "/Run " + SolutionFile;
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
        process.WaitForExit();
        Console.ReadKey();

Based on my test, the above code will open vs2019 and open the startup project.


text:
Q: Else if statment not working I've been having a tough time with this code I've been working with.
For context, I'm programming a simplistic Tumblr page (not my blog theme, just a page) in which the music, background, and gif will change depending on the time of day. After much frustration and trial and error, I've gotten most things to work—except one thing.
I want to have three times of day (day, sunset, night) however, I can only achieve day and night, for whenever I try to include "else if" it doesn't work. Here's my current code that does work, but only has two times of day out of three (night/sunset):

var currentTime = new Date().getHours();
if (19 <= currentTime && currentTime < 6) {
    if (document.body) {
        document.body.background = "(night bg)";
        var url = "(night gif)";
        var img = new Image();
        img.src = url;
        document.body.appendChild(img);
        var source = "(night music)";
        var audio = new Audio();
        audio.addEventListener("load", function() {
        audio.play();
        }, true);
        audio.src = source;
        audio.autoplay = true;
        audio.loop = true;
    }
}

else {
    if (document.body) {
        document.body.background = "(sunset bg)";
        var url = "(sunset gif)";
        var img = new Image();
        img.src = url;
        document.body.appendChild(img);
        var source = "(day music)";
        var audio = new Audio();
        audio.addEventListener("load", function() {
        audio.play();
        }, true);
        audio.src = source;
        audio.autoplay = true;
        audio.loop = true;

    }
}

I've attempted to change
else {
    if (document.body) {
        document.body.background = "(day bg)";

into saying "else if" instead of just "else" on the top, and also adding a time, like so:
 else if (16 <= currentTime && currentTime < 19) {
    if (document.body) {
        document.body.background = "(day bg)";

when that didn't work I've tried multiple things, like doing away with the "if" or making both the "if" and "else" into "else if" but I've gotten nothing to work. I've also tried to make a third block that was just "else" with the rest of the coding, but that didn't work either. Does anybody know a solution and/or what I'm doing wrong?

A:
I think you have to change your code.
if (19 <= currentTime && currentTime < 6) is incorrect.
Because it means 19<= X < 6. It's impossible.
So you should change if (19 <= currentTime || currentTime < 6)

var currentTime = new Date().getHours();
if (19 <= currentTime || currentTime < 6) {
    if (document.body) {
        document.body.background = "(night bg)";
        var url = "(night gif)";
        var img = new Image();
        img.src = url;
        document.body.appendChild(img);
        var source = "(night music)";
        var audio = new Audio();
        audio.addEventListener("load", function() {
        audio.play();
        }, true);
        audio.src = source;
        audio.autoplay = true;
        audio.loop = true;
    }
}
else if(16 <= currentTime && currentTime < 19){
  /* programming Here */
}
else {
    if (document.body) {
        document.body.background = "(sunset bg)";
        var url = "(sunset gif)";
        var img = new Image();
        img.src = url;
        document.body.appendChild(img);
        var source = "(day music)";
        var audio = new Audio();
        audio.addEventListener("load", function() {
        audio.play();
        }, true);
        audio.src = source;
        audio.autoplay = true;
        audio.loop = true;

    }
}

A: I think your solution can be improved. If you look at your code, you see that there are a lot of repetition for each event.
If you want to add another event, there is even more code to add.
I suggest that you make a schedule in an array instead. That makes it much more easy to add new events.
// Define the schedule. start= start hour, end = end hour.
// With start=6 and end=19, the schedule will be used between
// 06:00 - 18:59.
// The schedules will be searched in order, and the first matching
// schedule will be used. Therefore the default schedule (night) must
// be last in the list.
var schedule = [
  { start : 6, end:19, bbg:"(sunset bg)", img:"(sunset gif)", music:"(sunset music)" },

  // Default schedule, must be last in list.
  { start : 0, end:24, bbg:"(night bg)", img:"(night gif)", music:"(night music)" }
];

var currentHour = new Date().getHours();
var currentSchedue;

// Loop though schedules
for (var idx=0; idx < schedule.length; idx+=1) {
  currentSchedule = schedule[idx];

  // Find first matching schedule
  if (currentSchedule.start <= currentHour && currentSchedule.end > currentHour) {
    document.body.background =  currentSchedule.bbg;

    var img = new Image();
    img.src = currentSchedule.img;
    document.body.appendChild(img);

    var audio = new Auido();
    audio.src = currentSchedule.music;
    audio.autoplay = true;
    audio.loop = true;

    break; // stop loop if matching schedule was found
  }
}

If you still want to use if-statements, here is a working example:
if ( 6 <= currentHour && currentHour < 16 ) {
  // Daytime, valid from 06:00 - 15:59
  console.log('Day', currentHour);
}
else if ( 16 <= currentHour && currentHour < 19 ) {
  // Evening  valid from 16:00 - 18:59
  console.log('Evening', currentHour);
}
else {
  // Night, valid 00:00 - 05:59 and 19:00 - 24:00
  console.log('Night', currentHour);
}

Logic error in your if-statement:
if (19 <= currentTime && currentTime < 6) {
}

*

*19 <= currentTime is only true if currentTime is 19 or higher

*currentTime < 6 is only true if currentTime is less than 6.

They can't be true at the same time.

A: var currentTime = new Date().getHours();
if (currentTime > 19 && currentTime < 6) {
  // Night
} else if (currentTime > 6 && currentTime < 17) {
  // Day
} else {
  // Sunset
}

For details see here


text:
Q: Need a backuper tool I'm a network admin, and I have to setup a backup process for 7 dirs, the dirs are on a windows remote folder about 2GB each with subdirs and files. I need backup a dir each day from 6pm.
Is there a freeware up that get this done for me?
What can you recommend?
Note:
Backup to a centralized windows 2003 server, all other matchines are windows 2003 servers, and are in the same LAN.

A: Have you tried Areca? Not sure if it works on the network, but for workstations it's a breeze!

A: I personally use http://backup.comodo.com/ for home and the office.
I have used http://mozy.com as well in the past and had no issues.
Mozy is a pay service, Comodo has a tool that allows you to back up on a schedule very easily to anywhere.
If you are on a windows network you could use DFS to sync between a couple of disks as a Pseudo backup.

A: JungleDisk with an Amazon S3 account is pretty reliable and while not free, is relatively inexpensive.  Looks like it'd be around $5 US for what you have.

A: For backing up Windows PCs over the network, I use BackupPC running on a Linux server. Works great with cwRsync running on the Windows PC for access.

A: I currently started testing ntbackup, comes with WinXP.


text:
Q: SSIS: Pass connection string as an argument in an Execute Process task? I use a dtsConfig file that holds the actual connections.
I am working with the Execute Process task and the executable that the task calls needs 2 of the connection strings from the dtsConfig file.  Is there a way for me to pass these connection string values as an argument in the task?
I have not found a way to do this so inside the executable I load the dtsConfig file as an XmlDocument and look for the connections that I need.
Is there any other way?
Oh, I cannot use a Script task/component as this has to run on both SQL 2008R2 and SQL 2012.  SQL 2012 can't upgrade packages with Script components during execution.
Thanks.

A: I would change the dtsConfig definition to set the Connection String in a Variable.
Within each package you can use that variable as an Expression to override the ConnectionString property of the Data Connection.
You can pass variables to sub-packages or processes.


text:
Q: How to identify invalid parameter error in PDOStatement::execute() I know that there are some general answers available at stack (I have read them) but I am failed to understand what I am doing wrong in below code snippet. I have logged all the variable values and they are correct but I am still getting error. I am watching this code from last couple of hours but failed. Code snippet is:
   global $connPDO;
    $userId = $_COOKIE["userID"];
    $currentDateTime = date("Y-m-d H:i:s");

    $sql  = "UPDATE project_progress SET
                      project_part_no             = :project_part_no           ,
                      progress_description        = :progress_description      ,
                      progress_update_datetime    = :progress_update_datetime  ,
                      cad                         = :cad                       ,
                      blds                        = :blds                      ,
                      p_floor                     = :p_floor                   ,
                      f_floor                     = :f_floor                   ,
                      bridges                     = :bridges                   ,
                      tracks                      = :tracks                    ,
                      p_veg                       = :p_veg                     ,
                      f_veg                       = :f_veg                     ,
                      obj_model                   = :obj_model                 ,
                      obj_place                   = :obj_place                 ,
                      spw                         = :spw                       ,
                      fence                       = :fence                     ,
                      ola                         = :ola                       ,
                      qa                          = :qa                        ,
                      progress_update_by_id       = :progress_update_by_id
            WHERE project_progress_id             = :project_progress_id        ";

    $queryInsert = $connPDO->prepare($sql);

    $binds = array(
        ':project_progress_id'                   =>      $_POST["recordId"],
        ':project_part_no'                       =>      $_POST["projectPartNo"],
        ':progress_description'                  =>      $_POST["progressDesc"],
        ':progress_update_datetime'              =>      $currentDateTime,
        ':cad'                                   =>      $_POST["cad"],
        ':blds'                                  =>      $_POST["blds"],
        ':p_floor'                               =>      $_POST["pFloor"],
        ':f_floor'                               =>      $_POST["fFloor"],
        ':bridges'                               =>      $_POST["bridges"],
        ':tracks'                                =>      $_POST["tracks"],
        ':p_veg'                                 =>      $_POST["pVeg"],
        ':f_veg'                                 =>      $_POST["fVeg"],
        ':obj_model'                             =>      $_POST["objModel"],
        ':obj_place'                             =>      $_POST["objPlace"],
        ':spw'                                   =>      $_POST["spw"],
        ':fence'                                 =>      $_POST["fence"],
        ':ola'                                   =>      $_POST["ola"],
        ':qa'                                    =>      $_POST["qa"],
        ':progress_update_by_id   '              =>      $userId
    );

    //echo $binds;
    $querySuccess = $queryInsert->execute($binds);

    echo $querySuccess;

And The error is:

( ! ) Warning: PDOStatement::execute() [<a href='pdostatement.execute'>pdostatement.execute</a>]: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in D:\wamp\www\Employee_Switch_Persons\Employee_Switch_Person.php on line 925

Call Stack

#	Time	Memory	Function	Location

1	0.0212	2816136	{main}(  )	..\Employee_Switch_Person.php:0

2	0.0248	2836384	ProjectProgressAndCommentSave(  )	..\Employee_Switch_Person.php:39

3	0.0249	2843376	PDOStatement->execute(  )	..\Employee_Switch_Person.php:925

A: The key of the last parameter in $binds ...
':progress_update_by_id   '

has some extra spaces at the end.  Remove these spaces ...
':progress_update_by_id'


text:
Q: OpenIddict: Share authentication between ASP.NET Core application and WEB.API Application I have an asp.net core web application that using OpenIddict. It works fine and users can login.
Now I want to add web.api hosted on separate subdomain, but because the user is already authenticated I want to somehow share that authentication.
Is it possible? How can I do it? I see in the examples for OpenIddict user have to authenticate again, but I do not want that.
My Setup:

*

*ASP.NET Core Web App: app.domain.com

*OpenIddict server: login.domain.com

*Web API .net Core App: api.domain.com (that is new requirement)

My web application has views that display data from controllers, I want to add extra javascript logic, and I can have web.api as part of the asp.net core domain: app.domain.com/api/
in that case, it works, the authenticated shared between web application and API,
but my goal is to have web.api on a separate subdomain: api.domain.com
I know I have to create a Bearer token, but it is not clear how to do it without authenticating the user again. So I want somehow share ASP.NET Core web application authentication to access api.domain.com
Can you please point me in the right direction? Where to start looking?


text:
Q: D3 filled gauge - is it possible to dynamically update the color of the filing circle through d3 itself? Is it possible to dynamically update the color of the filing circle?

A: Not only possible, but fun for all the family..
I have a function to set the colors eg:
function getColor(num){
    if( num >= 9 ){
            return '#E72530';
    } else if( num >= 7 ){
            return '#EAAB0E';
    } else if( num >= 5){
            return '#FFE400';
    } else if( num >= 3 ){
            return '#187AD3';
    } else {
            return '#00ADGE';
    }
}

So, from there I have my gauge(s) which call the getColor function with a number from the returned data from getData. The getData url calls an API which returns json data. Based on this level, will change the color
function loadStuff(){
    $.getJSON('/getData', function(d) {
            var ccolor = getColor(d.level);
            var config1 = liquidFillGaugeDefaultSettings();
            config1.circleColor = ccolor;
            config1.textColor = "#ffffff";
            config1.waveTextColor = "#ffffff";
            config1.waveColor = ccolor;
            config1.circleThickness = 0.2;
            config1.textVertPosition = 0.2;
            config1.waveAnimateTime = 1000;
            config1.displayPercent = false;
            var gauge1 = loadLiquidFillGauge("fillgauge1", d.level*10, config1);
    });

By now you have noticed this will only work when the page is loaded. I can you thinking "what a shame", but help is at hand.
You can call the loadStuff function when the page is loaded, and then set a timer to do it at whatever interval you like.
window.onload = function () {
    //Make sure the function fire as soon as the page is loaded
    loadStuff();

    // run the function every 60 seconds
    setInterval(function() {
            loadStuff();
    }, 60 * 1000); // 60 * 1000 milsec
}


text:
Q: using git post-receive for overwriting files in multiple directories I'm using git to deploy changes to the files on my server, but the files live in two directories (/var/www and /user/myfiles) but I want to just use one repo to push the changes. So I've set up a repo (/user/gitrepo) and I think, after looking around for solutions, the best approach is to use post-receive to overwrite the files in the other directories, but I don't know how to use the hook post-receive to do what I want (I'm a git noob). Can any one help?
To be clear I have files in user/gitrepo/www/file1 and user/gitrepo/myfiles/file2
I want to push changes to the repo and have var/www/file1 and user/myfiles/file2 be updated.
Thanks!
(also if you have something you think should work better and also uses git, could you give me a detailed how-to?).

A: I think you are looking for an introduction to git hooks.
Try:

*

*http://git-scm.com/book/en/Customizing-Git-Git-Hooks

*http://ryanflorence.com/deploying-websites-with-a-tiny-git-hook/

*http://google.com/?q=git+post-receive+hook+example

A: If your remote server is linux (which it likely is) you can use any terminal commands within your remote server.
Say for example you wish to delete a file you can use the command
rm file2
You can chain as many commands in the hook as you like.
To copy the contents of one folder to another you could use: cp Folder1/* Folder2/


text:
Q: Nginx Drupal Redirect Loop In the root of my SSL directory I have 2 separate Drupal 7 installations on the same domain name, one linked to www.eastercamp.org.nz/southern/ and one at www.eastercamp.org.nz/central/, previously running apache this all worked fine.
However now that I've moved over to Nginx (I'm still quite new to it), on my current server block config (linked below) accessing either of the above URL's ends in a redirect loop and I can't figure out why.
How do I get this working?
My Nginx server-block config file: http://paste.ubuntu.com/6761774/

A: I think your issue is that the URI /central and /southern are sent to your drupal installation, so the framework is looking for routes that match that, when it's not found it returns a 404 error not a redirect loop.
You need to rewrite the request uri in those paths, try adding this location block and tell me if it works
location /(southern|central)(?<myuri>.*) {
  rewrite ^ $myuri last;
}

I also think your @rewrite location should be modified, but we'll see if this works first or not.


text:
Q: Why does Laravel's Response::json return blank if called from another function? I'm building an API using Laravel. I'd like to pass data to a function in the base controller and have the JSON served out via Response::json() from there (the reason for this is so that the response method carries out benchmarking and logging, among other things)
This works:
<?php

public function show($id)
{
    $data = Member::find($id);

    return Response::json($data);
}

This doesn't:
<?php

public function show($id)
{
    $data = Member::find($id);

    $this->respond($data);
}

private function respond($data)
{
    return Response::json($data);
}

Can anyone tell me why Response:json() doesn't like being popped into another function?
If I echo Response::json($data) instead of return it outputs the full response, including the headers.
All input appreciated. Thanks.

A: As cecilozaur commented, perhaps you need to:
return $this->respond($data);

So that the response actually gets returned to the parent function.


text:
Q: Using non-numerical identifier in Rails find function In many Rails examples I see
ModelName.find(:id) being used, supposed every model has a unique string attribute named :symbol, how can I set up the model so that find(:symbol) would work? Do I have to implement the searching algo myself?

A: You could use
 ModelName.find_by_symbol("uniquestring")

More info on Rails Dynamic Finders

A: You might want to try "find_by_yoursymbol"
ModelName.find_by_yoursymbol("symbol value")

I just used this to check if a record exists and to create it if it isn't there.
Spree::MailMethod.create(:environment => "test") unless Spree::MailMethod.find_by_environment("test").present?


text:
Q: how can I read each filed of json I am posting to API and get a response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var jsonResponse = JsonConvert.SerializeObject(responseString , Formatting.Indented);

and this is the value of jsonResponse :
"{\"Id\":333,
  \"Name\":\"TestProduct\",
  \"ApplicationId\":\"9edcc30d-7852-4c95-a6b2-1bf370655965\",
  \"Features\":[{
         \"Id\":301,
         \"Name\":\"Sodalis Mobile Client2.0\",
         \"Code\":\"Beeware.Sodalis.Mobile\",
         \"ProductId\":0,
         \"Selected\":null}]
}"

how can I read each filed ?
like Name , ApplicationId , Features-Name and Features-Code.
I would appreciate any help.

A: You have to create a class like
public class Feature
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("Code")]
    public string Code { get; set; }

    [JsonProperty("ProductId")]
    public int ProductId { get; set; }

    [JsonProperty("Selected")]
    public object Selected { get; set; }
}

public class YourApp
{
    [JsonProperty("Id")]
    public int Id { get; set; }

    [JsonProperty("Name")]
    public string Name { get; set; }

    [JsonProperty("ApplicationId")]
    public string ApplicationId { get; set; }

    [JsonProperty("Features")]
    public IList<Feature> Features { get; set; }
}

then to Deserialize it just do
YourApp p = JsonConvert.DeserializeObject<YourApp>(json);
Console.WriteLine(p.Name + p.ApplicationId);

You can read all the features by using a foreach since now all the feautures are there in your object
foreach(Feature AllFeatures in p.Features)
{
    Console.WriteLine(AllFeatures.Name + AllFeatures.Code);
}

A: First of all, create classes which will hold your response:
public class MyResponse {
    public int Id {get; set;}
    public string Name {get; set;}
    public string ApplicationID {get; set;}
    public IList<MyFeature> Features {get; set;}
}

public class MyFeature {
    public int Id {get; set;}
    public string Name {get; set;}
    public int ProductId {get; set;}
    public string Selected {get; set;}

}

Then you can use JsonConvert:
MyResponse response = JsonConvert.DeserializeObject<MyResponse>(responseString);
string name = response.Name;

A: Try this classes
public class MyResponse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ApplicationID { get; set; }
    public List<MyFeature> Features { get; set; }
}

public class MyFeature
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string Code { get; set; }
    public int ProductId { get; set; }

    public bool? Selected { get; set; }

}

then you can read json by this
string _Json = @"{'Id':333,'Name':'TestProduct','ApplicationId':'9edcc30d-7852-4c95-a6b2-1bf370655965','Features':[{'Id':301,'Name':'Sodalis Mobile Client2.0','Code':'Beeware.Sodalis.Mobile','ProductId':0,'Selected':null}]}";
MyResponse M = JsonConvert.DeserializeObject<MyResponse>(_Json);


text:
Q: optimizing two variable function. I want to optimize the following objective function subjected to the constraint as given below:
$$ min \hspace{2mm} ||x||_1+j$$
$$s.t. \hspace{2mm} ||Ax-\frac{1}{j}(b_1+b_2+\ldots +b_k)||_2 \leq \epsilon \\
1\leq j \leq k\\$$
$\text{where}, \\
A=m \times n \hspace{2mm} \text{matrix and is known.}\\
x=n \times 1 \hspace{2mm} \text{vector}\\
b_i, i=1,2, \ldots k \hspace{2mm} \hspace{2mm} \text{all} \hspace{2mm} m \times 1 \hspace{2mm} \text{vector and are known.}\\
j=\text{total numbers of $b_i$}$
where, the $k$ is fixed integer value and $j$ is in between $1$ and $k$. Can anyone please suggest me how can I proceed this further. I want average of $j$ $b_i'\text{s}, i=1,2 \ldots k$ and $x$ which minimizes the given objective function. Any general method to solve the given optimization problem?

A: For each fixed $j$, this is a straight forward problem that can be solved by iterative soft threshholding (ISTA), FISTA, ADMM, IRLS, etc.
Unless the $b_{i}$ vectors have some special property that you haven't told us about, there's no reason to believe that you do better than solving the problem for $j=1$, $2$, $\ldots$, $k$ and then pick the best objective value you found.


text:
Q: How do I insert images like this website in my website? I'm trying to replicate the functionality of this website: http://8tracks.com/pitchfork/the-year-in-music-2012-the-top-100-tracks-of-2012 but I'm not sure how I'd go about displaying images on the website like they do. How would I display images as links like this website does? More specifically, how could I display different links each time the webpage is refreshed?
Sorry if I'm being vague, I'd more or less just like to know where to start.
Thanks

A:
How would I display images as links like this website does?

Images as links are just links containing images:

More specifically, how could I display different links each time the webpage is refreshed?

Generate the HTML from a server side program (written in your programming language of choice). Have it select images at random. You could track them in a database and then use something like this to pick one (or more).


text:
Q: Using flickr api in custom wordpress plugin I'm currently trying to add flickr api to my custom wordpress plugin... and am failing. :( I was trying to use this tutorial, Getting Started With Flickr API, to learn the basic code structure and then I was going to refer to flickr's app garden for documentation to do what I'm wanting; but, it's not working.
What I have... I built a new PHP file and named it "class.flickr.php" and added the code listed in the tutorial...
<?php

    class Flickr{

    private $flickr_key;
    private $flickr_secret;
    private $format = 'json';

    // Setting up flickr_key and flickr_secret
    public function __construct( $flickr_key ) {

        $this->api_key_shown_here = $flickr_key;
    }

    public function searchPhotos( $query = '', $tags = '' ){ // Begin searchPhotos

        $urlencoded_tags = array();

        if ( !empty( $args )) {

            $tags_r = explode( ',', $tags );
            foreach ( $tags_r as $tag ) {

                $urlencoded_tags[] = urlencode( $tag );
            }
        }

        // Construct the url
        $url  = 'http://api.flickr.com/services/rest/?';
        $url .= 'method=flickr.photos.search';
        $url .= '&text=' . urlencode( $query );
        $url .= '&tags=' . implode( ',', $urlencoded_tags );
        $url .= '&sort=relevance';
        $url .= '&safe_search=1';
        $url .= '&content_type=4';
        $url .= '&api_key=' . $this->flickr_key;
        $url .= '&format' . $this->format;
        $url .= '&per_page=10';

        // Get search results
        $result = file_get_contents( $url );

        // Remove the unneccessary strings that wraps the result returned from the API
        $json = substr( $result, strlen( "jsonFlickrApi("), strlen( $result ) - strlen( "jsonFlickrApi(") - 1 );

        $photos = array();
        $data = json_decode( $json, true );

        // Check if the status didn't fail
        if ( $data['stat'] != 'fail' ) {

            // Return only the data for the photos as that's the only thing that we need
            $photos = $data['photos']['photo'];
            return $photos;
        } else {

            return false;
        }
    } // end searchPhotos

}

and then tried calling the above method in my page template (which is in the same folder as "class.flickr.php"), using the following code...
<?php // Flickr search photos test

require_once( 'class.flickr.php' );

$flickr = new Flickr( $flickr_key );

$results = $flickr->searchPhotos( $query, $tags );
if ( !empty( $results )) {

    foreach( $results as $photo ) {

        $src = "http://farm" . $photo['farm'] . ".static.flickr.com/" . $photo['server'] . '/' . $photo['id'] . '_' . $photo['secret'] . '_m.jpg';
        ?>

        <img  src="<?php echo $src; ?>" alt="<?php echo $photo['title']; ?>" />

    <?php }
}

But, alas, all I'm getting is a blank screen. Any help would be appreciated. ;)

A: I see two issues right off the bat that are going to cause problems:
$this->myApiKey = $flickr_key;
$thix->myApiSecret = $flickr_secret;

*

*myApiKey and myApiSecret aren't in your code anywhere, so setting them here isn't doing anything. They should be $this->flickr_key and $this->flickr_secret.

*You have a typo in the 2nd line above. Change $thix to $this and give it a go.


text:
Q: app.js:1 Uncaught ReferenceError: angular is not defined at app.js:1 This is index.html
<!DOCTYPE html>
<html lang="en" ng-app="quizApp">
  <head>
    <meta charset="UTF-8">
    <title>Angular JS Quiz App</title>
    <link rel="stylesheet" href="src/style.css">
  </head>
  <body ng-controller="quizController">
           {{message}}
        <script src="src/libs.js"></script>
        <script src="src/scripts.js"></script>
        <script src="app.js"></script>
  </body>
</html>

This is app.js
var quizApp = angular.module('quizApp',[]);

when i console  i m getting error as

app.js:1 Uncaught ReferenceError: angular is not defined   at app.js:1

A: Depending on what you have in src/libs.js I don't think you are importing the Angular code at all;
Add this line to your <head> element:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>

You can see the beginners examples on the angularjs website:
https://angularjs.org/

A: You forgot to load angular.min.js/ angular.js before writing angular.module('quizApp',[]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script>

Just load .js file and your error will be removed.


text:
Q: Custom views with ADT I've been messing around in the ADT source. There are Layout Rules for all the views that can be dragged over in the graphical editor. These rules appear to allow you to add extra XML attributes automatically (for instance, adding the handler, and content for a SlidingDrawer). Has anyone use these successfully? I tried just using my custom view + Rule, like how the current ones are, but it doesn't work. I also don't see where these Rule files are used.
Basically, I'm trying to create a modified SlidingDrawer. Even just extending SlidingDrawer itself, it seems to lose the XML attributes of it's parent. (So it doesn't show up in the UI screen, and doesn't place the handler, and content views).

A: Ok, the view rules require at least ADT 16.
A few things which are good to know:
1) Make sure the rule is the same name as your custom class, only with Rule at the end (ex MyCustomViewRule).
2) Make sure your view rule is in the same package
3) Make sure you export your view rules to a separate jar
4) Add the jar to your project, but do NOT add it to the build path
5) Add the following line to your project.properties file (note: the location has to be the actual filesystem location)
layoutrules.jars=c:\temp\workspace\test\customviewrules.jar

I believe in r17 they are going to make the filepath relative to the project, or workspace, rather than the actual filesystem location.


text:
Q: Why are my global variables not updating after i call my functions? I created a couple of functions which load a dataset from github and then combines it. This part of the code works correctly. My problem arises when I run the combine function for a second time.
What I tried when testing if my functions work as intended.
loadDataset("https://raw.githubusercontent.com/AAF108/ml/master/test3")
print (dataset)
combine({"data": [{"room_temperature": 20, "light_intensity":
511,"humidity": 50}]})
print(combinedData)

the URL in loadDataset is this:
{"data": [{"room_temperature": 20, "light_intensity": 511,"humidity": 50}]}

When I run this part I get (which is what I expected to get):
   humidity  light_intensity  room_temperature
0        50              511                20

   humidity  light_intensity  room_temperature
0        50              511                20
0        50              511                20

Below is the code for the functions I made:
def loadDataset(url):
    global dataset
    dataset = pd.read_json(url)

def combine(obj):
    global combinedData

    json= obj

    df1 = pd.DataFrame(dataset)
    df2 = pd.DataFrame(json["data"])

    combinedData = pd.concat([df1, df2])

My problem arises when I do this:
loadDataset("https://raw.githubusercontent.com/AAF108/ml/master/test3")
print (dataset)
combine({"data": [{"room_temperature": 20, "light_intensity":
511,"humidity": 50}]})
print(combinedData)
combine({"data": [{"room_temperature": 20, "light_intensity":
511,"humidity": 50}]})
print(combinedData)

What I Expect:
   humidity  light_intensity  room_temperature
0        50              511                20

   humidity  light_intensity  room_temperature
0        50              511                20
0        50              511                20
0        50              511                20

What I get instead:
   humidity  light_intensity  room_temperature
0        50              511                20

   humidity  light_intensity  room_temperature
0        50              511                20
0        50              511                20

I'm not sure why my combineData is not updating.

A: That's not how global works. Rather, it "imports" the name combinedData into your function as a local variable that refers to the globally defined object.
So, therefore, when you run combinedData = pd.concat([df1, df2]), you are assigning the result of pd.concat([df1, df2]) to the local variable combinedData. This change is obviously not visible in the global scope.
You should avoid using global variables in this way, and instead pass objects as arguments.
If you really want to do this, though...you can do something like this (edit: this actually wouldn't work because pd.append doesn't work inplace):
combinedData = pd.DataFrame()

def combine(obj):
    global combinedData

    json = obj

    df1 = pd.DataFrame(dataset)
    df2 = pd.DataFrame(json["data"])

    combinedData.append(pd.concat([df1, df2]))

Thanks to a comment, I did some more testing, and I found the real reason OP's code doesn't work: the runtime environment.
If you run this code as a script, then it does modify the global variable combinedData. However, if you run it in a Jupyter notebook, then it doesn't.


text:
Q: ActionMailer 4.2.6 giving `wrong number of arguments (1 for 0)` on `deliver_later(wait: 1.hour)` I'm trying to send a simple email that needs to be delayed for on hour. Emails overall work well and I can call deliver_now and deliver_later with no problem. However, if I call the same email deliver_later(wait: 1.hour) (as documented here: http://edgeapi.rubyonrails.org/classes/ActionMailer/MessageDelivery.html#method-i-deliver_later) I get the following error:

ArgumentError (wrong number of arguments (1 for 0))

On the same line as deliver_later(wait: 1.hour). The stack trace doesn't show any other lines in my code.
Here's my mailer:
def project_reminder(project_id)
  @project = Project.find project_id
  @user    = @project.user

  mail(to: user_email(@user), subject: "Project Reminder")
end

And the relevant code in my controller:
def remind
  @project = current_user.projects.find(params[:project_id])
  UserMailer.project_reminder(@project.id).deliver_later(wait: 10.minutes)
end

Also, I'm using sidekiq 4.1.0 with redis as my queue adapter.


text:
Q: Laravel Socialite InvalidStateException in AbstractProvider.php line 200 I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting

InvalidStateException in AbstractProvider.php line 200

frequently. i tried

php artisan cache:clear
php artisan config:clear
composer dump-autoload

these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..

A: I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.

A: If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.

A: I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();

it works

A: I have same issue and solved in 3 steps;

*

*add request on the top
use Illuminate\Http\Request;

*Pass request object to function
public function handleProviderCallback(Request $request)
        {
            try {
                $user = Socialite::driver('facebook')->user();
            } catch (Exception $e) {
                throw new Exception;
            }
    }

*Clear cache.
php artisan cache:clear

A: I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"

This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true

in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.


text:
Q: How to delete all procedures of a database in mysql5 I want to delete all procedures from my MySQL database sbnmaster. How should I write a query for this?

A: Try this
USE sbnmaster;

SELECT CONCAT("DROP PROCEDURE IF EXISTS ",SPECIFIC_NAME) AS StorePrecedure
FROM information_schema.ROUTINES R
WHERE R.ROUTINE_TYPE = "PROCEDURE"
AND R.ROUTINE_SCHEMA = DATABASE();

A: Not sure that it is correct, but seems it works -
DELETE FROM mysql.proc WHERE db = 'sbnmaster' AND type = 'PROCEDURE';