text:
Q: Xero webhook not working says "Response contained a body" I am trying to get a webhook setup with Xero working locally. I am using ngrok to allow xero to call my localhost. To get the webhook working I must correctly return the "intent to receive"
It seems to be working fine in that I can debug it and follow it through. However when I try to return 200 for success (hashes match) or 401 unauthorized (hashes don't match) the receiving Xero still doesn't accept it. All it says is: "Response contained a body"
According to the Xero webhook docs my endpoint must ensure:

*

*It uses HTTPS

*It responds within 5 seconds with a 200 O.K status code

*There is no body in the response

*There are no cookies in the response headers

*If the signature is invalid a 401 Unauthorised status code is returned

I have tried returning the code in various ways:
public IHttpActionResult WebHooks()
{
    //if hash check fails I tried these
    return Unauthorized();
    return Request.CreateResponse((int)HttpStatusCode.Unauthorized);
    return StatusCode(HttpStatusCode.Unauthorized);

    //if hash check matched I tried the following
    return Ok();
    return Request.CreateResponse((int)HttpStatusCode.OK);
    return StatusCode(HttpStatusCode.OK);

}

In seething desperation I also tried
public int WebHooks()
{
    //if hash check matches
    return 200;
    //if hash check fails
    return 401;
}

Thank you in advance for your help. I spent too long searching for an existing answer, but I couldn't find any. What am I doing wrong? As far as I can see my webapi should work.

A: Figured it out. This is what I did to get it working:
            if (hashedPayload != xeroSignature)
            {
                ControllerContext.HttpContext.Response.Clear();
                ControllerContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                ControllerContext.HttpContext.Response.End();
                return Content(string.Empty);
            }

            ControllerContext.HttpContext.Response.Clear();
            ControllerContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            return Content(string.Empty);

A: Nothing I tried worked and my swear-jar overfloweth. I noticed through ngrok that the "intent to receive" would return a 302 (as opposed to 401) and then would redirect to Account/Login.
This led me down a rabbit hole to where I discovered the answer
To quote:

If you are adding asp.net WebApi inside asp.net MVC web site you
probably want to respond unauthorized to some requests. But then
ASP.NET infrastructure come into play and when you try to set response
status code to HttpStatusCode.Unauthorized you will get 302 redirect
to login page.

That was exactly the behaviour I saw. When I tried the webhook in a new webapi project with only one method - it worked. However I want to get it working in my MVC site. I added what this post suggested and it now works perfectly for me.
Many thanks to @Jacob Alley


text:
Q: Stop the n+1 in an eloquent query Currently, when I'm retrieving the messages, it is presenting the n+1 issue:
select * from `messages` where `messages`.`alert_id` = '21'

This sometimes is replicated over 100+ times!
Controller function:
public function getAdminIndex() {
    $company = User::find(Auth::user()->id)
               ->companies()
               ->with('users.alerts.location')
               ->first();
    $this->layout->content = View::make('agents.admin.index',
                             array('company' => $company));
}

User Model:
public function companies()
{
    return $this->belongsToMany('Company')->withTimestamps();
}

public function credits()
{
    return $this->hasMany('Usage');
}

public function deletedAlerts()
{
    return $this->hasMany('Alert')->onlyTrashed();
}

public function alerts()
{
    return $this->hasMany('Alert');
}

Alert Model:
public function location()
{
    return $this->belongsTo('Location');
}

public function messages()
{
    return $this->hasMany('Message');
}

Message Model:
public function alert()
{
    return $this->belongsTo('Alert');
}

public function user()
{
    return $this->belongsTo('User');
}

If I use the following line of code, I can see the MYSQL is correct, but it then can't find the location method:
->companies()
->with('users.alerts.messages.location')
->first();

select * from messages where messages.alert_id in ('21', '42')
I think it maybe a relationship issue, but I'm unsure of how to resolve it. Any help would be hugely appreciated.

A: The problem is that you need to load 2 relations on the Alert model (guessing without view code, but 99% sure):
public function getAdminIndex() {
$company = // User::find(Auth::user()->id)
           Auth::user()  // better approach as in @ollieread's comment
           ->companies()
           ->with('users.alerts.location', 'users.alerts.messages')
           ->first();
$this->layout->content = View::make('agents.admin.index',
                         array('company' => $company));
}

This will execute only 1 additional query for the messages relation, because users.alerts are already loaded.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing `get_or_insert()` without the error: cannot borrow `*self` as mutable more than once I'm trying to implement a get_or_insert() style method for a binary search tree. I can't seem to find a trick to getting this to work. The following fails.
I've posted a playground example which duplicates the issue in a similar manner.
struct Foo {
    data: Vec<i32>,
}

impl Foo {
    fn new() -> Self {
        Foo { data: vec![42; 5] }
    }

    fn get_mut(&mut self, index: usize) -> Option<&mut i32> {
        if index < self.data.len() {
            Some(&mut self.data[index])
        } else {
            None
        }
    }

    fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 { todo!() }
}

fn main() {
    let mut foo = Foo::new();
    let mut val = foo.get_or_insert(100, 88);
    *val = 42;
}

pub fn get_or_insert(&mut self, key: &K, value: V) -> &mut V {
    match self.get_mut(key) {
        Some(value) => value,
        None => {
            self.insert(key.clone(), value);
            self.get_mut(key).unwrap()
        }
    }
}

error[E0499]: cannot borrow `self.data` as mutable more than once at a time
  --> src/main.rs:35:9
   |
29 |     fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 {
   |                      - let's call the lifetime of this reference `'1`
30 |         {
31 |             if let Some(value) = self.get_mut(index) {
   |                                  ---- first mutable borrow occurs here
32 |                 return value;
   |                        ----- returning this value requires that `*self` is borrowed for `'1`
...
35 |         self.data.extend_from_slice(vec![value; index].as_slice());
   |         ^^^^^^^^^ second mutable borrow occurs here

error[E0499]: cannot borrow `self.data` as mutable more than once at a time
  --> src/main.rs:36:14
   |
29 |     fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 {
   |                      - let's call the lifetime of this reference `'1`
30 |         {
31 |             if let Some(value) = self.get_mut(index) {
   |                                  ---- first mutable borrow occurs here
32 |                 return value;
   |                        ----- returning this value requires that `*self` is borrowed for `'1`
...
36 |         &mut self.data[index]
   |              ^^^^^^^^^ second mutable borrow occurs here

Scoping the first attempt at acquiring the value also fails.
pub fn get_or_insert(&mut self, key: &K, value: V) -> &mut V {
    {
        let ret = self.get_mut(key);
        if ret.is_some() {
            return ret.unwrap();
        }
    }
    self.insert(key.clone(), value);
    self.get_mut(key).unwrap()
}

I've tried several other ways, but can't find something that works. I'm guessing this is impossible at this point. Is there some trick to getting a feature like this to work?


text:
Q: android uiautomator runtest error didn't find class recent i tryied getting started with android uiautomation testing.
The tutorial from the developer site I've worked through a few times and after having some problems and solving them now I have got a bigger issue.
I created a project, imported the two jar files and builded a java testcase scenario (the one from the tutorial.)
after that I created  an uitest projekt with shell command line. updated the build.xml created a jar file and pushed it onto my device.
As far as good everything worked nicely upon this point.
But tryin to run my tests with the command line:
adb -s <ANDROID_SERIAL> shell uiautomator runtest DeviceUnlocker.jar -c c.d.d.DeviceUnlocker

I only get the error:

INSTRUMENTATION_RESULT: shortMsg = java.lang.RuntimeException
INSTRUMENTATION_RESULT: longMsg=Didn't find class "c.d.d.DeviceUnlockingPseudoCodeTest on Path: /system/framework/android.test.runner.jar: /system/framework/uiautomator.jar:: /data/local/tmp/DeviceUnlocker.jar
INSTRUMENTATION_CODE: 0

A: okay the easiest way is to only create inside eclipse a new android junit projekt.
i think this is more or less equal to uiautomator.
and i think you might have the same oportunities ... correct me if i'm wrong...
uiautomator is still not running... and i also found some bugs in the uibuild.xml from android itself
<target name="test" description="Runs tests">
        <!-- todo: fix this -->
        <fail message="Launching tests from Ant not supported yet" />
     <exec executable="${adb}" failonerror="true">
        <arg line="${adb.device.arg}" />
        <arg value="shell" />
        <arg value="uiautomator" />
        <arg value="runtest" />
        <arg value="${out.filename}" />
        <arg value="-e" />
        <arg value="class" />
        <arg value="com.android.uiautomator.samples.skeleton.DemoTestCase" />
    </exec>
</target>`

thanks for your help. for me uiautomator is no option anymore.
regards

A: *

*new JavaProjekt (import JUnit android.jar uiautomator.jar

*create packages c.d.d

*Copy TestCase Device Unlocking pseudoTestCase into Projekt

*run cmd
4.1. "set ANDROID_HOME=" to sdk location
4.2. \tools\ android create uitestprojekt -n name -t "android-16" -p projPath

*edit build.xml that was created from create command:
added code:

<delete dir="jar"/>
<mkdir dir="jar" />
<javac destdir="bin" encoding="UTF-8" debug="on" target="1.6" includeantruntime="false">
    <src path="src" />
</javac>
<jar destfile="jar/uiautomator.jar">
     <fileset dir="bin" />
</jar>

*

*run as antbuild

*cmd -> cd ANDROID_HOME-> cd  platform-tools

*adb push /jar/uiautomator.jar data/local/tmp

*adb -s  shell uiautomator runtest DeviceUnlocker.jar -c c.d.d.DeviceUnlocker

that were all steps i've done
thanks

A: Make sure you've compiled the java classes into android dex!
I've met the same issue when put a pure java "jar" package to /data/tmp/.
Assume your project is device-unlock:
cd device-unlock
android create uitest-project -n device-unlock -t 1 -p .
and build

Now you'll find the dexed jar package in bin/device-unlock.jar, open it with zip you'll see a classes.dex.
With this jar, it should be ok to continue your test.

A: I had the exact same problem and made a quick haxx to fix it:
Solve it by:

*

*go to you UiautomationTest project and from the bin/ folder copy
the classfile(s). In my case I copied the whole folderstructure
com/poc/MyTest.class

*go to the App-Under-Test project and in the
bin/ folder past the class data. In my case the com/poc/MyTest.class
is merged with the existing classes under com/

*Re-build the UiAutomation project with "ant build"

*re-deploy and now you can run it!

This is just a workaround but it identified the root case - that the testcase class is excluded from the UiAutomator buildstep

A: While running the uiautomator Tests command run it in the below way
Example:
adb shell uiautomator runtest LaunchSettings.jar -c com.uia.example.my.LaunchSettings
adb shell uiautomator runtest "jar name" -c "packagename"."Classname"

This should work.

A: Best way to check this problem is to run this command without using -c <classpath>#<testMethod> and check if it works.
If it works check for the class name that it prints in the terminal is the one that's used with -c
adb -s shell uiautomator runtest DeviceUnlocker.jar


text:
Q: He has been watching TV 1.He has been watching TV.
What does this sentence mean?
Does it mean that the person started watching TV sometime before and still watching it or the person started watching TV sometime before and has stopped watching it? does it mean something else rather than my options?

A: The present perfect continuous has lots of applications. Its main definition states that an action began in the past and is still in progress.
Your ideas are right. The first one fits with the main definition. The second one is also used to describe the cause of something in the present.

He's been watching TV. That's why the TV is hot.

A: You can use the present perfect continuation as follows:

*

*For an action that happens over a period of time leading up to
the present such as "He has been watching TV for two hours".

*For an action that ends just before the present such as "He has been
watching TV". That's why his homework is still pending.

*For a repeated action up to now such as "He has been watching
TV since he  was five".


text:
Q: Android, setText and setTypeface don´t work I have a small issue with something, which I have peformed many times and also correctly. I want use my own font, resp. external google Roboto Font for my text of buttons in MainActivity, so I use a simple code which works before, but not now in onCreate() method when application/activity starts. Then I try just chane text but it also don´t work. After app start, it stay like it is prescribed activity_main.xml, anything change. When I use a other button function for that, it works. Where is problem? Cause I want set it immediately after activity start.
MainActivity.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DbHelper cryfi_db = new DbHelper(this);
    DbHelper_user user_db = new DbHelper_user(this);

    Button btn_ratings = (Button) findViewById(R.id.btn_ratings);
    Typeface roboto_light = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
    btn_ratings.setTypeface(roboto_light);

    //here are some others working functions for sqlite dbs
}

public void onButtonClick(View v){
    Button btn_ratings = (Button) findViewById(R.id.btn_ratings);
    Typeface roboto_light = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
    btn_ratings.setTypeface(roboto_light);
}

Can the problem be associated with functions for database or extending AppCompatActivity?
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/iv_intro"
    android:src="@drawable/intro_1"
    android:scaleType="fitXY" />

<Button
    android:id="@+id/btn_ratings"
    android:text="@string/ratings"
    android:textColor="#FFFFFF"
    android:textSize="20sp"
    android:layout_width="200dp"
    android:layout_height="40dp"
    android:background="@drawable/intro_btn"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="20dp" />

<Button
    android:id="@+id/btn_generate"
    android:text="@string/generate"
    android:textColor="#FFFFFF"
    android:textSize="20sp"
    android:layout_width="200dp"
    android:layout_height="40dp"
    android:background="@drawable/intro_btn"
    android:layout_marginBottom="20dp"
    android:layout_above="@+id/btn_ratings"
    android:layout_alignLeft="@+id/btn_ratings"
    android:layout_alignStart="@+id/btn_ratings" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OtherButton"
    android:id="@+id/button2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="47dp"
    android:layout_below="@+id/ib_settings"
    android:onClick="onButtonClick" />

I have there others imageButtons, but they do not have anything to do with that.

A: Just make sure that your ttf file is inside the  main/assets/fonts folder.
And try the same code in
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
             Button btn_ratings = (Button) findViewById(R.id.btn_ratings);
             Typeface roboto_light = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf");
            btn_ratings.setTypeface(roboto_light);
        }
    }

A: Use TypeFaceHelper class to cache the fonts and use them.
public class Typefaces{

    private static final Hashtable<String, Typeface> cache = new Hashtable<String, Typeface>();

    public static Typeface get(Context c, String name){
        synchronized(cache){
            if(!cache.containsKey(name)){
                Typeface t = Typeface.createFromAsset(c.getAssets(), String.format("fonts/%s.ttf", name));
                cache.put(name, t);
            }
            return cache.get(name);
        }
    }
}

Now you can use Typefaces.get to change your font.
btn_ratings.setTypeface(Typefaces.get(this, "fonts/Roboto-Light.ttf"));

A: Create a custom button that will solve your issue :
public final class RobotoButton extends Button {
    private static Typeface mTypeface;
     public RobotoButton(final Context context, final AttributeSet attrs) {
         super(context, attrs);
         setTypeface(Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"));
     }
}

And in your xml :
<com.x.RobotoButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="OtherButton"......./>


text:
Q: Plugin for aroundSavePaymentInformationAndPlaceOrder Throwing Error I have a plugin that i want to intercept aroundSavePaymentInformationAndPlaceOrder, but it is giving me an error. Here is how it is set up:
Vendor/Module/etc/di.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <virtualType name="Magento\Sales\Model\ResourceModel\Order\Grid" type="Magento\Sales\Model\ResourceModel\Grid">
          <arguments>
              <argument name="columns">
                  <item name="veratad_action" xsi:type="string">sales_order.veratad_action</item>
              </argument>
          </arguments>
      </virtualType>
      <type name="Magento\Checkout\Model\GuestPaymentInformationManagement">
              <plugin name="veratad_ageverification_before_order" type="Veratad\AgeVerification\Plugin\Ageverification" sortOrder="10" disabled="false"/>
        </type>
    </config>

Vendor/Module/Plugin/Ageverification.php
    namespace Veratad\AgeVerification\Plugin;

    use Magento\Checkout\Model\PaymentInformationManagement as CheckoutPaymentInformationManagement;

    class Ageverification
    {

      public function aroundSavePaymentInformationAndPlaceOrder(CheckoutGuestPaymentInformationManagement $subject){

        return ($subject);

   }

}

I am getting the following error:
    PHP Fatal error:  Uncaught TypeError: Argument 1 passed to Veratad\AgeVerification\Plugin\Ageverification::aroundSavePaymentInformationAndPlaceOrder() must be an instance of Veratad\AgeVerification\Plugin\CheckoutGuestPaymentInformationManagement, instance of Magento\Checkout\Model\GuestPaymentInformationManagement\Interceptor given, called in /home/z3hjb5ti7gx1/public_html/magento/vendor/magento/framework/Interception/Interceptor.php on line 135 and defined in /home/z3hjb5ti7gx1/public_html/magento/app/code/Veratad/AgeVerification/Plugin/Ageverification.php:10
    Stack trace:
    #0 /home/z3hjb5ti7gx1/public_html/magento/vendor/magento/framework/Interception/Interceptor.php(135): Veratad\AgeVerification\Plugin\Ageverification->aroundSavePaymentInformationAndPlaceOrder(Object(Magento\Checkout\Model\GuestPaymentInformationManagement\Interceptor), Object(Closure), 'f2c487019bcfd1b...', 'tcanfarotta2@v....', Object(Magento\Quote\Model\Quote\Payment), Object(Magento\Quote\Model\Quote\Address))
    #1 /home/z3hjb5ti7gx1/public_html/magento/ve in /home/z3hjb5ti7gx1/public_html/magento/app/code/Veratad/AgeVerification/Plugin/Ageverification.php on line 10

Can someone help me understand what I am doing wrong?
New Plugin Code:
      namespace Veratad\AgeVerification\Plugin;

      use Magento\Framework\Exception\CouldNotSaveException;

      class Ageverification {

          public function aroundSavePaymentInformationAndPlaceOrder(
          \Magento\Checkout\Model\PaymentInformationManagement $subject,
          callable $proceed,
          \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
          \Magento\Quote\Api\Data\AddressInterface $billingAddress = null) {
              $action = "FAIL";
              if($action == "FAIL"){
                      throw new CouldNotSaveException(__('You have not been age verified.'));
                      return false;
              }else{
                  $proceed($paymentMethod,$billingAddress);
          }
      }
    }

A: You plugin  class  is wrong, The aroundSavePaymentInformationAndPlaceOrder() should have 4 parameters.

*

*$subject which object of Magento\Checkout\Model\GuestPaymentInformationManagement.

*second callback $proceed.

*3rd parameter is   $paymentMethod which instance of \Magento\Quote\Api\Data\PaymentInterface.
4 .4th parameter is    $billingAddress which instance of Magento\Quote\Api\Data\AddressInterface .
Please check how to use around plugin https://devdocs.magento.com/guides/v2.2/extension-dev-guide/plugins.html
<?php
namespace Veratad\AgeVerification\Plugin;

use Magento\Checkout\Model\PaymentInformationManagement as CheckoutPaymentInformationManagement;

class Ageverification {

    public function aroundSavePaymentInformationAndPlaceOrder(
    CheckoutGuestPaymentInformationManagement $subject, callable $proceed,
    \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
    \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    ) {

        $proceed($paymentMethod,$billingAddress);
    }

}


text:
Q: What is the printf format specifier for bool? Since ANSI C99 there is _Bool or bool via stdbool.h. But is there also a printf format specifier for bool?
I mean something like in that pseudo code:
bool x = true;
printf("%B\n", x);

which would print:
true

A: There is no format specifier for bool. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");

A: You can't, but you can print 0 or 1
_Bool b = 1;
printf("%d\n", b);

source

A: ANSI C99/C11 don't include an extra printf conversion specifier for bool.
But the GNU C library provides an API for adding custom specifiers.
An example:
#include <stdio.h>
#include <printf.h>
#include <stdbool.h>

static int bool_arginfo(const struct printf_info *info, size_t n,
    int *argtypes, int *size)
{
  if (n) {
    argtypes[0] = PA_INT;
    *size = sizeof(bool);
  }
  return 1;
}
static int bool_printf(FILE *stream, const struct printf_info *info,
    const void *const *args)
{
  bool b =  *(const bool*)(args[0]);
  int r = fputs(b ? "true" : "false", stream);
  return r == EOF ? -1 : (b ? 4 : 5);
}
static int setup_bool_specifier()
{
  int r = register_printf_specifier('B', bool_printf, bool_arginfo);
  return r;
}
int main(int argc, char **argv)
{
  int r = setup_bool_specifier();
  if (r) return 1;
  bool b = argc > 1;
  r = printf("The result is: %B\n", b);
  printf("(written %d characters)\n", r);
  return 0;
}

Since it is a glibc extensions the GCC warns about that custom specifier:

$ gcc -Wall -g    main.c   -o main
main.c: In function 'main':
main.c:34:3: warning: unknown conversion type character 'B' in format [-Wformat=]
   r = printf("The result is: %B\n", b);
   ^
main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]

Output:

$ ./main
The result is: false
(written 21 characters)
$ ./main 1
The result is: true
(written 20 characters)

A: If you like C++ better than C, you can try this:
#include <ios>
#include <iostream>

bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;

A: To just print 1 or 0 based on the boolean value I just used:
printf("%d\n", !!(42));

Especially useful with Flags:
#define MY_FLAG (1 << 4)
int flags = MY_FLAG;
printf("%d\n", !!(flags & MY_FLAG));

A: In the tradition of itoa():
#define btoa(x) ((x)?"true":"false")

bool x = true;
printf("%s\n", btoa(x));

A: There is no format specifier for bool types. However, since any integral type shorter than int is promoted to int when passed down to printf()'s variadic arguments, you can use %d:
bool x = true;
printf("%d\n", x); // prints 1

But why not:
printf("Your boolean variable is: %s", x ? "true" : "false");

instead?

A: I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like
printf("%s\n", "false\0true"+6*x);

*

*x == 0, "false\0true"+ 0" it means "false";

*x == 1, "false\0true"+ 6" it means "true";


text:
Q: DISQUS: Is it possible to get a particular user's posts in a given forum? I am running a website, whose community is powered by Disqus. I would like to create user profile pages, where the page would display the particular user's most recent activity, but only for my particular site (forum, in Disqus' terminology).
I ran through the entire API documentation, but I could not find a way that would allow me to filter by both user, and forum. I would be able to grab either the entire list of posts for a given forum, or the one from a particular user.
In every API call, there is a mysterious query paramater, where I tried to plug a series of filters, but none of them worked.
Is there something that I could be missing?

A: It's not that obvious, but you can use the query param as a filter for users. Try something like this:
https://disqus.com/api/3.0/forums/listPosts.json?forum={SHORTNAME}&query=user:{USERNAME}&api_key={YOUR_API_KEY}


text:
Q: Call to undefined method Illuminate\Foundation\Application::share() - LARAVEL 9 EXCEL i want to make export excel using composer require maatwebsite/excel
this is composer.json code
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"php": "^8.0.2",
"barryvdh/laravel-dompdf": "^2.0",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.19",
"laravel/sanctum": "^3.0",
"laravel/tinker": "^2.7",
"laravel/ui": "^4.0",
"maatwebsite/excel": "*"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\Foundation\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r "file_exists('.env') || copy('.env.example', '.env');""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "dev",
"prefer-stable": true
}
when i write
php artisan vendor:publish –provider="Maatwebsite\Excel\ExcelServiceProvider" –tag=config

the error appears as follows:
Call to undefined method Illuminate\Foundation\Application::share()

  at vendor/maatwebsite/excel/src/Maatwebsite/Excel/ExcelServiceProvider.php:159
    155▕     */
    156▕    protected function bindClasses()
    157▕    {
    158▕        // Bind the format identifier
  ➜ 159▕        $this->app['excel.identifier'] = $this->app->share(function($app) {
    160▕            return new FormatIdentifier($app['files']);
    161▕        });
    162▕    }
    163▕

      +8 vendor frames
  9   artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

I have followed these tips, but still confused about the share() method in the comments all or not? Laravel - Call to undefined method Illuminate\Foundation\Application::share()


text:
Q: "Failed to initialize the Common Language Runtime" when trying to access a SQL 2014 Express database I'm currently developing a website that uses a SQL Server 2014 Express database on my machine. This has always worked in the past, but today I got the following error:

Failed to initialize the Common Language Runtime (CLR) v4.0.30319 with
  HRESULT 0x80131534. You need to restart SQL Server to use CLR
  integration features.

Of course I restarted SQL Server 2014 Express, but to no avail.

A: I ended up downloading a .NET framework repair tool. After running it and rebooting my computer, I was able to connect to the database again.


text:
Q: How to test a delegate using Moq and NUnit I have a factory class returning a delegate like below (GetDelegate method)
  public interface IFactory
{
    Func<int, string> GetDelegate(bool isValid);
}

public class AFactory : IFactory
{
    private readonly IService1 _service1;
    private readonly IService2 _service2;

    public AFactory(IService1 service1, IService2 service2)
    {
        _service1 = service1;
        _service2= service2;
    }

    public Func<int, string> GetDelegate(bool isValid)
    {
        if (isValid)
            return _service1.A;
        return _service2.B;
    }
}

public interface IService1
{
    string A(int id);
}

public interface IService2
{
    string B(int id);
}

I have been trying to write unit test for GetDelegate but dont know how to assert that a specific Func was returned depending on isValid
My attempt of a unit test is like below (which i am not happy with)
[Test]
    public void ShouldReturnCorrectMethod()
    {
        private var _sut = new AFactory(new Mock<IService1>(), new Mock<IService2>());

        var delegateObj = _sut.GetDelegate(true);
        Assert.AreEqual(typeof(string), delegateObj.Method.ReturnType);
        Assert.AreEqual(1, delegateObj.Method.GetParameters().Count());
    }

Any help is much appreciated
thanks

A: One way would be to mock the result of calling IService1.A and IService2.B, in exactly the same way as if you were calling them directly. You could then check that when you call the returned delegate, you get the expected answer (and that the call was made to the appropriate service).

A: [Test]
public void GetDelegate_WhenCalledWithIsValidTrue_ReturnsDelegateA()
{
    // Arrange
    Mock<IService1> service1Mock = new Mock<IService1>();
    Mock<IService2> service2Mock = new Mock<IService2>();

    string expectedResultA = "A";
    string expectedResultB = "B";

    service1Mock.Setup(s => s.A(It.IsAny<int>())).Returns(expectedResultA);
    service2Mock.Setup(s => s.B(It.IsAny<int>())).Returns(expectedResultB);

    var _sut = new AFactory(service1Mock.Object, service2Mock.Object);

    // Act
    Func<int, string> delegateObj = _sut.GetDelegate(true);

    // Assert
    string result = delegateObj(0);
    Assert.AreEqual<string>(expectedResultA, result);
}


text:
Q: File won't open in Chrome or Firefox, file name in URL changes to "0" I tried searching for "file name changes to 0 in browser" both in Google and here, but got nowhere.  This is a simple file which suddenly stopped opening. I can't even get at the inspector to troubleshoot it. Undo/redo history is lost, so that will not help.  I'm guessing it's a simple mistake, but I have NEVER seen this before.
<!doctype html>

    <title>JS Animated Navigation Test</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

<button onclick="myMove()">Click Me</button>

Thank you

A: You can't use the variable name location as it is a reserved word; what you're actually doing is setting the window.location variable to 0.
Rename it, or put it in a namespace or object.


text:
Q: OS X Server - setting up a share for network home directories + fast user switching I'm nearly finished setting up my Open Directory master to allow users to be managed centrally and logged in on any of the client machines at home.
I found discussion suggesting that using an AFP share for the 'Users' automount would result in network users (cf. users defined locally, or Portable Home Directory users) are unable to use fast user switching, as the first user logging in would trigger the automount and mount the 'Users' share with his permissions, preventing further users from using the mount.
I've also found some suggestions to configure autofs such that the 'Users' share is mounted prior to any user logging in, but not great amounts of details along these lines.
I'd greatly appreciate some instructions to set up autofs - ideally, on the OpenDirectory server rather than each client's etc/fstab or equivalent location, so that it isn't required per every client machine - to get fast user switching working with network users.

A: I got two sites, connected to each other by a site-to-site vpn. The sites are named s1 and s2, s1 and s2 both having several Macs and PC's. I want all the users on all the Macs having access to a shared data map on s1, lets say Data_s1, and to a shared data map on s2, lets say Data_s2. Data_s1 will reside on a server on site s1, Data_s2 will reside on a server on site s2. For the users, Data_s1 en Data_s2 will be in the parent map Data (will be indirect map. For more info and the best info I found so far, see this white paper)
The best way to do this, is by creating automount maps and you can do this in /etc/auto_master etcetera, etcetera. But than you will have to do this on every single machine in both s1 and s2.
A more elegant way to do this, is by using the auto mount feature in LDAP, but all this has been changed in Lion and I couldn't find that anywhere (after looking for hours on the web).
In Lion, there is a new utility in the Directory Utility.
Go to - System preferences - Users & Groups - Login options - click lock & authenticate - Edit (at bottom, next to Network Account Server) - Open Directory Utility - Directory Editor (on top).
Now choose the node: /LDAPv3/'IP' ('IP'= 127.0.0.1 if you are running the directory utility on the server itself, or else the IP of the server) and in View, choose AutomountMap.
Click the lock and authenticate as a Directory Administrator.
Click "+" at bottom left. In the left pane an entry appears, something like "Nameless 1". In the upper right pane, you will see "Recordname" with its name. This name can be changed in the bottom right pane. Change it to "auto_master", making the equivalent of the auto_master file in /etc. When you save this, a new object of the object class AutomountMap is created.
The new object also contains some attributes that can't be changed (greyed out), like e.g. RecordType. Here, I also create the indirect map Data, in which Data_s1 and Data_s2 will appear later on (see scheme in white paper mentioned above).
So far so good.
Now, we have to create the automount-objects. Change View - AutomountMap to View - Automount.
Add an object (Bottom +) which will mount the Data_s1 map. Change Recordname to Data_s1.
Add an attribute to the Data_s1-object by clicking the + sign in the middle, between the two right panes. Accept the default attribute (Automountinformation) and put in the path to the map on the fileserver on s1.
This should complete the auto mount information, but here I am stuck: Saving the object results in an error: Invalid recordtype (4101).
If someone could get us further from this point on, equally appreciated.
In fact, this is not for creating home directories solely, it is a more general approach. Creating home directories on a certain server can be done through the Server App.

A: I set up phpLDAPadmin for the DirectoryServer.
I noticed that there wasn't an AutoMount Container.
Because of that I created (in phpLDAPadmin) below the automountMap entry (e.g. auto_master)
automount entries. Now I see this entries in DirectoryUtility below AutoMount.
Restart autofs on Linux.
This works with Mountain Lion Server and an Ubuntu Precise Pangolin client.


text:
Q: If I burn Ubuntu onto one of my internal hard drives and boot off it to install it on another hard drive, can I undo it? I have an internal hard drive that's empty. I want to make that like a USB to boot from. But I'm afraid if I create that I cannot undo it and format my HDD, the same way you can't undo burning a movie to a CD. I'm on Windows 10.

A: You can use a hard disk drive as a live drive and re-use it afterwards
I have done it many times with HDDs and  SSDs too.
Be very careful to write to the correct target drive (check and double-check to avoid mistakes). It is a good idea to have a backup of everything, that you cannot afford to lose.

*

*In Linux I use mkusb for this purpose, both to make a live-only drive or persistent live drive and to wipe the first mibibyte or restore it to a standard storage device. See this link,
help.ubuntu.com/community/mkusb
You may want to use gparted after wiping the first mibibyte in order to create a more advanced partition table.

*In Windows I use Win32 Disk Imager to make a live-only drive (for installing purposes). See this link,
wiki.ubuntu.com/Win32DiskImager/iso2usb
You can use other software too, for example Rufus, which is recommended officially by Ubuntu,
rufus.akeo.ie
Edit: I am not sure, if the tools in Windows will write to an internal drive, or if the HDD or SSD must be connected via USB (and an adapter or external box). If problems with one tool, let us try another one, in order to do what you want.

A: Hard disks and SSDs can always be wiped clean after use, short of a hardware failure. Several ways to do this exist:

*

*dd -- The dd command is a sort of "nuclear option" for wiping disks. It copies data from one device to another. You can give it /dev/zero as the source to wipe the disk. Thus, something like sudo dd if=/dev/zero of=/dev/sdb bs=4096 will completely wipe all data on /dev/sdb. This makes the dd command potentially very dangerous -- but also very useful. (The bs=4096 part of this command is optional. It tells dd to write 4096 bytes at a time. This reduces the time it takes the command to wipe modern Advanced Format disks, which use 4096-byte sectors.) Note that completely wiping a hard disk is likely to take hours. When it's done, the disk will be completely empty. Using this procedure is advisable before you sell a hard disk or hand it over for recycling, to ensure you've erased all personal data (credit card numbers, tax returns, passwords, etc.). In your case, it's probably overkill, but it may be an option worth considering if other options don't quite get the job done. Note that a full wipe like this on an SSD will make the SSD think the whole disk is in use. You should probably create a Linux filesystem and then use fstrim on it to ensure that the SSD understands that the disk is now effectively empty.

*Partial dd -- By adding options to the preceding dd command, you can erase part of a disk. Most partitioning information resides early on the disk, and this is certain to be true if you used dd to copy the .iso file to the hard disk to begin with. I don't recall exactly how much data you'd need to erase to wipe a hybrid ISO-9660/MBR or ISO-9660/GPT disk image, but something like sudo dd if=/dev/zero of=/dev/sdb bs=4096 count=1000 would almost certainly get it all, and would be much faster than wiping the whole disk. This approach will not erase all the sensitive data on the disk, though. If you partitioned the disk in a conventional way, this would be more than enough to get all MBR data. Some GPT data might lurk at the end of the disk, though....

*GPT fdisk -- My GPT fdisk utility suite (installed in the gdisk package in Ubuntu), and in particular its gdisk and sgdisk tools, provide a feature to wipe all GPT data from the disk. This feature will also wipe all MBR data. The easiest way to do this is by typing sudo sgdisk -Z /dev/sdb, changing /dev/sdb as necessary. This command wipes all the GPT data structures, including both the main data structures at the start of the disk and the backup data structures at the end of the disk. Like a partial dd operation, this one leaves sensitive data on the disk, so it's not adequate if you want to "sanitize" a disk before it leaves your possession.

For your purposes, I'd try using either sgdisk -Z or a partial dd operation. If that fails, a full dd of the whole disk might be in order.
Note that there are some exotic cases where something else might be required, in addition to or instead of the preceding. One of these is if something has set the Host Protected Area (HPA) feature on the disk. This feature enables part of the disk's space to be hidden from the computer. See the link to the Wikipedia article for details. It sometimes gets set accidentally and must be unset by using the -N option to hdparm. Another possible complicating factor is if the disk is part of a RAID array, or if your firmware is set to enable RAID. This has an effect that can be similar to HPA, in that a part of the disk is hidden and used to store RAID metadata. In this case, you'd need to use RAID-specific tools (and/or disable the RAID settings in your firmware) to properly use (and delete data from) the affected parts of the disk. Simply writing an Ubuntu .iso file to a hard disk will not activate either HPA or RAID settings, though, so chances are you don't need to be concerned with them. I mention them only in case one of these features happens to have been set on your disk in addition to what you're doing, or in case somebody else in the future might have such a problem and stumble across this answer.


text:
Q: Castle Windsor - Automatic Transaction Management Are there any simple examples on how to use Castle Windsor's Automatic Transaction Management?  The documentation seems to be lacking some information.  I see there are facilities for nHibernate, ActiveRecord, etc....  However, I'm looking for a simple implementation just to understand how it works.

A: Here's a simple sample app that uses ASP.NET MVC + Castle Automatic Transaction Facility + NHibernate facility.


text:
Q: CSS transition class width on hover I'm trying to use pure css to alter the widths of my classes on hover.
So far the transition is working with regard to altering the classes, but class .b and .c are not affecting the width of the classes that come before them. I need the previous class (i.e. class .a) to contract when hovering on class .b
I posted the code below and hopefully someone has a solution that ideally contains only CSS.

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

.column {
  float: left;
  width: 33.33%;
  height:100%;
}

.a{
    background-color: #ff0000;
    transition: 0.3s;
}
.a:hover{
    background-color: #c41333;
    width:40%;
}

.a:hover ~ .b, .c{
    width:30%;
}

.b{
    background-color: #eeeeee;
    transition: 0.3s;
}

.b:hover{
    background-color: #c41333;
    width:40%;
}

.b:hover ~ .a, .c{
    width:30%;
}

.c{
    background-color: #cccccc;
    transition: 0.3s;
}

.c:hover{
    background-color: #c41333;
    width:40%;
}

.c:hover ~ .a, .b{
    width:30%;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

tester

tester

tester

Thanks for your help.

A: Fiddle: https://jsfiddle.net/kawal/ygn8fk17/7/
.box {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  transition: width 0.2s ease-out;

}

.box:hover {
  width: 200px
}

A: You can use flexbox to do this. You only change the width of the element currently hovered and it's siblings adapt to it.

.row {
  display: flex;
}

.col {
  background: red;
  width: 33.33%;
  height: 50px;
  transition: width 0.3s ease-in-out;
}
.col:nth-child(even) {
  background: green;
}

.col:hover {
  width: 50%;
}

A: How about this instead? https://jsfiddle.net/jtnxL7cz/
.column {
  float: left;
  width: 33.33%;
  height:100%;
  transition: 0.3s;
}

.row:hover .column {
  width: 30%;
}

.row:hover .column:hover {
  width: 40%;
}

.a{
  background-color: #ff0000;
}

.b{
  background-color: #eeeeee;
}

.b:hover{
  background-color: #c41333;
}

.c{
  background-color: #cccccc;
}

.c:hover{
  background-color: #c41333;
}


text:
Q: jQuery: Can't use the "find" method twice on a single object I'm currently trying to use the jquery "find" method on an object twice but it isn't letting me do it, only the first instance of "find" is working.  Here is the code that I would like to run...
$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').find('.delete_phone').remove();

The above code works just fine except for the last "find" method, it isn't removing the elements with a ".delete_phone" class.
However, if I change the code to look like this...
$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.delete_phone').remove();

It does remove the elements with a ".delete_phone" class.  I assume this is because I can't use the "find" method twice in a row, but I'm not sure.
Does anyone know what's going on or if there is a way around this problem?
Thanks!

A: You need a .end() to hop back in the chain (so you're not looking inside the previous .find() results), like this:
$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').end().find('.delete_phone').remove();

Broken down view:
$("#phone_numbers > p:first-child").clone(true)
  .insertBefore("#phone_numbers > span:last-child")
  .find('.phone_type, .phone_number, .user_phones_id') //look in the cloned

  .val('')                                             //empty those inputs
  .end()                                               //hope back to the

  .find('.delete_phone')                               //look in the clone

  .remove();                                           //remove those elements

A: It looks like you are trying to cram a lot of requests into one line when you don't really need to. I'm not exactly sure what you are aiming to do, but I would manage it more like this.
Instead let's break it down into three simple requests:
var numbers = $("#phone_numbers > p:first-child");//grab the data you want
numbers.insertBefore("#phone_numbers > span:last-child");//insert it where you want
$("#phone_numbers .delete_phone').remove();//remove numbers with class 'delete_phone'

Not sure what you are trying to do for the val() part as you are not storing the value in a variable, neither are you changing the value.
If you need more help message back.
W.


text:
Q: Code works in code tester but not in adressbar If i input my code here:
http://writecodeonline.com/javascript/
It works as intended, but if i input it in my adressbar with "javascript:" infront the alert box just shows the original string.
What is going wrong?
var string = "Sunshine & Whiskey";
var stringFeedback;
var i = 0;

string = string.replace("&","%26");

do {
    stringFeedback = string.search(/[ ]/);
    string = string.replace(/[ ]/,"%20");
    i += 1;
} while (i < 5);

alert(string);

Edit:
If i input in my Chromium console it works fine, but if i make a bookmark with the same code it doesn't.
Any suggestions on how to fix that?

A: Try initialising i before the loop:
var i = 0;
do {
    stringFeedback = string.search(/[ ]/);
    string = string.replace(/[ ]/,"%20");
    i += 1;
} while (i < 5);

Whatever, I recommend you use your browser console to test these code snippets.

A: You can use
encodeURIComponent("Sunshine & Whiskey");

That returns
Sunshine%20%26%20Whiskey

without any loop, it's a native method of javascript that is supported by all Browser.
MDN documentation


text:
Q: Implement Array using linkedlist This was asked in an interview.
Can you implement/create an object in java which is similar to Array class in java.
basically we should be able to iterate over the object like we do with arrays and getValue() or putValue() methods should be able to directly work on index of the object created.
ex: below operation should be performed with created object.
int ar[] = new int[5];
for(int i=0; i<5; i++){
     ar[i]=i;
}

Hint given was to use linkedlist data structure.
in simple words its the similar like ArrayList class implementation.
can anyone give me an idea how can we do this?

A: He was asking about nested objects. please read about decorator pattern. please see the below example.
public interface NodeInterface{

// your methods
}

public class Node implements NodeInterface{
    private NodeInterface node = null;

   // your methods

}

There every node contains nested object of same type. last object that have no object points to a null. you can traverse untill you find a null.

A: I've asked a similar question before which has been answered, and it has to do with the concept of nodes and linked list. My question can be found by following this link
Problems understanding concept of nodes and linked list
I accepted the answer because it helped me visualize what the linked list would look like and what my Node class would look like.
When you do make the node object, you can then make custom classes to change to value of what that node is storing, as well as retrieving and displaying the data stored in the node.
The node class would look something like this
public class Node{

  private int val;
  private Node node;

  public Node(int val){
      this.val=val;
  }

  public Node(Node node, int val){
      this.node = node;
      this.val = val;
  }

  public Node getNext(){
      return node;
  }

  public int getVal(){
      return val;
  }

}

Obviously you can modify the code to store anything you want, but this is probably what the interviewers were looking for.

A: Using LinkedList it should looks like:
LinkedList<Integer> linkedList = new LinkedList<>();
for(int i=0; i<5; i++){
     linkedList.add(i);
}

However, I'm giving you the link for beginners in which you can lear everything about the java util package. Good luck.


text:
Q: How do I monitor a directory for changes and run a command automatically? (CLI) I would like to monitor a directory for changes (new files, subdirectories, or changed files or subdirectories). As soon as a change has been detected, I want the passed command to be called. It should continue to monitor for changes and run the command, until the command is killed using ctrl-c.
For example:
$ cd directoryname
$ watchcommand examplecommand arg1 arg2 arg3
...
... change detected in example1.txt, running "examplecommand arg1 arg2 arg3"
...
... change detected in example2.txt, running "examplecommand arg1 arg2 arg3"

I know there are similar questions out there to this question. However, they have not been marked as duplicates of each other, because they all differ in what the user wants to happen once a change has been detected. This question is meant to be more generic. I'm interested in running a placeholder command once changes are detected.
Please post one answer per tool, so that each tool can be voted on separately.


text:
Q: Cannot run PIP3 in MacBook Air M1 Background: I just got this new MacBook Air M1. I installed ITerm2 and when asked if I wanted to install the dev package I did it.
Problem: I cannot run Pip3. When I try I got this error:
Traceback (most recent call last):
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 193, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/__main__.py", line 16, in <module>
    from pip._internal import main as _main  # isort:skip # noqa
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/__init__.py", line 40, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/autocompletion.py", line 8, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/main_parser.py", line 11, in <module>
    from pip._internal.commands import (
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/__init__.py", line 6, in <module>
    from pip._internal.commands.completion import CompletionCommand
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/commands/completion.py", line 6, in <module>
    from pip._internal.cli.base_command import Command
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/cli/base_command.py", line 26, in <module>
    from pip._internal.index import PackageFinder
ImportError: cannot import name 'PackageFinder' from 'pip._internal.index' (/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages/pip/_internal/index/__init__.py)

A: try reinstalling pip
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py && python get-pip.py

and when you are done
$ rm get-pip.py


text:
Q: I have written Verilog code for FSM based Serial Adder Circuit, but m getting some sort of syntax error Block diagram
Design is a serial adder. It takes 8-bit inputs A and B and adds them in a serial fashion when the goinput is set to 1. The result of the operation is stored in a 9-bit sum register, The block diagram is attached. I am using Quartus II 13.0sp1 (64-bit) Web Edition.
Errors:
Error (10170): Verilog HDL syntax error at LAB9b.v(56) near text "â";  expecting ":", or ","
i have not written this text "â" anywhere in the code but still it is sowing me syntax error near "â" .??
Following is the Code written :-
module LAB9b(A, B, start, resetn, clock, sum);
    input [7:0] A, B;
    input resetn, start, clock;
output [8:0] LEDR;

 // Registers
wire [7:0] A_reg,B_reg;
wire [8:0] sum;
reg [1:0] temp;
reg cin;

 // Wires
wire reset, enable, load;
wire bit_sum, bit_carry;

//  Confrol FSM
FSM my_control(start, clock, resetn, reset, enable, load);
// Datapath
shift_reg reg_A( clock, 1'b0, A, 1'b0, enable, load, A_reg);
shift_reg reg_B( clock, 1'b0, B, 1'b0, enable, load, B_reg);

 // a full adder
assign temp [1:0] = A_reg[0] + B_reg[0] + cin;
assign  bit_sum = temp [0];
assign bit_carry = temp [1];

always @(posedge clock)
begin
    if (enable)
        begin
            if (reset)
            cin <= 1'b0;
        end
    else
        cin <= bit_carry;
end

shift_reg reg_sum( clock, reset, 9'd0, bit_sum, enable, 1'b0, sum);
defparam reg_sum.n = 9;
endmodule

module FSM(start, clock, resetn, reset, enable, load);
parameter WAIT_STATE = 2'b00, WORK_STATE = 2'b01, END_STATE = 2'b11;
input start, clock, resetn;
output reset, enable, load;

reg [1:0] current_state, next_state;
reg [3:0] counter;
 // next state logic
 always@(*)
 begin
 case(current_state)
WAIT_STATE:
    if (start) next_state <= WORK_STATE;
    else next_state <= WAIT_STATE;
WORK_STATE:
    if (counter == 4'd8) next_state <= END_STATE;
    else next_state <= WORK_STATE;
END_STATE:
    if (»start) next_state <= WAIT_STATE;
    else next_state <= END_STATE;
default: next_state <= 2'bxx;

endcase
end

// state registers and a counter
always@(posedge clock or negedge resetn)
begin
    if (»resetn)
        begin
            current_state <= WAIT_STATE;
            counter = 'd0;
    end
    else
        begin
            current_state <= next_state;
            if (current_state == WAIT_STATE)
                counter <= 'd0;
            else if (current_state == WORK_STATE)
                counter <= counter + 1'b1;
        end
end

// Outputs
assign reset = (current_state == WAIT_STATE) & start;
assign load = (current_state == WAIT_STATE) & start;
assign enable = load | (current_state == WORK_STATE);
endmodule
//
//
module shift_reg( clock, reset, data, bit_in, enable, load, q);
parameter n = 8;

input clock, reset, bit_in, enable, load;
input [n-1:0] data;
output reg [n-1:0] q;

always@(posedge clock)
begin
if (enable)
if (reset)
q <= 'd0;
else
begin
if (load)
q <= data;
else
begin
q[n-2:0] <= q[n-1:1];
q[n-1] <= bit_in;
end
end
end
endmodule

A: ' is not ' (notice the shape difference). Verilog works with the apostrophe character (', ASCII 0x27). Your ' is likely an extended ASCII character. There is also a » character, which I believe should be !.
I'm guessing you wrote your code in word editor (ex Microsoft Word, LibreOffice Writer, Apple iWork, etc). These kinds of editors tend to swap ' for ' while you type because it is more visually appealing for humans. Email clients and some messaging apps tend to do this too.
You should always write your code in a plain texted editor or an editor intended for writing code. Emacs and Vim are popular editors for writing code; syntax highlighting plugins are available for both. An IDE, like Eclipse, is another option. Notepad does work as well.

I also noticed you used an assign statement on the reg type temp. This is not legal in Verilog because assign statements can only be done on net types (e.g. wire). You may have other compiling errors that will show up after fixing ' and », the error message will likely be more helpful.
The compiler will not flag it, but the recommended coding style is to use blocking assignments (=) inside combination block (always@(*)), not non-blocking (<=).


text:
Q: React Native how to pass google play store and App Store url parameters to input How to pass google play store and app store url parameters value to input field?
for example, https://play.google.com/store/apps/details?id={appID}&hl=en&referrer=ABC123
i want to pass the ABC123 to referrer input field after the user installed the app.
i have tried, Linking but the Linking will only work when the user app is installed.
What i trying to do is,

*

*When the user not installed the app.

*go to https://play.google.com/store/apps/details?id={appID}&hl=en&referrer=ABC123

*App installed

*When opened the app auto field up referrer field to ABC123

A: You can make use of Firebase Dynamic Links. If a user clicks your link, and doesn't have the app installed, user would be redirected to the app store to download. After download, the app launches and you can then process the link.

*

*Set up Firebase Dynamic Links (by following the docs above)

*Set up Deep Linking in React Navigation to handle deep links in your app

*Add data you intend to pass (in your case, referral link etc) to the dynamic link

*User clicks on your link and is redirected to app store or play store to download the app.

*After download, user launches app

*Then the Linking module you set up in step 2 will handle the deep link and extract the data you need


text:
Q: Pass request through method in test I have a generate() method on my class which is just a shorthand way to create an instance of the class. It accepts a request which is type hinted on the method. I am trying to unit test this and the only way I know how is to make an answer and pass that through. That doesn't work tho because it is not a request. Is there a work around for this? Here is the method:
public static function generate(Question $question, Request $request): self
    {
        return self::create([
            'user_id' => Auth::user()->getKey(),
            'question_id' => $question->getKey(),
            'answer_body' => $request->answer_body,
        ]);
    }

Here is the test
/** @test */
    public function it_can_generate_a_new_instance()
    {
        $user = factory(User::class)->create();
        $this->actingAs($user);

        $question = factory(Question::class)->create();
        $answer = factory(Answer::class)->make();

        Answer::generate($question, $answer);

        $this->assertEquals($user->getKey(), Answer::first()->user_id);
        $this->assertEquals($question->getKey(), Answer::first()->question_id);
        $this->assertEquals($answer->answer_body, Answer::first()->answer_body);
    }

The test passes until I type hint Request in the method.

A: You can make a new request object with the given property. It's probably a bit flimsy but it should work:
public function it_can_generate_a_new_instance()
{
    $user = factory(User::class)->create();
    $this->actingAs($user);

    $question = factory(Question::class)->create();
    $answer = factory(Answer::class)->make();
    $request = new Request([ 'answer_body' => $answer->answer_body ]);

    Answer::generate($question, $request);

    $this->assertEquals($user->getKey(), Answer::first()->user_id);
    $this->assertEquals($question->getKey(), Answer::first()->question_id);
    $this->assertEquals($answer->answer_body, Answer::first()->answer_body);
}

A: a request should only be present on a controller, and not in the Model Answer (Or you will encounter errors like that ^^)
If your process require a request, then you should test an http request instead :

/** @test */
    public function it_can_generate_a_new_instance()
    {

       $user = factory(User::class)->create();
        $this->actingAs($user);

        $question = factory(Question::class)->create();
        $answer = factory(Answer::class)->make();

        $this->post(route('answer.store'), $answer->toArray());

        // Then your answer will be generated in your controller

        $this->assertEquals($user->getKey(), Answer::first()->user_id);
        $this->assertEquals($question->getKey(), Answer::first()->question_id);
        $this->assertEquals($answer->answer_body, Answer::first()->answer_body);

    }


text:
Q: Make exception when replacing diacritics with regular characters Trying to make an exception to all characters that have been converted to regular letters.
txtValue.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
As you can see, I replace all the special characters for normal letters, but now I would like to add an exception for the char "ç" and it's capital equivalent "Ç", which are u00e7 and u00c7 respectively.

A: The only simple way I see is not optimized but do the job properly :

const text = "Çééé éÇé àç" // test this string
  .replace(/\u00e7/g, '__minC__') // save wanted chars position
  .replace(/\u00c7/g, '__majC__')
  .normalize('NFD') // normalize to prepare diacritic edit
  .replace(/\p{Diacritic}/gu, '') // replace all diacritics
  .replace(/__minC__/g, 'ç') // restore wanted chars
  .replace(/__majC__/g, 'Ç')

  console.log(text)

In this case we use \p{Diacritic} from Unicode Property Escapes


text:
Q: Managing licenses for Office 365 in vb.net I am trying to run Office365 cmdlets in a vb.net webservice project.The code is:
Public Function ExcutePowershellCommands() As ObjectModel.Collection(Of PSObject)
    Try
        Dim userList As ObjectModel.Collection(Of PSObject) = Nothing

        Dim initialSession As InitialSessionState = InitialSessionState.CreateDefault()
        initialSession.ImportPSModule(New String() {"MSOnline"})

        Dim O365Password_secureString As New System.Security.SecureString()
        Dim O365Password As String = "password"
        For Each x As Char In O365Password
            O365Password_secureString.AppendChar(x)
        Next
        Dim credential As New PSCredential("username", O365Password_secureString)

        Dim connectCommand As New Command("Connect-MsolService")
        connectCommand.Parameters.Add((New CommandParameter("Credential", credential)))

        Dim getCommand As New Command("Get-MsolUser")

        Using psRunSpace As Runspace = RunspaceFactory.CreateRunspace(initialSession)

            psRunSpace.Open()

            For Each com As Command In New Command() {connectCommand, getCommand}
                Dim pipe As Pipeline = psRunSpace.CreatePipeline()
                pipe.Commands.Add(com)

                Dim results As ObjectModel.Collection(Of PSObject) = pipe.Invoke()
                Dim [error] As ObjectModel.Collection(Of Object) = pipe.[Error].ReadToEnd()
                If [error].Count > 0 AndAlso com.Equals(connectCommand) Then
                    Throw New ApplicationException("Problem in login! " + [error](0).ToString())
                    Return Nothing
                End If
                If [error].Count > 0 AndAlso com.Equals(getCommand) Then
                    Throw New ApplicationException("Problem in getting data! " + [error](0).ToString())
                    Return Nothing
                Else
                    userList = results
                End If
            Next

            psRunSpace.Close()
        End Using
        Return userList
    Catch generatedExceptionName As Exception
        Throw
    End Try
End Function

When Connect-MsolService is run, I get this error message:

There was no endpoint listening at https://provisioningapi.microsoftonline.com/provisioningwebservice.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.

I can run this function successfully within a windows App. I think some thing might be wrong in IIS. any idea?


text:
Q: How do i pass an id as a parameter for a function using the click eventListener in jquery? <script>
$( document ).ready(function() {
    //for example item is the button that will be clicked and panelContent is the panel that will be shown
    $('#item').click({param1: '#panelContent'}, toggleObjects);

    // i tried this also and it doesn't work
    $('#item').click(toggleObjects('#panelContent'));
});
var currentObject;
function toggleObjects(theObject) {
    //theObject is the id of the panel
    if(currentObject===null)
    {
        currentObject=theObject;
        $(currentObject).show();
    }
    if(currentObject===theObject)
    {
        $(theObject).toggle();
    }
    if(currentObject!==theObject)
    {
        $(currentObject).hide();
        currentObject=theObject;
        $(currentObject).show();
    }
    console.log( 'executed!' );
}
</script>

If i put onclick="toggleObjects('#panelContent')" on the button in html it works fine, but i would like to use the jquery event listener.
How should i use the .click event for passing the function and also the parameter?
 Or is there another solution besides the html onclick version ?
Please excuse my poor English!
Thank you in advance for your attention to this matter.

A: What it appears you want is either an in-line function--
$('#item').click(function() { toggleObjects('#panelContent'); } );

Or to define a new function that calls the toggleObjects function with the specific parameter --
var toggleObjectsWithPanelContent = function() {
  toggleObjects('#panelContent');
};
$('#item').click(toggleObjectsWithPanelContent);

.
You got close with $('#item').click(toggleObjects('#panelContent'));,
but the toggleObjects('#panelContent') bit is actually a function call there, not a reference to a function, so you're actually passing the return value of toggleObjects to the click() fn. (The return value in this case being undefined).

A: You are right but If you write like this
<input type="button " id="item" onclick="toggleObjects('panelContent');" />

pass the id not the id with #.
then it will hit the function toggleObjects in your script accepting the parameter you are passing .
If you want this using jQuery click event handler , then do this :-
 $("#item").click(function(){
     toggleObjects('panelContent');
 });

And if your button is being dynamically generated in the DOM , then use on-click event handler like this :-
 $("#item").on('click',function(){
     toggleObjects('panelContent');
 });

Just remember don't pass the id alongwith # . As i can see you are comparing that id with the currentObject in your toggleObject() and i hope that would not be something beginning with #.
But If the currentObject is beginning with # then , whatever you wrote in the HTML will work and for jQuery , instead of doing  toggleObjects('panelContent');  inside the click and on-click EVENT HANDLERS  just add # too at the beginning of panelContent ( toggleObjects('#panelContent'); )
Thanks !!


text:
Q: DateTime "invalid per syntax" in LDAP pwdLastSet attribute I'm trying to add a pwdLastSet attribute to my LDAP test user. I've created this ldif file:
dn: cn=test,dc=example,dc=com
changetype: add
objectClass: passwordLastSet
add: pwdLastSet
pwdLastSet: 199412161032Z

When I try to ldapmodify
sudo ldapmodify -Y EXTERNAL -H ldapi:/// -f add-pwdlastset.ldif

I get a error message:
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry "cn=test,dc=example,dc=com"
ldap_add: Invalid syntax (21)
   additional info: objectClass: value #0 invalid per syntax

I've looked up chapter 3.3.13 "Generalized Time" in RFC4517 which provides the following examples:
  Examples:
     199412161032Z
     199412160532-0500

Both example values represent the same coordinated universal time:
10:32 AM, December 16, 1994.

As you might notice, I even copy-pasted the first example to my ldif file, to no avail. Could someone enlighten me what's wrong with this syntax?
Forgot to mention that I also tried with a unix timestamp
pwdlastset: 1643988710

which yields the same error message.

Update:
When I change the changetype from add to modify and remove the objectClass (as suggested in EricLavault's answer) like this:
dn: cn=test,dc=example,dc=com
changetype: modify
add: pwdLastSet
pwdLastSet: 1643988710

I get the following error:
$ sudo ldapmodify -Y EXTERNAL -H ldapi:/// -f add-field.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "cn=test,dc=example,dc=com"
ldap_modify: Undefined attribute type (17)
    additional info: pwdlastset: attribute type undefined

When I then add the objectClass definition again like this
dn: cn=test,dc=example,dc=com
changetype: modify
objectClass: passwordLastSet
add: pwdLastSet
pwdLastSet: 1643988710

I get the following error:
$ sudo ldapmodify -Y EXTERNAL -H ldapi:/// -f add-field.ldif
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
ldapmodify: modify operation type is missing at line 3, entry "cn=test,dc=example,dc=com"

I tried some other modify operation types (replace), but nothing worked. Still stuck here.

A: The thing (which is not obvious at first glance) is that ldapmodify allows to add entries, in which case you set changetype: add.
You want to modify an existing entry, so you should set changetype: modify in order to add: pwdLastSet or (replace|delete).
If you also need to add objectClass: passwordLastSet to the entry or other changes, note that every operation (add|replace|delete) must be separated, eg.
dn: cn=test,dc=example,dc=com
changetype: modify
add: objectClass
objectClass: passwordLastSet
-
add: pwdLastSet
pwdLastSet: 199412161032Z

Also if I'm not wrong, the PwdLastSet attribute is only implemented in Active Directory.
If you are using OpenLDAP you should probably use the PwdPolicy auxiliary class (ppolicy overlay).


text:
Q: Get Values in Already Created Picklist im trying to retrieve the values in a picklist (using code) that was created without code. i want to be able to assign the already created values to a custom object's field in apex.
any idea how to retrieve those values below is my code
public class TestIMP {
// a class used to test any implementation
public static void mymethod(){

}

public static List<selectOption> returnPickList (sObject targetobject,  string objfield ){

    List<selectoption> options = new List<selectoption>();
    Schema.SObjectType objtype = targetobject.getSObjectType();
    schema.DescribeSobjectResult description = objtype.getDescribe();
    map<string, schema.SObjectField> fields = description.fields.getmap();

    List<schema.PicklistEntry> pickoptions = fields.get(objfield).getdescribe().getpicklistValues();

    for(schema.PicklistEntry a : pickoptions){

        options.add(new selectoption (a.getlabel(), a.getvalue()));

    }
    system.debug(options);
    return options;

}

}
then i opened an anonymous execution and tried to run it using this code..
    Account acct = new Account(Name='test');
   testImp.returnPickList(acct, acct.AccountSource);

im getting a null pointer error at this line
   List<schema.PicklistEntry> pickoptions = fields.get(objfield).getdescribe().getpicklistValues();

A: Its because you are passing wrong value in the method returnPickList
 Account acct = new Account(Name='test');
 testImp.returnPickList(acct, acct.AccountSource);

in the second line , you passing value of Account acct instance's value for AccountSource, as AccountSource was not instantiated, its value would be null and thus it gives you null pointer exception.
Fix: Provide String Constant field API name
 Account acct = new Account(Name='test');
 testImp.returnPickList(acct, 'AccountSource');


text: Q: Is there any domain $\Omega\subset\mathbb{R}^3$ with nontrivial homotopy group but with trivial first homology? I'm using the word domain relatively loosely here. Ideally, I mean by a domain $\Omega\subset\mathbb{R}^3$ the interior of a connected smooth 3-manifold with corners in $\mathbb{R}^3$, though if this question has an answer for any connected open $\Omega\subset\mathbb{R}^3$, that would of course also be good. I know that for general manifolds $M$, it is possible that $\pi_1(M)\ne 0$ but $H_1(M)=0$, but how about if we only consider the case for domains $\Omega\subset\mathbb{R}^3$? Does this remain true?


text:
Q: How to add a CSS class for the displayed discounted percentage near sale price on single product pages in WooCommerce I using "Display the discounted percentage near sale price in Single product pages for WC 3.0+" (Original answer code)
I used this code to show sale percentage after price on single product page. but I want to customize it - to give it background, paddings, etc...
So I need to include CSS class name in that function to be able to customize it via CSS
I want to add it only to "-percentage" (I don't want it to be applied neither to discounted or regular price)

A: Some additional information

*

*HTML  Tag

*HTML  Tag

*How TO - Add a Class
So you get
function woocommerce_custom_sales_price( $price, $regular_price, $sale_price ) {
    $percentage = round( ( $regular_price - $sale_price ) / $regular_price * 100 ).'%';
    $percentage_txt = '' . __('-', 'woocommerce' ) . $percentage . '';
    $price = '' . ( is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price ) . '
    ' . ( is_numeric( $sale_price ) ? wc_price( $sale_price ) . $percentage_txt : $sale_price . $percentage_txt ) . '';

    return $price;
}
add_filter( 'woocommerce_format_sale_price', 'woocommerce_custom_sales_price', 10, 3 );


text:
Q: WordPress Gutenberg, update post content programmatically I have been starting to testing out Gutenberg editor with both ACF and custom blocks. And I have been looking around to solve my problem but I couldn't find anything about this topic (Maybe my google skills is not good enought)
But my case is this:
I have a custom post type where I want to set a template so they can't move around the blocks and add other blocks and so on. And on this post type around 70% is created by code. Because it is fetching all the information from an API.
Test 1: I have created an ACF block with all the fields I need, and it is working as it should when I create a new post from WP admin. But when I run the update_field function it is saving it to post_meta table as it did before. So my question here is how do I update a field so it saves it to post_content and not to post_meta table.
Test 2: I created custom blocks for all of the fields (convert each ACF field to and block) and set up the template to use these blocks only.
But here I have no idea how update update post_content with PHP or Javascript.
I hope you can help me out with this :) If anything is unclear tell, and I will try to explain it

A: ACF has an ability to pre-init fields before post will be visible to user on post creation page. You can try to use this function to set desired content to fields.
You can read about this here:
https://www.advancedcustomfields.com/resources/acf-prepare_field/

A: As of Wordpress 5.0.0
You can use template and template_lock arguments upon registering your custom post type.

*

*Source @ https://developer.wordpress.org/reference/functions/register_post_type/#changelog
You can then set an array of specific blocks to use and you can chose to restrict users from adding new blocks or removing them.

Attribute
Description

template
(array) Array of blocks to use as the default initial state for an editor session. Each item should be an array containing block name and optional attributes.

template_lock
(string/false) Whether the block template should be locked if $template is set. If set to 'all', the user is unable to insert new blocks, move existing blocks and delete blocks. If set to 'insert', the user is able to move existing blocks but is unable to insert new blocks and delete blocks. Default false.

A short example would be something along the lines of...
<?php
$args = [
    //...
    'template_lock' => 'all',
    'template' => [
        [ 'core/paragraph' ],
        [ 'core/file' ],
        //...
    ],
    //...
];
register_post_type( $post_type, $args );
?>

Currently, Gutenberg documentation is scarced, you can find a complete list of blocks & parameters @ https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src

 Gutenberg is still in development, some features don't act as they should.


text:
Q: gnu_cxx::hash_map is behaving strangely I am trying to find an element in a gnu_cxx::hash_map that is keyed by strings. The string I am searching is "\xofiller!fill!1_620200 " (thereis only 1 backslash at the beginning.
The element is not found. So inside gdb I change the search key to "xofiller!fill!1_620200 " and the element is found but oddly the key of the pair found is the original on. "\xofiller!fill!1_620200 ". I am using std::equal_to which is really ==.
I experimented and I can lose a few characters at the end as well. I am starting to suspect that GDB is misleading me. Is there something special about a backslash at the beginning?
Thanks
Danny


text:
Q: How do I correct a NumberFormatException error? The error Exception in thread "main" java.lang.NumberFormatException: For input string: "triangle" occurs when I try to run my program. However, if i delete all of the items in Arrays.asList() no results or errors are produced.
This is part of my Helper class containing the issues.
public static void display(ArrayList<String> shapes) throws IOException, FileNotFoundException{

    java.util.List<String> list = Arrays.asList("rectangle", "circle","triangle");

    for(int i = 0; i<list.size(); i++)
        switch (list.get(i).toLowerCase())
        {
        case "rectangle":
            Rectangle rectangle = new Rectangle();
            rectangle.name = list.get(i+1);
            rectangle.setWidth(Double.valueOf(list.get(i+2)));
            rectangle.setLength(Double.valueOf(list.get(i+3)));
            System.out.print(rectangle);
            i = (i+3);
            break;

A: Adding comments to clarify what is happening. The NFE occurs when you try to set the width of your rectangle object.
public static void display(ArrayList<String> shapes) throws IOException,
FileNotFoundException{

    // index 0 = "rectangle", index 1 = "circle", index 2 = "triangle"
    java.util.List<String> list = Arrays.asList("rectangle", "circle","triangle");

    // on the first iteration i = 0
    for(int i = 0; i<list.size(); i++)
        // i is 0 so list.get(i).toLowerCase() = "rectangle"
        switch (list.get(i).toLowerCase())
        {
        // since switch (list.get(i).toLowerCase()) evaluates to "rectangle" we enter
        // this case statement
        case "rectangle":
            Rectangle rectangle = new Rectangle();
            // i is 0 so list.get(i+1) = "circle", this probably isn't desired
            // behavior
            rectangle.name = list.get(i+1);
            // i is 0 so list.get(i+2) = "triangle", "triangle" can't be converted to
            // a double because it's not a number a NumberFormatExpection is thrown
            rectangle.setWidth(Double.valueOf(list.get(i+2)));
            // i is 0 so we can't determine what element is in the list at index 3
            // because it doesn't exist an ArrayIndexOutOfBoundsException is thrown
            rectangle.setLength(Double.valueOf(list.get(i+3)));
            System.out.print(rectangle);
            // not sure what this is doing
            i = (i+3);
            break;


text:
Q: Sharepoint Webservice 401 error I'm trying to call sharepoint webservices in C# console application. The code works fine when I use my local system's WSS as target application but don't work with another server accessible over the web. Following is my code.
Webs service = new Webs();
            service.PreAuthenticate = true;
            service.Credentials = new System.Net.NetworkCredential(login, password);
            //service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

            service.Url = url + @"/_vti_bin/webs.asmx";

            XmlNode sites = null;

            try
            {
                sites = service.GetWebCollection();
            }
            catch (Exception ex)
            {
                return;
            }

Points to note:
1. It neither work with DefaultNetworkCredentials nor with my domain user credentials.
2. The webservice end point if pasted in a browser successfully list the web service methods.
3. I get 401 unauthorized error in all cases(accessing the remote server).
Am I missing something?

A: Use a tool like Fiddler to capture the http traffic between console app and SharePoint.  That will help debug what your problem is.

A: Did you check your App pool account? May be your application pool account does not have enough rights. Change your application pool account to an account that has full permissions on your site and try again. It should work.
I also found that this could be a known issue if you install Microsoft Windows XP Service Pack 2 (SP2) or Microsoft Windows Server 2003 Service Pack 1 (SP1). To solve this, you can follow the steps in this KB article - http://support.microsoft.com/?scid=kb;en-us;896861&x=14&y=17.


text:
Q: Ubuntu 17.04: Terminal not opening when clicked on - how get terminal to work properly? The terminal icon is present, but the terminal does not open when clicked on. How do I get the terminal to open and work?

A: If you are in the desktop, you can try Alt+F2, and then type gnome-terminal and then Enter to see if you can get it fired up.
If for some reason gnome-terminal does nothing, try the same thing but this time using xterm

A: You should always consider the possibility that you don't have malware but did something wrong yourself, in which case it should be possible to fix it with normal commands.
If you indeed got malware on your computer, stop using the installed operating system ASAP.
Boot the computer from a live CD/DVD and save the files that you need to an external drive (an USB stick for example). Be careful not to copy executables or scripts that may be part of the malware.
After everything is saved, do a complete reinstall of the operating system (the current version, not 17.04 again), create the user account and copy the files you need back to the disk. If you preserved the directory structure of your home directory, desktop files should appear on the desktop again.
If you're unsure about how to do all of this, get someone knowledgeable to help you. They will appreciate receiving a favor in return, some won't even say no to some money :-)


text:
Q: Simple form error messages moving input boxes I'm having an issue with the way that error messages are formatted on my "registration" form, using the simple_form gem.
This is what my registration form looks like when handling errors.
I want the error messages to appear below the input boxes, and I don't want the alignment of the input boxes to change when incorrect input is submitted. The input and error messages are structured as seen below:
        <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
        <%= f.error_notification input_html: { class: 'error' } %>
        <div class="panel-body">
          <%= f.input :email, required: true, autofocus: true, label: false, placeholder: 'Email', input_html: { class: 'input-lg' } %>
          <%= f.input :user_name, required: true, label: false, placeholder: 'User Name', input_html: { class: 'input-lg' } %>
          <%= f.input :password, required: true, label: false, placeholder: 'Password', input_html: { class: 'input-lg' } %>
          <%= f.input :password_confirmation, required: true, label: false, placeholder: 'Confirm Password', input_html: { class: 'input-lg' } %>

Is there something I can adjust in my css to make the error messages appear in the center below the input boxes? I have tried messing around with the margins, but when I do, the input boxes change alignment.

A: Found the solution, it was pretty simple. Just had to edit the CSS as follows:
.error {
    display: block;
    text-align: center;
}


text:
Q: Use a categorical argument to add one layer of list structure Consider the following nested list
x = {{1,2,a}, {3,4,a}, {8,11,b}, {12,3,a}, {4,3,b}, {3,2,c}}

I want to use the categorical variable [a,b,c] in order to group the above sublists (resulting in a list with "3 degrees of nestedness"). For the above example the goal is to obtain:
{ { {1,2},{3,4},{12,3} }, { {8,11},{4,3} }, {3,2} }

, where the first nested sublist is the group of sublists in x that contained the argument a, the second nested sublist is the group of sublists in x that contained the argument b and the third sublist is the group of sublists in x that contained the argument c

A: x = {{1, 2, a}, {3, 4, a}, {8, 11, b}, {12, 3, a}, {4, 3, b}, {3, 2, c}};

f = Map[Most, GatherBy[#, Last], {2}] &;
(* or f = Most /@ # & /@ GatherBy[#, Last] & *)

f@x
(* {{{1,2},{3,4},{12,3}},{{8,11},{4,3}},{{3,2}}} *)

or
f2 = Map[Most, SplitBy[SortBy[#, Last], Last], {2}] &;
(* or f2 = Map[Most, SplitBy[#[[Ordering[Last /@ #]]], Last], {2}] &; *)

f2@x
(* {{{1,2},{3,4},{12,3}},{{8,11},{4,3}},{{3,2}}} *)

Note: Under this method, the ordering of the elements within each category may change (thanks: @Michael E2).
Version 10:
f3 = Values@GroupBy[#, Last->Most]&
f3@x
(*  {{{1,2},{3,4},{12,3}},{{8,11},{4,3}},{{3,2}}} *)

A: f[l_List, cats_List] := Cases[l, p : {__, #} :> Most@p] & /@ cats
f[x, {a, b, c}]
(* {{{1, 2}, {3, 4}, {12, 3}}, {{8, 11}, {4, 3}}, {{3, 2}}} *)

It will ignore the "categorical" variables not included:
f[x, {a, b}]
(* {{{1, 2}, {3, 4}, {12, 3}}, {{8, 11}, {4, 3}}}*)

A: groupCategorically[ll_List, keys_List] :=
 keys /. GroupBy[ll, Last] /. Thread[keys :> Sequence[]]

Example:
groupCategorically[{{1, 2, a}, {3, 4, a}, {8, 11, b}, {12,
   3, a}, {4, 3, b}, {3, 2, c}}, {a, b, c}]

(* Out[156]= {{{1, 2}, {3, 4}, {12, 3}}, {{8, 11}, {4, 3}}, {{3, 2}}} *)

A: DeleteCases[GatherBy[x, Last], _Symbol, -1]
(*{{{1, 2}, {3, 4}, {12, 3}}, {{8, 11}, {4, 3}}, {{3, 2}}}*)


text:
Q: Send mail using msbuild I have been trying to find out if MSbuild can send an email to the developers just like NANT.
I don't see any option in mSbuild.

A: There is an email task in the  MSbuild Community Tasks collection. This is a set of open source MSBuild tasks - lots of goodies there.

A: I know that this has already been answered, but if you install the power tools you get an alerts option in the Team Explorer.
That alerts has several TFS Based options to send emails (on fail, on succeed).


text:
Q: Java Graphic2D, scaled shape and mouse Hi everybody I have a piece of code that can zoom some shapes into a restricted area but when zooming I can't click the shapes, what can I do for? I can clicked in the old area in the original location.
The code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class ZoomDemo extends JPanel implements Runnable {

AffineTransform tx = new AffineTransform();
Rectangle2D.Double rect1 = new Rectangle2D.Double(100, 100, 30, 60);
Rectangle2D.Double rect2 = new Rectangle2D.Double(150, 250, 60, 40);

public ZoomDemo() {
    this.addMouseWheelListener(new ZoomHandler());
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;

    g2.drawRect(100, 100, 100, 100);
    g2.setClip(100, 100, 100, 100);
    g2.setColor(Color.RED);
    g2.draw(tx.createTransformedShape(rect1));
    g2.setColor(Color.BLUE);
    g2.draw(tx.createTransformedShape(rect2));
}

private class ZoomHandler implements MouseWheelListener, MouseListener {

    double scale = 1.0;

    public ZoomHandler() {
        addMouseListener(this);
    }

    public void mouseWheelMoved(MouseWheelEvent e) {
        if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {

            Point2D p1 = e.getPoint();
            Point2D p2 = null;
            try {
                p2 = tx.inverseTransform(p1, null);
            } catch (NoninvertibleTransformException ex) {

                ex.printStackTrace();
                return;
            }

            scale -= (0.1 * e.getWheelRotation());
            scale = Math.max(0.1, scale);

            tx.setToIdentity();
            tx.translate(p1.getX(), p1.getY());
            tx.scale(scale, scale);
            tx.translate(-p2.getX(), -p2.getY());

            ZoomDemo.this.revalidate();
            ZoomDemo.this.repaint();
        }
    }

    @Override
    public void mouseClicked(MouseEvent me) {
        System.err.println("click");
        if(rect1.contains(me.getPoint())){
            System.err.println("asdasdsd");
        }
    }

    @Override
    public void mousePressed(MouseEvent me) {

    }

    @Override
    public void mouseReleased(MouseEvent me) {

    }

    @Override
    public void mouseEntered(MouseEvent me) {

    }

    @Override
    public void mouseExited(MouseEvent me) {
    }
}

public void run() {
    JFrame f = new JFrame("Zoom Demo");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(this);
    f.setSize(600, 600);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new ZoomDemo());
}
}