text:
Q: Form submission returns inputs Laravel I'm trying to create a submission form, if a user submit the form it should redirect him to the next page which is in confirmation controller. So far it redirects back with the inputs like this
{"shipping_city":"gfg","shipping_phone":"087484","shipping_name":"Hellle",}
Here is my code
CheckoutController
 public function store(Request $request)
 {
    foreach(session('cart')  as $productId =>$item);
    $product = product::find($productId);
    //Insert into orders table
    $order = Order::create([
        'shipping_city' => $request->city,
        'shipping_phone' => $request->phone,
         'shipping_name' => $request->name,
    ]);

    if ($order) {
        foreach(session('cart')  as $productId =>$item) {
           if (empty($item)) {
               continue;
           }
           $product = product::find($productId);
           OrderProduct::create([
            'order_id' => $order->id ?? null,
            'product_id' => $productId,
            'quantity' => $item['quantity'],
        ]);
       }
       return $order;
    }
    $cart = session()->remove('cart');
     return redirect()->route('confirmation.index');
   }

Checkout.blade
    <form action="{{ route('checkout.store') }}" method="POST" id="payment-form">
        {{ csrf_field() }}

            Name
            <input type="text" class="form-control" id="name" name="name" value="{{ auth()->user()->name }}" required>

                City
                <input type="text" class="form-control" id="city" name="city" value="{{ old('city') }}" required>

                Phone
                <input type="text" class="form-control" id="phone" name="phone" value="{{ old('phone') }}" required>

        <button type="submit" id="complete-order" class="buttons-primary full-width">Complete Order</button>
    </form>

ConfirmationController
  public function index()
 {
    {
        if (! session()->has('success_message')) {
            return redirect('/');
        }

        return view('thankyou');
    }
 }

Routes
 Route::post('/checkout', 'CheckoutController@store')->name('checkout.store');

Any help will be appreciated.

A: Let's take a look at what your code currently does and what you want it to do:
Current Code with comments:
public function store(Request $request) {
    foreach(session('cart')  as $productId =>$item);
    $product = product::find($productId);
    //Insert into orders table
    $order = Order::create([
        'shipping_city' => $request->city,
        'shipping_phone' => $request->phone,
        'shipping_name' => $request->name,
    ]);

    if ($order) { // If a new order was successfully created
        foreach(session('cart')  as $productId =>$item) {
           // Do some stuff with each item / product
        }
        return $order; // return the newly created order with it's data
    }
    // If we didn't created a new order for whatever reason
    $cart = session()->remove('cart');
    return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
}

As you can see, you just return the data of the created order (when $order is not false), otherwise you redirect to the "confirmation.index" page. Since this always does the opposite of what it should do (returning the order although you should be redirected to the confirmation page and vice versa), you have to swap the cases:
public function store(Request $request) {
    ...
    if ($order) { // If a new order was successfully created
        foreach(session('cart')  as $productId =>$item) {
           // Do some stuff with each item / product
        }
        $cart = session()->remove('cart');
        return redirect()->route('confirmation.index'); // Redirect user to the "confirmation.index" route
    }
    // If we didn't created a new order for whatever reason
    return false; // return something else, since we didn't create an order
}


text:
Q: Does Ubuntu have kernel config requirements? I'm building a stripped-down variant of the kernel for an arm-based device and I want to use Ubuntu there. Does Ubuntu require some specific kernel options to be set? Also, is it necessary to apply Ubuntu's own patchset on top of the kernel (similar to https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.3.12/ for 5.3.12)?
I'm aware of https://wiki.ubuntu.com/Kernel/BuildYourOwnKernel, but modifying existing config is harder than writing it based on default one (since Ubuntu tries to be universal and includes a lot of modules). It takes ages to build and just wastes the space (which is scarce).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Check if record exists in Model Rails I was wondering if i would need to create a custom validation for the following scenario.
I have a Prediction model, in which a user submits their predicted scores for a set of football matches, they are grouped by fixture_date.
If a user has already submitted predictions for these games already i would like to show an error message stating they are unable to submit as the error exists, or maybe not show the form if the predictions for the dates exist.At the moment I can create multiple sets of predictions for the same games. Probably the validation would be better. How would i go about stating that if a prediction exists for that date for the current_user then do not submit?
So my setup looks like this so far
class Prediction < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :home_score, :away_score, :fixture_date,   :fixture_id, :user_id

has_one :fixture
end

class Fixture < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :fixture_date, :kickoff_time, :prediction_id
end

Predictions Controller
 def index
   @predictions = current_user.predictions if current_user.predictions
 end

 def new
   @prediction = Prediction.new
 end

 def create
  begin
  params[:predictions].each do |prediction|
    Prediction.new(prediction).save!
  end
  redirect_to root_path, :notice => 'Predictions Submitted Successfully'
rescue
  render 'new'
 end
end
end

A: Im not sure about the relation between predictions and games. Do you have a Game model? If so then something like this should work:
class Prediction < ActiveRecord::Base
  attr_accessible :home_team, :away_team, :home_score, :away_score, :fixture_date, :fixture_id, :user_id

  has_one :fixture

  validates :fixture_id, :uniqueness => { :scope => :user_id,
:message => "only one prediction per game is allowed, for each user" }
end


text:
Q: R - group specific list items I have a character data that looks like this:
  x= c("Clause 1 - AGREEMENT. Buyer agrees to buy, and Seller agrees to sell, the Property described below on the terms and conditions set forth in this contract.",
       "Clause 2 - Buyer. Buyer, will take title to the Property described below:",
      "Item 2.1 - Seller. Seller, is the current owner of the Property described below assignable by Buyer without Seller's prior written consent.",
       "Clause 3 - Inclusions. The Purchase Price includes the following items: ",
       "Item 3.1 - Fixtures. If attached to the Property on the date of this Contract, the following items are included unless")

I am tryng to group all Items into the Clauses in a list. Basically, I want it to do this
x[grep("Clause . - ", x)]= c(x[1], paste(x[2], x[3]), paste(x[4], x[5]))

and this
x= x[grep("Clause . - ", x)]

but dynamically. How can I do it without specifyng the list items i want to combine? Thank you all.

A: First strip out just the numbers:
> nums <- gsub("^..* (\\d+\\.*\\d*) -..*$", "\\1", x, perl = T)
> nums
[1] "1"   "2"   "2.1" "3"   "3.1"

Group them by dropping the decimal place:
> nums <- as.integer(nums)
> nums
[1] 1 2 2 3 3

Loop over these groupings and paste them together:
> grouped <- tapply(x, nums, paste, collapse='\n')
> cat(grouped[2])
Clause 2 - Buyer. Buyer, will take title to the Property described below:
Item 2.1 - Seller. Seller, is the current owner of the Property described below assignable by Buyer without Seller's prior written consent.

A: I solved my problem adapting the answer provided by Zelazny. With the data:
> x= c("Clause 1 - AGREEMENT. Buyer agrees to buy",
        "Item 1.2 - Seller agrees to sell",
        "Item 1.2 - the Property described below",
        "Item 1.3 - on the terms and conditions set forth in this contract",
        "Item 1.4 - If attached to the Property on the date of this Contract",
        "Item 1.5 - the following items are included:",
        "I - property",
        "II - car",
        "III - motorcycle",
        "Clause 2 - Buyer, will take title to the Property described below:",
        "Item 2.1 - Seller. Seller, is the current owner of the Property",
        "I - this is binding contract",
        "Item 2.2 - by Buyer without Seller's prior written consent.",
        "Clause 3 - The Purchase Price includes the following items",
        "Clause 4 - property will be transmited",
        "Clause 5 - as discribed in",
        "Each party is signing this agreement on the date stated opposite that party's signature.",
        "city, date")

First find the items that are clauses:
> f= grep("Clause . - ", x)
> f
[1]  1 10 14 15 16

As the rep dosn't allow a list of times, loop over and repeat the previous item number for all the missing itens:
> nums= f
> for (i in 1:length(f)-1){
>    a= f[i+1]-f[i]-1 #times to repeat the number
>    nums= c(nums, rep(f[i], times= a))
> }
> sort(nums)
 [1]  1  1  1  1  1  1  1  1  1 10 10 10 10 14 15 16

Add all the numbers after the last clause:
> nums= sort(c(nums, (1+f[length(f)]):length(x)))
> nums
 [1]  1  1  1  1  1  1  1  1  1 10 10 10 10 14 15 16 17 18

And finally group the items in the clause:
> grouped <- tapply(x, nums, paste, collapse='\n')
> cat(grouped[1])
 Clause 1 - AGREEMENT. Buyer agrees to buy
 Item 1.2 - Seller agrees to sell
 Item 1.2 - the Property described below
 Item 1.3 - on the terms and conditions set forth in this contract
 Item 1.4 - Fixtures. If attached to the Property on the date of this Contract
 Item 1.5 - the following items are included:
 I - property
 II - car
 III - motorcycle


text:
Q: DC-DC Converter - Why is the input voltage called Vg? In the textbook I'm reading (Fundamentals of Power Electronics 2nd Ed, Erickson and Maksimovic), the input voltage for several different types of converter circuits is labeled Vg. The textbook gives no explanation for what the g refers to. Does anyone know?

A: Voltage generator, maybe? I used this text in school and they use the Vg nomenclature from the get-go. I don't think there's anything special about it.
On page 3, they introduced Vg for the first time:

So Vg is just the way they call the input voltage to the converters in the text.


text:
Q: Android SQLite Insert-Select There are two different methods for inserting a row into table:

*

*execSql, using it I can execute sql statements with SELECT - INSERT. But it doesn't return id of new row.

*different inserts - I can get insert-id here, but I can't create insert queries with substitution values from another table.

I can split my query into two, but isn't it slower, than one query?

A: Do your insert however you like, then execSql "select last_insert_rowid()".


text:
Q: Why is TextWriter.Write(char) not abstract? TextWriter is an abstract class with one abstract function - Encoding Encoding { get; }. Implementations must also implement void Write(char), but this function is not abstract - why? The default implementation does nothing which for me does not make sense.

A: It's a design error in TextWriter. According to Reflector, all other Write* methods reduce to  Write(char). The documentation says something similar. Write(char) should be abstract.
A developer not noticing this might be mislead to create an implementation that mostly works, but when writing a char (which is uncommon) it might do nothing. Surprising behavior.
If you derive from TextWriter and you know that callers will only use certain overloads such as Write(string) you can save some work by only overriding the necessary methods and ignoring Write(char). That, however, violates the Liskov substitution principle. Back when the BCL was designed they might not have taken a strict stance on the SOLID principles.
The reference source is not enlightening:
    // Writes a character to the text stream. This default method is empty,
    // but descendant classes can override the method to provide the
    // appropriate functionality.
    //
    public virtual void Write(char value) {
    }


text:
Q: Dynamically navigating through n categories I'm trying to create my first iOS project. I have quite well experiences with C#. I receive data with categories and articles. But I don't know, how many subcategories I will get, before the articles will be listed. The browsing though the subcategories should be done via TableView. When a User clicks a category, the subcategories (level 1) should be displayed in a tableView. Then, after touching a subcategory, the subcategories (level 2) of present should be displayed (and so on). Lastly, when there are no further subcategories, the article-list should be displayed. After touching one article, a new ViewController with the article-data should be displayed.
My question is, how to handle the navigation through the subcategories and creating segues or sth. like that. I know, that I can't use storyboard for this, because I don't know the number of subcategories and they also differ.
How can I achieve this dynamic navigation? Can you give me an example? I know how to populate data to the tableView. Only the dynamic navigation is the problem.

A: I now have a solution. Can someone please check, if I am doing it correctly not that I don't violate programming patterns or guidelines.
In short: In TableSource-Class I access the Storyboard and dynamically create and show the same Controller which actually is presented. But before presenting the new one, I declare an other source-class. So the TableView is used for displaying Addressbooks and Addresscards, the UIViewController is used for displaying the carddata. These two controllers are connected via segue.
Here are my Controller and both Source-Classes:
AddressbooksController.cs
public AddressbooksController (IntPtr handle) : base (handle)
    {
        displayModel = "addressbooks";
    }

    private void loadAddressbooks()
    {
        var AppDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
        addressbooks = AppDelegate.api.DeserializeEntities<YAddressbook>(Task.Run(async () => await AppDelegate.api.Get("Yaddressbooks")).Result);
    }

    public void loadAddresscards()
    {
        var AppDelegate = UIApplication.SharedApplication.Delegate as AppDelegate;
        addresscards = AppDelegate.api.DeserializeEntities<Ycard>(Task.Run(async () => await AppDelegate.api.Get("Ycards")).Result);
    }

    public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
    {
        base.PrepareForSegue(segue, sender);

        // do first a control on the Identifier for your segu
        if (segue.Identifier.Equals("segueShowAddress"))
        {

            var viewController = (AddresscardController)segue.DestinationViewController;
            viewController.card = Card2Display;
        }
    }

    public override void ViewDidLoad()
    {
        if (displayModel == "addressbooks")
        {
            loadAddressbooks();
            tableView.Source = new AddressbooksTableSource(addressbooks.data, this);
            this.NavigationController.Title = "Addressbücher";
        }
        else if (displayModel == "addresscards")
        {
            loadAddresscards();
            tableView.Source = new AddresscardsTableSource(addresscards.data, this);
            this.NavigationController.
        }

        base.ViewDidLoad();
    }

AddressbooksTableSource
public class AddressbooksTableSource: UITableViewSource
{

    private List<YAddressbook> addressbooks;
    private string cellIdentifier = "AddressbooksCell";
    private UINavigationController navigationController;

    public AddressbooksTableSource(List<YAddressbook> books, AddressbooksController ab)
    {
        addressbooks = books;
        this.navigationController = ab.ParentViewController as UINavigationController;
        Console.WriteLine(ab.displayModel);
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        Console.WriteLine("Row selected" + addressbooks[indexPath.Row].displayname);
        UIStoryboard Storyboard = UIStoryboard.FromName("Main", null);

        AddressbooksController newab = Storyboard.InstantiateViewController("AddressbooksViewController") as AddressbooksController;
        newab.displayModel = "addresscards";
        navigationController.PushViewController(newab, true);

        tableView.DeselectRow(indexPath, true);
    }

    ....
}

AddresscardsTableSource
public class AddresscardsTableSource: UITableViewSource
{
    private List<Ycard> addresscards;
    UINavigationController navigationController;
    AddressbooksController ab;
    string cellIdentifier = "AddresscardCell";

    public AddresscardsTableSource(List<Ycard> cards, AddressbooksController vc)
    {
        addresscards = cards;
        navigationController = vc.ParentViewController as UINavigationController;
        ab = vc;
        //navigationController = tableview;
    }

    public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
    {
        Console.WriteLine("Row selected" + addresscards[indexPath.Row].carddata);
        //UIStoryboard Storyboard = UIStoryboard.FromName("Main", null);

        ab.Card2Display = addresscards[indexPath.Row];
        ab.PerformSegue("segueShowAddress", indexPath);

        //AddresscardController ab = Storyboard.InstantiateViewController("AddresscardViewController") as AddressbooksController;
        //ab.TableView.Source = this;
        //navigationController.PushViewController(ab, true);

        tableView.DeselectRow(indexPath, true);
    }

    .....

}

It works. But am I doing it correctly? Thanks


text:
Q: How do I dynamically route through a list of objects in Angular.js? How can I make this  tag link to a template that then dynamically populates data based on what project it is linked to?
I am able to link to any URL like '/skreens', '/viewpoint', or '/dogedots' through the 'project.html' view,
 but the template will not dynamically populate the expressions within that template.
This is my list of projects.

  {{project.title}}

And this is the view they link to (project.html)

{{project.title}}
 //right now nothing appears here :(

The  link populates its href with static data loaded from
angular.module('MyWeb', ['ngRoute'])
  .config( ['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/viewpoint', {
            templateUrl: '/myWebpage/app/templates/project.html'
            controller:'MainControl'
        })
        .when('/dogedots', {
            templateUrl: '/myWebpage/app/templates/project.html',
            controller:'MainControl'
        })
        .when('/skreens', {
            templateUrl: '/myWebpage/app/templates/project.html'
            controller:'MainControl'
        })
        .otherwise({
            redirectTo: '/',
            templateUrl: '/myWebpage/app/templates/portfolio.html'
        })
  }])
  .controller('MainControl', function($scope){
      $scope.projects = [
         { "id": 0, "linkUrl": "skreens", "title": "Skreens"},
         { "id": 2, "linkUrl": "viewpoint", "title": "ViewPoint Cloud"},
         { "id": 1, "linkUrl": "dogedots", "title": "Doge Dots"}
      ]
  })

controller:'MainControl'
but the projects data will not populate the template t

A: First, to link using ng-router, you should use ng-href="{{project.linkUrl}}". The way you have it defined right now will not work.
As far as the value not showing properly, from what you've posted it doesn't show that you are binding your controller to a view anywhere. This should happen in the .when object. Ex. .when('/portfolio', {
  controller:'MainControl',
  templateUrl:'/myWebpage/app/templates/portfolio.html'
})


text:
Q: List w/ Versioning on requires delete permission? So to use the multiline text field with append changes, I turned on the versioning setting for my list. However since doing so, users without delete permissions (custom contribute level without delete) can no longer open Display or Edit forms.
I can't see anything in the versioning settings that would prevent their view/edit of list items, nor have I seen documentation that supports the requirement to have Delete permissions for lists with versioning enabled.
Am I mistaken, or is there a work-around?

A: To your custom contribute level, add the permission "View Versions". This enables user of the group to view versions and edit items. They can't delete items nor versions, if you don't allow them to.
More to read: Create custom permissions - for SharePoint


text:
Q: Power problems related to copper wires and pigtails I am using a battery to power a odroid which requires 5V/4A. The battery voltage when measured using a multimeter was around 26.7.
I had two setups:

*

*I used a 1 sq mm copper current carrying wire to connect between the battery and dc converter (24V-5V) and a pigtail to power the odroid and it worked.

*In this one I had replaced the 1 mm sq copper wire with a 2.5 mm sq copper wire but the board doesn't seem to get started.

Is their anything I had missed out regarding the copper wires in the 2nd setup?


text:
Q: Update Flatlist when state array change on Functional component I have this code below, when the socket event is activated it is supposed to update the list (which is not happening), I've searched everywhere but I couldn't find how to make this list update, can anyone help me?
const [globalMessages, setGlobalMessages] = useState([]);
const chatList = useRef(null);

useEffect(()=>{
  socket.on("GlobalMessage", (globalMessageData) => {
     console.log(globalMessages.length)
     globalMessages.push(globalMessageData)
     setGlobalMessages(globalMessages)
  });
},[])

<FlatList
  ref={chatList}
  onContentSizeChange={() => chatList.current.scrollToEnd() }
  onLayout={() => chatList.current.scrollToEnd() }
  data={globalMessages}
  extraData={globalMessages}
  keyExtractor={message => message._id}
  renderItem={(message) =>  {
     return (
        <ChatBubble
           text={message.item.text}
           from={message.item.user.name}
           datetime= {message.item.createdAt}
           myId={playerData.id}
           msgfromId={message.item.user._id}
           containerStyle={styles.msgContainer}
           smallTextColor= "#6B6B6B"
           msgTextColor= "white"
        />
     )
  }}
/>

A: I changed this inside socket.on
setGlobalMessages([])
setGlobalMessages(globalMessages)

and it worked as it should


text:
Q: info frame vs Tcl_Eval I want to know invocation line number of proc. When file is sourced from tclsh
I can put in my proc
set infoFrame [info frame -1]
set line [dict get [info frame -1] line]

and this will get the line I need. However when I read file from C program and call Tcl_Eval info frame returns "type proc" instead of "type source" and the line number becomes relative to calling proc.
Is there something I can do before Tcl_Eval to specify that I am actually sourcing a file and make info frame behave like file is sourced.
I think Tcl_EvalFile will solve the problem but since the file is already in memory why to read it again. (I have to read content of file in memory)

A: I'm sorry, but no. The internal API you'd need access to in order to make that work is pretty awful, unfortunately, and there are no plans at the moment to expose anything to allow you to improve upon it. Writing to a file is the best approach for now.
Though if you mount a VFS, that writing to a file could be no big deal.


text:
Q: Can we get windows phone device temprature, air pressure, humidity , Infrared Sensor in c# Is there any way to check the following in windows phone 8.1?

*

*Infrared Sensor

*Windows phone device temperature.

*Heart Rate, SPO2, and Uv Sensor

*Pedometer

A: *

*No, there isn't an api for this.

*System temperatures are handled by the OS, I don't see why you'd need this. Also, it isn't available.

*These are accessible through the Band (2) SDK, found on http://developer.microsoftband.com/bandSDK

*Again, available through the Band SDK, although I am not sure if Microsoft Health supports this without a Band.


text:
Q: What are some examples of image effects (css) I am wondering what image effects can be done via css, such as the glint from Minecraft. Is there any way to do this, or similar, effects?

A: Try this script in CSS: http://una.im/CSSgram/
You can replicate the Instagram's filter with only a class!


text:
Q: Ways to Draw and Redraw / update just the Content (not the background) components of JPanel? I am creating a graph plotter that plots (draws) datapoints & lines based on periodically updating data points.
I am using a JPanel inside a JFrame as the drawing canvas.
The JPanel contains the line axis & other info (scales etc) as background. It also contains the updating data points as the content.
I would like to update the content of the JFrame periodically, after the new data is fetched.
The data points fetching part is complete & works fine.
This is my code: http://pastebin.com/SAEjNT1R , http://pastebin.com/WvPTyEfR (The panel class).
Main:
Panel object class:
This the the OraclePinger package (not really required, in case u wanna run) : At pastebin Wdmd3q1t (Connector class), MycAgyu3 (Target class)
Originally by Oracle - modified by me : docs.oracle.com/javase/1.4.2/docs/guide/nio/example/Ping.java
I am just confused with the JPanel drawing part. I would like to be able to draw the background once, then periodically refresh/clear & redraw the contents.
---Say if it's not possible to separate the background & content while refreshing.. that we only can clear all Components in the panel. Can I at least make a call to something like panel.clearAllComponents(); panel.draw(TheBackGround+Content) (repeatedly) from the Main
How can I solve this ?
Thanks

A: I can't look at links due to work related firewall restrictions but regardless, since you're asking volunteers for free advice, you really should be posting pertinent code here so as to make it as easy as possible for us to help you.
That being said, draw the invariant parts of your graph on a BufferedImage that is shown in the JPanel's paintComponent method, and then draw the changing parts in the JPanel's paintComponent method, possibly by looping through an ArrayList of data points.

A: If you are using JFreeChart, here's a related example that uses a javax.swing.Timer to pace the animation. Note that JFreeChart updates the entire plot on each increment by design.


text:
Q: WAZUH All Commands monitor How to monitor each and every command executed by user, even in sudo level.
I have configured audit rules and they are appearing in audit.logs, but I want to view each command timely from server to Kibana/wazuh manager.
enter image description here

A: Auditd share complete commands and users UID too with wazuh if configured properly.
So I just added those columns from list in Kibana and now data is apearing fine.


text:
Q: NullInjectorError when using inject() in runInContext The following code is triggering NullInjectorError when i'm calling @inject() in runInContext.
This does not happen if the service is providedIn: 'root' or passed in the module providers.
Any idea why ?
@Injectable()
class Service {}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [Service],
})
export class AppComponent {
  name = 'Angular ' + VERSION.major;

  public constructor(service: Service, injector: EnvironmentInjector) {
    console.log(service); // OK
    console.log(inject(Service)); //OK

    setTimeout(() => {
      injector.runInContext(() => {
        console.log(inject(Service)); //KO
      });
    }, 1000);
  }
}

Stackblitz

A: Per Angular#47566, this is currently as design but could be improved.
So wait & see.


text:
Q: send the POST without URLencoding the data I post a form,and the value is
<

But It last be enocded
%3C

So,how I keep <? or send the POST  without URLencoding the data.

A: Try changing your forms enctype value to text/plain. The only encoding done by that is to replace spaces with + symbols.


text:
Q: Is it possible to match on the type of a manifest in Scala? I'm writing some code in Scala that depends a the type parameter that I can't see on an argument.
def read[T](json: String)(implicit m: Manifest[T]): T = {
  if (m <:< manifest[Map[String, Any]]) {
    JsonParser.jsonToMap(json).asInstanceOf[T]
  } else {
    throw new UnsupportedOperationException("Not implemented for type %s".format(m))
  }
}

Apart from the fact that I'm writing my own json framework, which is probably a pretty bad idea...
Can I use a case statement instead of the if statements, or should I be thinking in a different direction?

A: A much better idea in situations like these where you feel tempted to use sequences of tests against manifests or classes (or type casing more generally) is to use a type class. In this particular case it would look like,
// Type class
trait JsonReader[T] {
  def apply(json : String) : T
}

// Type class instance for type Map[String, Any]
implicit def mapReader = new JSonReader[Map[String, Any]] {
  def apply(json : String) =
    JsonParser.jsonToMap(json).asInstanceOf[Map[String, Any]]
}

def read[T](json : String)(implicit reader : JsonReader[T]) : T = reader(json)

You should add type instances for all of the types that you care about.
You can now call your read function as follows,
read[Map[String, Any]](... some json ...)

Note that now if you attempt to call it with a type parameter corresponding to a type for which you haven't provided a type class instance the result will be an error at compile time rather than an UnsupportedOperationException at runtime.


text:
Q: Get start date & end date from the range of timestamp I have a dataframe in Spark (Scala) from a large csv file.
Dataframe is something like this
key| col1 | timestamp            |
---------------------------------
1  | aa  | 2019-01-01 08:02:05.1 |
1  | aa  | 2019-09-02 08:02:05.2 |
1  | cc  | 2019-12-24 08:02:05.3 |
2  | dd  | 2013-01-22 08:02:05.4 |

I need to add two columns start_date & end_date something like this
key| col1 | timestamp            | start date              | end date              |
---------------------------------+---------------------------------------------------
1  | aa  | 2019-01-01 08:02:05.1 | 2017-01-01 08:02:05.1   | 2018-09-02 08:02:05.2 |
1  | aa  | 2019-09-02 08:02:05.2 | 2018-09-02 08:02:05.2   | 2019-12-24 08:02:05.3 |
1  | cc  | 2019-12-24 08:02:05.3 | 2019-12-24 08:02:05.3   | NULL                  |
2  | dd  | 2013-01-22 08:02:05.4 | 2013-01-22 08:02:05.4   | NULL                  |

Here,
for each column "key", end_date is next timestamp for the same key. However,  "end_date" for the latest date should be NULL.
What I tried so far:
I tried to use window function to calculate rank for each partition
something like this

  var df = read_csv()

  //copy timestamp to start_date
  df = df
       .withColumn("start_date", df.col("timestamp"))

  //add null value to the end_date
  df = df.withColumn("end_date", typedLit[Option[String]](None))

  val windowSpec = Window.partitionBy("merge_key_column").orderBy("start_date")

  df
  .withColumn("rank", dense_rank()
  .over(windowSpec))
  .withColumn("max", max("rank").over(Window.partitionBy("merge_key_column")))

So far, I haven't got the desired output.

A: Use window lead function for this case.
Example:
val df=Seq((1,"aa","2019-01-01 08:02:05.1"),(1,"aa","2019-09-02 08:02:05.2"),(1,"cc","2019-12-24 08:02:05.3"),(2,"dd","2013-01-22 08:02:05.4")).toDF("key","col1","timestamp")
import org.apache.spark.sql.expressions._
import org.apache.spark.sql.functions._
import org.apache.spark.sql._
val df1=df.withColumn("start_date",col("timestamp"))
val windowSpec = Window.partitionBy("key").orderBy("start_date")

df1.withColumn("end_date",lead(col("start_date"),1).over(windowSpec)).show(10,false)
//+---+----+---------------------+---------------------+---------------------+
//|key|col1|timestamp            |start_date           |end_date             |
//+---+----+---------------------+---------------------+---------------------+
//|1  |aa  |2019-01-01 08:02:05.1|2019-01-01 08:02:05.1|2019-09-02 08:02:05.2|
//|1  |aa  |2019-09-02 08:02:05.2|2019-09-02 08:02:05.2|2019-12-24 08:02:05.3|
//|1  |cc  |2019-12-24 08:02:05.3|2019-12-24 08:02:05.3|null                 |
//|2  |dd  |2013-01-22 08:02:05.4|2013-01-22 08:02:05.4|null                 |
//+---+----+---------------------+---------------------+---------------------+


text:
Q: Cancellation operation in time series analysis When studying the time series analysis, I read the following example.

I do not know how to understand this cancellation process. Yes, it can be cancelled like normal algebraic formula. But this "z" is an operator instead of just a variable. How can we cancel the common factor like we do in algebra?

A: Actually, $B$ is the operator in question. Or rather a linear function of it, the operator $(1+0.5B)$.
If the operator has an inverse (it does), then the cancellation will be meaningful, since it's just multiplying both sides by the inverse operator.
That is, multiply $\phi(z)$ and $\theta(z)$ by $(1+0.5z)^{-1}$, which represents that inverse operator, which is actually meaningful (as long as you have convergence*). Cancellation complete.
* (you might consider where $(1+az)^{-1} = 1 - az + (az)^2 - (az)^3 + ...$ converges, say, and perhaps consider what might happen at a zero of a term like $(1+az)$)
If you write out what is going on in terms of the original series, it might be clearer.

A: It is possible to cancel the common factor as in algebra because it is possible to prove it that it works.
The idea is to to start with the series $\sum_j \psi_j X_{t-j}$, where $X_{i}$ is the time series and show that this series converges if $\sum_j |\psi_j|<\infty$ and $\sup_tE|X_t|<\infty$. Now the convergence of series $\sum_j |\psi_j|<\infty$ implies that the Laurent series $\sum_j \psi_j z^j$ converges absolutely on unit circle $\{z\in \mathbb{C}: |z|=1\}$ and hence defines function $\psi(z)$.
So you have relation between the the polynomials and time series and hence the rules of algebra are "transferable". So if you have $\phi(B)X_t=\theta(B)Z_t$ you can write $X_t=\psi(B)Z_t$, where $\psi(z)=\frac{\theta(z)}{\phi(z)}$. If $\theta(z)$ and $\phi(z)$ have common roots, they cancel themselves in the fraction as in usual algebra. Note however that the cancelation is possible when the remainder (after cancelation) $\frac{\theta(z)}{\phi(z)}$ is well defined, i.e. $\phi(z)$ must not have roots in the unit circle, as only then the equation $\phi(B)X_t=\theta(B)Z_t$ has a well defined solution.
If you want more details I would recommend reading these excellent lecture notes by A. Van der Vaart. My answer can be thought as a condensed summary of the first pages of chapter on ARIMA processes.


text:
Q: Are AWS API Gateway routes "discoverable"? Or to put it another way:
Should I consider my list API routes public?
Reason for asking is if I setup a web hook for a payment service - will this be available to anyone to post to?
I guess the thing to do would be restrict to their origin.


text:
Q: Intel vector instruction to zero-extend 8 4-bit values packed in a 32-bit int to a __m256i? as the question says, I have a normal int that is 8 packed values of 4 bits each, and I would like to zero-extend that into a 256-bit vector register. Is that possible with sse/avx/avx2 ?

A: The solution by chtz (called cvt_nib_epi32_chtz in the remainder) is very suitable
for general purposes. However, in some specific cases, the solutions presented below might
be slightly more efficient:
/*     gcc -O3 -m64 -Wall -march=skylake cvt_nib_epi32.c     */
#include <immintrin.h>
#include <stdio.h>
#include <stdint.h>

__m256i cvt_nib_epi32_SKL(uint32_t x) {                /* Efficient on Intel Skylake and newer         */
                                                       /* Broadcast x to 8 elements                    */
    __m256i input   = _mm256_set1_epi32(x);
                                                       /* Shift the nibbles to the right position      */
    __m256i shifted = _mm256_srlv_epi32(input,_mm256_set_epi32(28,24,20,16,12,8,4,0));
                                                       /* Mask off the unwanted bits and return        */
            return _mm256_and_si256(shifted, _mm256_set1_epi32(0xF));
}

__m256i cvt_nib_epi32_HSW(uint32_t x) {                /* Efficient on intel Haswell and Broadwell     */
                                                       /* Very inefficient in AMD Zen!                 */
    __uint64_t x_b = _pdep_u64(x, 0x0F0F0F0F0F0F0F0F); /* Expand nibbles to bytes                      */
    __m128i    x_v = _mm_cvtsi64_si128(x_b);           /* Move x_b from GPR to AVX vector register     */
    return _mm256_cvtepu8_epi32(x_v);                  /* Convert bytes to integer elements and return */
}

The following assembly is generated by gcc:
cvt_nib_epi32_SKL:
        vmovd   xmm0, edi
        vpbroadcastd    ymm0, xmm0
        vpsrlvd ymm0, ymm0, YMMWORD PTR .LC0[rip]
        vpand   ymm0, ymm0, YMMWORD PTR .LC1[rip]
        ret
cvt_nib_epi32_HSW:
        movabs  rax, 1085102592571150095
        mov     edi, edi
        pdep    rdi, rdi, rax
        vmovq   xmm0, rdi
        vpmovzxbd       ymm0, xmm0
        ret
cvt_nib_epi32_chtz:
        vmovd   xmm0, edi
        vpsrld  xmm1, xmm0, 4
        vpunpcklbw      xmm0, xmm0, xmm1
        vpand   xmm0, xmm0, XMMWORD PTR .LC2[rip]
        vpmovzxbd       ymm0, xmm0
        ret

Function cvt_nib_epi32_chtz is very suitable for the AMD zen microarchitecture,
because it doesn't use instructions pdep and vpsrlvd, which are slow on these processors.
On Intel processors, cvt_nib_epi32_chtz may suffer
from high port 5 (p5) pressure, depending on the surrounding code,
because vmovd, vpunpcklbw, and vpmovzxbd, all execute on p5.
The other functions decode to only 2 p5 uops.
The Skylake solution cvt_nib_epi32_SKL uses the vpsrlvd, which is slow
on Intel Haswell and Broadwell.
For these processors cvt_nib_epi32_HSW is suitable. It uses the BMI2 instruction pdep, which is very(!) slow on
the AMD zen microarchitecture. Note that cvt_nib_epi32_HSW should also work well on Intel Skylake, but
(again) the actual performance depends on the surrounding code.
Note that in a loop context the constant loading, such as YMMWORD PTR .LC0[rip], and movabs  rax, 1085102592571150095,
is likely hoisted out of the loop. In that case only 4 uops are needed by
cvt_nib_epi32_HSW and cvt_nib_epi32_SKL.

A: Here is a solution that should keep the order:
__m256i foo(int x) {
    __m128i input = _mm_cvtsi32_si128(x);
    __m128i even  = input;
    // move odd nibbles to even positions:
    __m128i odd   = _mm_srli_epi32(input,4);
    // interleave: (only lower 64bit are used)
    __m128i inter = _mm_unpacklo_epi8(even, odd);
    // mask out wrong nibbles:
    __m128i masked = _mm_and_si128(inter, _mm_set1_epi32(0x0f0f0f0f));
    // convert to 32bit:
    return _mm256_cvtepu8_epi32(masked);
}

Godbolt link: https://godbolt.org/z/8RLUVE
You could get slightly more efficient, if you load two or four int32 at once for the interleaving and masking of the even and odd nibbles. (This would result in multiple __m256i vectors, of course)


text:
Q: Verify duplicate values on the array in Laravel5.7 I want to verify if email address in my database is duplicate or not?
Here is my codes :
'users.*.email'=> ['required','unique:users','email']

and this is my Controller
UsersController
public function MassStore(MassStoreUserRequest $request)
{

    $inputs = $request->get('users');
    return redirect()->route('admin.users.index');
}

and this is my POST data (post data($inputs) will send like as below) :
'users' => [
    [
        'name' => 'Ken Tse',
        'email' => 'ken@gamil.com',
        'password' => 'ken12ken34ken',
    ],
    [
        'name' => 'Ken Tse',
        'email' => 'ken@gamil.com',   //duplicate, so need trigger error
        'password' => 'ken12ken34ken',
    ],
]

and this is error I get :

[2019-12-10 15:51:16] local.DEBUG: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'ken@gamil.com' for key 'users_email_unique'

MassStoreUserRequest
public function rules()
{
    return [
        'users'                => ['required','array'],
        'users.*.name'         => ['required'],
        'users.*.email'        => ['required','unique:users','email'],
        'users.*.password'     => ['required','min:8']
    ];
}

A: To prevent duplicate data being submitted in an array you can use the distinct rule:
return [
    'users'            => ['required', 'array'],
    'users.*.name'     => ['required'],
    'users.*.email'    => ['required', 'email', 'distinct', 'unique:users'],
    'users.*.password' => ['required', 'min:8'],
];

A: Please try to use like this:
$rules = array(
            "name" => "required",
            "email" => "required|email|unique:users",
             "password" => "required|min:6",

        );

A: Just use the distinct with your email keyword such as :
public function rules()
{
    return [
        'users'                => ['required','array'],
        'users.*.name'         => ['required'],
        'users.*.email'        => ['required','unique:users','email', 'distinct'],
        'users.*.password'     => ['required','min:8']
    ];
}


text:
Q: Node - how can i pipe to a new READABLE stream? My app is supposed to take Web Audio streamed from the client, encode it as MP3, before sending it back out to clients via WebSocket.
I can currently encode and pipe to a file like this:
inbound_stream.pipe(encoder).pipe(fs.createWriteStream('audio.mp3'));

And if I already have a file on the server I can do this:
var mp3File = fs.createReadStream('audio.mp3');

            mp3File.on('data', function(buffer){
                io.sockets.emit('audio', { buffer: buffer });
            });

However, I want to access the encoded chunks in real time, and send those out to clients - not write to a file.
What I want is this, effectively:
inbound_stream.pipe(encoder).pipe(newReadStream);

        newReadStream.on('data', function(buffer){
            io.sockets.emit('audio', { buffer: buffer });
        });

I've looked at Duplex and Transform streams, but frankly I am still learning and the Prototyping made my head spin.
How do I do this? Thanks.
UPDATE
The solution below from @Nazar Sakharenko certainly does what I wanted, but the overhead of live encoding seems to make this inpossible, so writing the encoded MP3, and pre-buffering it seems to be the only way (thanks to various people for the suggestion.)
However I still have problems with this approach. New question here:
node.js - create a new ReadStream for a new file, when that file reaches a certain size

A: According to documentation readable.pipe(destination[, options]) the destination should be stream.Writable.
What you can do is to implement your own Writable stream:
const Writable = require('stream').Writable;

var buffer = [];
//in bytes
const CHUNK_SIZE = 102400; //100kb

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    buffer += chunk;
    if(buffer.length >= CHUNK_SIZE) {
       io.sockets.emit('audio', { buffer: buffer});
       buffer = [];
    }

    callback();
  }
});

myWritable.on('finish', () => {
   //emit final part if there is data to emit
   if(buffer.length) {
       io.sockets.emit('audio', { buffer: buffer});
   }
});

inbound_stream.pipe(encoder).pipe(myWritable);

thats all.


text:
Q: VS2017 fails to build UWP Store bundle (.NET Native, error in the ARM build) I've just installed the newest Visual Studio 2017 update that was released yesterday (the one that added support for the Creators Update SDK), and now I can no longer build an app bundle for my app.
I'm targeting build 14393 and everything worked just fine up until this update.
It looks like the x86 and x64 packages are successfully built, but then the ARM one fails for some reason.
I get this error in the output window:

2>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\AppxPackage\Microsoft.AppXPackage.Targets(3899,5): error APPX0502: file 'C:\Users...\MyApp\bin\ARM\Release\Lockr_2017.407.108.0_language-de.appx' not found.

Here's the link to the full output window after the build finishes (fails):
full build log
I've never had that error before. I already tried to restart the PC, restart Visual Studio, delete all the bin/obj/temp folders, I still have the same issue.
I've also updated all the NuGet packages (including the new .NET Native 1.6.1. version that was released today).
NOTE: I tried not to generate an app bundle (so that VS would generate the three different x86, x64 and ARM packages) and that works fine. I need an app bundle to upload to the Store though.
NOTE #2: I tried to compile and deploy the app in Release mode (.NET native) on my Windows 10 Mobile device (so in ARM mode) and it works just fine, there's nothing wrong with the app and VS can compile it just fine this way. Yet the bundle is failing for some reason.
I don't know what to do from here, is there anything I can try to fix this?
Thank you for your help.

A: Please try the following:

*

*Download storepackageworkaround.zip. See details here.

*Close VS2017.

*Go to this folder:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\VisualStudio\v15.0\AppxPackage

*Rename Microsoft.AppxPackage.Targets as Microsoft.AppxPackage.Targets.BAK.

*Extract Microsoft.AppxPackage.Targets from the ZIP file to the above folder.

A: For me, this got resolved after updating VS2017 released on April 17th
This is now fixed in latest VS2017.
https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#15.1.26403.07


text:
Q: asp.net - Measuring Page loading when javascript enabled/disabled How do it exactly?

A: you could use firefox and install FireBug add-on
it has a tab that showsthe loading times against each object/resource into the page


text:
Q: Python3, Tkinter. Не обновляется кнопка в функции Python3, Tkinter. Не создаётся кнопка в функции. пытаюсь заставить работать только btn[0]. функция button_clicked1 есть
from tkinter import *

root=Tk()
root.title('Python Tkinter Test')
root.minsize(325,230)
root.resizable(width=False, height=False)

k = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
list1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

st = int(0)

def xstroke(k, st):
    for i in range(1, 10):
        if int(st) == int(i):
            if list1.count(str(i)) == 1:
                k[i-1] = 'X'
                list1.remove(str(i))#надо обновить кнопку как-то
                btn[i] = Button(root, bg="#DC143C", text = "\(. | .)/", command = button_clicked1, width=4,height=1)
    return k, btn
def button_clicked1():
    print('1')

btn = [Button(root, bg="#87CEFA", text = k[0], command = lambda: xstroke(k, int(1)), width=4,height=1), Button(root, bg="#87CEFA", text = k[1], command = button_clicked1, width=4,height=1),
       Button(root, bg="#87CEFA", text = k[2], command = button_clicked1, width=4,height=1), Button(root, bg="#87CEFA", text = k[3], command = button_clicked1, width=4,height=1),
       Button(root, bg="#87CEFA", text = k[4], command = button_clicked1, width=4,height=1), Button(root, bg="#87CEFA", text = k[5], command = button_clicked1, width=4,height=1),
       Button(root, bg="#87CEFA", text = k[6], command = button_clicked1, width=4,height=1), Button(root, bg="#87CEFA", text = k[7], command = button_clicked1, width=4,height=1),
       Button(root, bg="#87CEFA", text = k[8], command = button_clicked1, width=4,height=1)]
for i in range(0,9):
    btn[i].pack
btn[0].place(x=35,y=35)
btn[1].place(x=105,y=35)
btn[2].place(x=175,y=35)
btn[3].place(x=35,y=90)
btn[4].place(x=105,y=90)
btn[5].place(x=175,y=90)
btn[6].place(x=35,y=145)
btn[7].place(x=105,y=145)
btn[8].place(x=175,y=145)
root.mainloop()

пытаюсь заставить работать только btn[0]. функция button_clicked1 есть

A: Просто обновите ваши функции в виджете через config
btn[i-1].config(bg="#DC143C", text = "\(. | .)/", command = button_clicked1, width=4,height=1)


text:
Q: Why does increased bandwidth give you an increased data rate when sending radio waves? I was told that an increased data rate, with the same modulation scheme, requires an increased bandwidth. I understand that you could send at different frequencies, thereby increasing the data rate. However, I was told that only one frequency was used. Does anyone have a simple explanation for this?
And what happens if you keep the same signal, and just increase the sending rate? Does this automatically increase the bandwidth, or is that something you decide when generating the signal?

A: A pure, infinitely long, ideal, etc., sinusoid carries no information for it is completely predictable. To be able to carry information it must change in time in some unpredictable manner. That built-in unpredictability is the information.
It is also true that among many other reasons so that you can easily generate and radiate the EM wave and also have an easily controlled propagation it is convenient to have a signal whose average frequency (roughly its so-called carrier frequency) be much larger than the signal's bandwidth, say $ > \textrm{20x}$. From Fourier analysis we know that for the same type of modulation the occupied bandwidth $B=kR << f_c$ is, of course, directly proportional to the modulation rate $R$ and where the proportionality factor $k$ depends on the type of modulation being used.
The modulation rate $R=\mu\rho$ is directly proportional to the information rate $\rho$, and the proportionality factor $\mu$ between them (e.g., $\mu \ge 1$ when binary modulation is used) depends on the type of error correction coding used to protect the information from noise induced errors.
The type of demodulator and decoder needed in the receiver are essentially independent of the modulation rate but naturally will depend on the modulation type and error correction code, resp., being used.

A: Imagine a simple modulation system where you can detect one full wavelength of the signal as one bit.
If your radio is 100KHz (longwave) then you can obviously only send 1 bit every 1/100,000 second = 100Kbits/s, now if you switched to 5Ghz microwave band you can send a single bit in 1/5,000,000,000 second.


text:
Q: Deployment and Rollback Strategy with Windows Azure I'm hoping that Microsoft Azure offers services in the areas of application deployments and rollbacks.
Specifically, I'm interested in accomplishing the following using Azure:

*

*Deploy an application with zero downtime

*Rollback an application in the event that a deployment fails

Are these features / services baked into Azure?
So that you can feel my pain...Right now, my deployment strategy through Visual Studio is a File System deploy.  I need to plan downtime, and most times I still have users on the system who are losing data (and therefore complaining) and ignoring the warnings.  And based on the urgency of a  feature request and deployment, sometimes a bug sneaks in.  A user discovers that, and obviously we need an immediate rollback (which inadvertently requires another unplanned maintenance window).
If you've had positive "deployment with zero downtime" and "application rollback" experiences using Azure, please share.
Thanks,
Mike

A: Yes, these features are baked into Azure, specifically in the deploy to staging and production-staging VIP switch features.
In order to get zero downtime, you can deploy to your staging environment, test until you are satisfied, and then VIP switch the staging deployment into production.  If you leave your staging deployment around and running, you can VIP switch them back if you encounter any unexpected issues in production.
The negative with this, of course, is that the staging environment costs you money for as long as you keep it up.  You could always test live for some period, and when you were sure you didn't have any showstoppers just pull down the staging environment until the next deployment.
https://www.windowsazure.com/en-us/manage/services/cloud-services/how-to-manage-a-cloud-service/


text:
Q: Placing images over a US map in R - receiving coercion failure Current Code:
        library(USAboundaries)
#install.packages("USAboundariesData", repos = "https://ropensci.r-universe.dev", type = "source")
    library(sf)
    #> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
    library(tidyverse)
    library(rasterpic)
    library(tidyterra)

    states <- USAboundaries::states_contemporary_lores %>%
      select(State = state_abbr) %>%
      filter(!(State %in% c("AK", "HI", "PR"))) %>%
      st_transform("ESRI:102003")

    states

    plot <- ggplot(states) +
      geom_sf(fill = "white") +
      theme_minimal() +
      theme(panel.background = element_rect(fill = "lightblue1"))

    plot

    teams <- data.frame(State = January$ShipState)
    teams$Team <- data.frame(Team = January$Team)

    logos <- teams %>%
      rowwise() %>%
      mutate(png = switch(Team$Team,
                          "Kansas City Chiefs" = "https://cdn.freebiesupply.com/images/large/2x/kansas-city-chiefs-logo-transparent.png",
                          "Alabama Crimson Tide" = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Alabama_Crimson_Tide_logo.svg/1024px-Alabama_Crimson_Tide_logo.svg.png",
                          "Phoenix Suns" = "https://banner2.cleanpng.com/20180419/lpe/kisspng-phoenix-suns-nba-sacramento-kings-charlotte-hornet-basketball-team-logo-5ad88205c602d4.1820850415241385018111.jpg",
                          "San Francisco 49ers" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b55.png",
                          "Colorado Avalanche" = "http://assets.stickpng.com/images/5a4fbb29da2b4f099b95da0b.png",
                          "Tampa Bay Buccaneers" = "http://assets.stickpng.com/thumbs/580b585b2edbce24c47b2b5e.png",
                          "Washington Capitals" = "http://assets.stickpng.com/images/5a4fbbeada2b4f099b95da22.png",
                          "Philadelphia Eagles" = "http://assets.stickpng.com/thumbs/580b585b2edbce24c47b2b4b.png",
                          "Georgia Bulldogs" = "https://flyclipart.com/thumb2/logo-university-of-georgia-bulldogs-bulldog-head-585520.png",
                          "Chicago Bears" = "https://cdn.freebiesupply.com/images/large/2x/chicago-bears-logo-transparent.png",
                          "Cincinnati Bengals" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b19.png",
                          "New Orleans Saints" = "https://cdn.freebiesupply.com/images/large/2x/new-orleans-saints-logo-transparent.png",
                          "Baltimore Ravens" = "https://cdn.freebiesupply.com/images/large/2x/baltimore-ravens-logo-transparent.png",
                          "Minnesota Wild" = "http://assets.stickpng.com/images/5a4fbb61da2b4f099b95da12.png",
                          "Vegas Golden Knights" = "http://assets.stickpng.com/images/5a4fbbe1da2b4f099b95da21.png",
                          "Buffalo Bills" = "https://cdn.freebiesupply.com/images/large/2x/buffalo-bills-logo-transparent.png",
                          "Pittsburgh Steelers" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b4e.png",
                          "Tennessee Titans" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b61.png",
                          "Dallas Cowboys"= 'https://cdn.freebiesupply.com/images/large/2x/dallas-cowboys-logo-transparent.png',
                          "Seattle Seahawks" = "https://cdn.freebiesupply.com/images/large/2x/seattle-seahawks-logo-transparent.png",
                          "Green Bay Packers" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b25.png",
                          "West Virginia Mountaineers" = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/West_Virginia_Mountaineers_logo.svg/1987px-West_Virginia_Mountaineers_logo.svg.png",
                          "Arkansas Razorbacks" = "https://upload.wikimedia.org/wikipedia/commons/e/ef/Arkansas-Razorback-Logo-2001.png",
                          "La Rams" = "http://assets.stickpng.com/images/608968b9d598a5000448eaa2.png",
                          "Washington Commanders" = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/Washington_Commanders_logo.svg/2560px-Washington_Commanders_logo.svg.png",
                          "Philadelphia 76ers" = "http://assets.stickpng.com/images/58419ca3a6515b1e0ad75a64.png",
                          "Charlotte Fc" = "https://upload.wikimedia.org/wikipedia/en/thumb/9/91/Charlotte_FC_logo.svg/1200px-Charlotte_FC_logo.svg.png",
                          "Nebraska Cornhuskers" = "https://cdn.freebiesupply.com/logos/large/2x/nebraska-corn-huskers-logo-png-transparent.png",
                          "New York Yankees" = "http://assets.stickpng.com/images/584d4b740a44bd1070d5d494.png",
                          "Oklahoma Sooners" = "https://upload.wikimedia.org/wikipedia/commons/4/49/Oklahoma_Sooners_logo.png",
                          "Milwaukee Brewers" = "https://purepng.com/public/uploads/large/milwaukee-brewers-logo-9xg.png",
                          "Los Angeles Dodgers" = "http://assets.stickpng.com/images/584d3e8a0a44bd1070d5d3d7.png",
                          "Denver Broncos" = "https://cdn.freebiesupply.com/images/large/2x/denver-broncos-logo-transparent.png",
                          "Washington Nationals" = "https://cdn.freebiesupply.com/images/large/2x/washington-nationals-logo-transparent.png",
                          "Philadelphia Phillies" = "http://assets.stickpng.com/images/584d42ac0a44bd1070d5d420.png",
                          "Atlanta Braves" = "https://1000logos.net/wp-content/uploads/2017/08/Atlanta-Braves-logo.png",
                          "Iowa Hawkeyes" = "https://1000logos.net/wp-content/uploads/2021/06/Iowa-Hawkeyes-logo.png",
                          "Gonzaga University Bulldogs" = "https://www.pngkey.com/png/full/65-655460_bulldog-700x441-gonzaga-bulldog.png",
                          "Chicago Cubs" = "http://assets.stickpng.com/images/584d41b10a44bd1070d5d411.png",
                          "Kentucky Wildcats" = "https://upload.wikimedia.org/wikipedia/commons/5/5d/Kentucky_Wildcats_logo_2015.png",
                          "Lsu Tigers" = "https://www.nicepng.com/png/full/96-961386_lsu-football-png-transparent-lsu-football-louisiana-state.png",
                          "Boston Red Sox"= "https://cdn.freebiesupply.com/images/large/2x/boston-red-sox-logo-transparent.png",
                          "Detroit Tigers" = "https://cdn.freebiesupply.com/images/large/2x/detroit-tigers-logo-transparent.png",
                          "Minnesota Twins" = "http://assets.stickpng.com/images/584d47ae0a44bd1070d5d45d.png",
                          "St Louis Cardinals" = "http://assets.stickpng.com/images/584d3fc80a44bd1070d5d3ed.png",
                          "Mississippi State Bulldogs" = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Mississippi_State_Bulldogs_logo.svg/640px-Mississippi_State_Bulldogs_logo.svg.png",
                          "Cleveland Browns" = "https://cdn.freebiesupply.com/images/large/2x/cleveland-browns-logo-transparent.png",
                          "Portland Trailblazers" = "https://cdn.freebiesupply.com/images/large/2x/portland-trail-blazers-logo-transparent.png",
                          "Masters" = "https://logos-world.net/wp-content/uploads/2022/02/Masters-Symbol.png",
                          "Tennessee Vols" = "https://1000logos.net/wp-content/uploads/2021/07/Tennessee-Volunteers-logo.png",
                          "Houston Astros"= "http://assets.stickpng.com/images/584d493b0a44bd1070d5d477.png",
                          "Utah Jazz" = "http://assets.stickpng.com/images/58419bb6a6515b1e0ad75a55.png",
                          "La Lakers" = "http://assets.stickpng.com/images/58419d0aa6515b1e0ad75a6c.png",
                          "Kansas Jayhawks" = "https://brandslogos.com/wp-content/uploads/images/large/kansas-jayhawks-logo.png",
                          "Baltimore Orioles" = "https://upload.wikimedia.org/wikipedia/en/thumb/7/75/Baltimore_Orioles_cap.svg/1200px-Baltimore_Orioles_cap.svg.png",
                          "Unc Tar Heels" = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/North_Carolina_Tar_Heels_logo.svg/512px-North_Carolina_Tar_Heels_logo.svg.png",
                          "South Carolina Gamecocks" = "https://upload.wikimedia.org/wikipedia/commons/thumb/9/94/South_Carolina_Gamecocks_logo.svg/933px-South_Carolina_Gamecocks_logo.svg.png",
                          "Seattle Mariners" = "http://assets.stickpng.com/images/584d467c0a44bd1070d5d44c.png",
                          "Colorado Rockies" = "https://www.nicepng.com/png/full/141-1415329_colorado-rockies-logos-png-clipart-download-colorado-rockies.png",
                          "Golden State Warriors" = "http://assets.stickpng.com/images/58419ce2a6515b1e0ad75a69.png",
                          "Chicago White Sox" = "http://assets.stickpng.com/images/584d4aff0a44bd1070d5d48d.png",
                          "Boston Celtics" = "http://assets.stickpng.com/images/58419c6aa6515b1e0ad75a61.png",
                          "Carolina Hurricanes" = "https://toppng.com/uploads/preview/carolina-hurricanes-nhl-logo-png-11536005105kxafnwdw2o.png",
                          "Tampa Bay Lightning" = "http://assets.stickpng.com/images/5a4fbbc8da2b4f099b95da1e.png",
                          "Oregon Ducks" = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f8/Oregon_Ducks_logo.svg/928px-Oregon_Ducks_logo.svg.png",
                          "Milwaukee Bucks" = "http://assets.stickpng.com/images/58419ba7a6515b1e0ad75a54.png",
                          "Los Angeles Angels" = "http://assets.stickpng.com/images/584d498d0a44bd1070d5d47b.png",
                          "Carolina Panthers" = "https://cdn.freebiesupply.com/images/large/2x/carolina-panthers-logo-transparent.png",
                          "Minnesota Vikings" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b38.png",
                          "New England Patriots" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b3b.png",
                          "Clemson Tigers" = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/72/Clemson_Tigers_logo.svg/1071px-Clemson_Tigers_logo.svg.png",
                          "Wyoming Cowboys" = "https://cdn.freebiesupply.com/logos/large/2x/wyoming-cowboys-logo-png-transparent.png",
                          "Arizona Cardinals" = "https://cdn.freebiesupply.com/images/large/2x/arizona-cardinals-logo-transparent.png",
                          "Washington Football Team" = "http://assets.stickpng.com/images/60896cf3d598a5000448eaa8.png",
                          "Indianapolis Colts" = "http://assets.stickpng.com/images/580b585b2edbce24c47b2b2c.png",
                          "Detroit Lions" = "https://cdn.freebiesupply.com/images/large/2x/detroit-lions-logo-transparent.png",
                          "Las Vegas Raiders" = "https://www.pngmart.com/files/16/Las-Vegas-Raiders-Transparent-Background.png",
                          "Michigan State Spartans" = "http://assets.stickpng.com/images/6103b47a2d29570004bc56f2.png",
                          "Utah Utes" = "http://assets.stickpng.com/images/5859a2df4f6ae202fedf28ec.png",
                          "Seattle Kraken" = "https://www.gannett-cdn.com/presto/2020/07/23/PPAS/b671207b-9fd0-46ea-a78a-f1c0fd3cab7d-Edn6Cc3XgAALN8o.jpg",
                          "Michigan Wolverines" = "https://upload.wikimedia.org/wikipedia/commons/3/36/Michigan_Wolverines_Block_M.png"
      ))

    for (i in seq_len(nrow(logos))) {
      logo <- logos[i, ]
      shape <- states[states$State == logo$State, ]

      img <- rasterpic_img(shape, logo$png, mask = TRUE)

      plot <- plot + geom_spatraster_rgb(data = img)
    }

    plot

Currently, I am receiving this error: Error: [as,sf] coercion failed. You can try coercing via a Spatial* (sp) class.
The goal of this is to have a US map with sports logos on each state. It is most googled sports teams by state. So if the Yankees sell the most in New York, I want the Yankees logo plotted on top of the state. My dataset being used is very, very simple. It is two columns - the state name and the team name. (i.e. Column A (ShipState) is AL, Column B (Team) is Alabama Crimson Tide.) For some reason, the loop is failing. Can anyone tell me what may be going wrong?

A: Have you tried storing images locally instead of sourcing them from the internet? The thing is if any of the website goes down, the image wont appear.
Furthermore, to embed image src code is required. for example:
<img src="https://s1.pngtank.com/thumbnails/63c1c0b584396.png">


text:
Q: given hex input should be convert to decimal pretty new to assembly !!
My assembly code takes hex input which is 0-9 and a-f other inputs will result an error, every character of the input is stored in an array and every element in an array will be taken to print their integer value, but for some reason the elements  address is printing.
Please see the code below and give me solution for my problem. if you need the full code please let me know.
(The idea of below code is to take each element of hex number and print the elements in decimal number)
        mov     ebx, array

next_loop:                              ;this loop is to convert the character

        mov     al, [ebx]
        cmp     al, NEWLINE        ; here NEWLINE is 10 which is already defined
        je      end_loop

        cmp     al, 97
        jge     subblock
        jl      numsub

numsub:
        sub     al, 48
        mov     [ebx], al
        jmp     next

subblock:
        sub     al, 97
        add     al, 10
        mov     [ebx], al
        jmp     next

next:
        inc     ebx
        loop    next_loop

; below code is to print the value which is stored in array

end_loop:
        mov     ebx, array
        mov     eax, message2
        call    print_string

print_loop:
        mov     al, [ebx]
        inc     ebx
        call    print_int      ; addresses of ebx is printing but not the value
        cmp     al, NEWLINE
        jne     print_loop
        jmp     finalend

Please resolve my problem.
Many thanks.

A: Without knowing anything about the print_int procedure, I'd assume that one is the problem. Should just involve adding a couple of square brackets when pushing the register that has your value, assuming you are using printf.


text:
Q: JButtons don't load on panel until hovered over? When this is put on a frame, the buttons don't load until they are hovered over with the mouse, and then they stay up like they should. Here's the code:
I've calling things like repaint() and revalidate() but none of them seem to have fixed the problem. The main and the Frame are seperate classes from the StartPanel. Thanks!
JButton[][] levels = new JButton[3][8];

public StartPanel(){
    setSize(1600, 1000);
    setLayout(null);

    int count = 1;
    int yValue = 150;
    for(int r = 0; r < 3; r++){
        for(int c = 0; c < 8; c++){
            levels[r][c] = new JButton(String.valueOf(count));
            levels[r][c].setLocation(c*190 + 80, yValue);
            levels[r][c].setSize(100, 100);
            this.add(levels[r][c]);
            count++;
        }
        yValue += 200;
    }
}

public static void main(String[] args) {
    Frame f = new Frame();
    StartPanel sp = new StartPanel();
    f.add(sp);
    f.setVisible(true);
}

public Frame() {
    setSize(1600, 1000);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    setResizable(false);
}

A: Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design.  There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
GridLayout
I might suggest trying GridLayout, in combination with something like an EmptyBorder, you should be able to get close to what you want, for example...

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        JButton[][] levels = new JButton[3][8];

        public TestPane() {
            setBorder(new EmptyBorder(40, 40, 40, 40));
            setSize(1600, 1000);
            setLayout(new GridLayout(0, 8, 40, 40));

            int count = 1;
            int yValue = 150;
            for (int r = 0; r < 3; r++) {
                for (int c = 0; c < 8; c++) {
                    levels[r][c] = new JButton(String.valueOf(count));
                    levels[r][c].setMargin(new Insets(50, 50, 50, 50));
                    this.add(levels[r][c]);
                    count++;
                }
                yValue += 200;
            }
        }
    }

}

See How to Use GridLayout for more details
GridBagLayout
Another solution might be to use a GridBagLayout, which is more flexible, but also more complicated, for example...

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        JButton[][] levels = new JButton[3][8];

        public TestPane() {
            setSize(1600, 1000);
            setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.insets = new Insets(25, 25, 25, 25);
            gbc.fill = GridBagConstraints.BOTH;

            int count = 1;
            for (int r = 0; r < 3; r++) {
                gbc.gridx = 0;
                for (int c = 0; c < 8; c++) {
                    levels[r][c] = new JButton(String.valueOf(count));
                    levels[r][c].setMargin(new Insets(50, 50, 50, 50));
                    this.add(levels[r][c], gbc);
                    gbc.gridx++;
                    count++;
                }
                gbc.gridy++;
            }
        }
    }

}

See How to Use GridBagLayout for more details


text:
Q: ternary operator inside an arrow function inside forEach I have this little function that is supposed to remove object properties with even values.
function removeEvenValues(obj) {
  Object.keys(obj).forEach(k => ((!isNaN(obj[k])) && (obj[k] % 2 === 0)) ? delete obj[k] : k);
}

In the else {} part of the ternary operator, how do I leave it empty like in an if (true){ doSomething();} kind of construct?  Or does it even make sense to use a fat arrow function in this case?

A: Yes, you shouldn't use a concise arrow function or a ternary operator here. Well, you could use && instead of the ternary, but you really shouldn't.
You shouldn't even use forEach in ES6 - just use a proper loop:
function removeEvenValues(obj) {
  for (const k of Object.keys(obj))
    if (!isNaN(obj[k]) && obj[k] % 2 === 0)
      delete obj[k];
}

or (as you probably don't care about inherited properties)
function removeEvenValues(obj) {
  for (const k in obj)
    if (!isNaN(obj[k]) && obj[k] % 2 === 0)
      delete obj[k];
}

A: There is nothing wrong with using a fat arrow, as it is a function expression, but because you are not returning a value, you shouldn't use a ternary operator. You can do:
function removeEvenValues(obj) {
    Object.keys(obj).forEach(k => {if(!isNaN(obj[k]) && (obj[k] % 2 === 0)) {delete obj[k]}});
}

A: You could use a logical AND && and remove some superfluous parentheses.

function removeEvenValues(obj) {
    Object.keys(obj).forEach(k => !isNaN(obj[k]) && obj[k] % 2 === 0 && delete obj[k]);
}

var o = { foo: 41, bar: 42 };
removeEvenValues(o);

console.log(o);

A: As Nina wrote, you can use logical operators instead of the ternary operator. You can also turn the condition around and use ||.
Be aware though what isNaN returns. For instance isNaN([2]) === false! So instead you might want to test for the primitive number type with typeof.
Finally, recently the Object.entries method has found its way in some browsers, and in this case it can be nice to use instead of Object.keys:

function removeEvenValues(o) {
    Object.entries(o).forEach(([k, v]) => typeof v != "number" || v % 2 || delete o[k]);
}

// Sample
var obj = {
    "a": 2,
    "b": "hello",
    "c": [4],
    "d": 5,
    "e": 6
};

removeEvenValues(obj);

console.log(obj);


text:
Q: Table already exist sql When trying to import database
Error
SQL query:
CREATE TABLE `wp_ihrss_plugin` (
  `Ihrss_id` int(11) NOT NULL,
  `Ihrss_path` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Ihrss_link` text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `Ihrss_target` varchar(50) NOT NULL,
  `Ihrss_title` varchar(500) NOT NULL,
  `Ihrss_order` int(11) NOT NULL,
  `Ihrss_status` varchar(10) NOT NULL,
  `Ihrss_type` varchar(100) NOT NULL,
  `Ihrss_extra1` varchar(100) NOT NULL,
  `Ihrss_extra2` varchar(100) NOT NULL,
  `Ihrss_date` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=utf8

MySQL said: Documentation

#1050 - Table 'wp_ihrss_plugin' already exists

and 5 more tables ; when try to drop one it show that there is another one

A: One possible approacj to deal with this would be to drop and recreate the object. For instance:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

A: There are some duplicate tables present in your database dump.
Check the sql file from which you are trying to import


text:
Q: How to call a method defined on the iPhone from the Apple Watch Is there any way to call a defined method in a class on the iPhone from the Watchkit extension?
From my understanding currently one of the ways to communicate locally between Watch kit and the iPhone is by using NSUserDefaults, but are there other ways?
A simple example would be great.

A: You can add the class to both targets (main iOS app and WatchKit extention) and use methods in WatchKit Extention directly.

Conveniently add classes (preferable utilities or categories) with few dependencies.
If file is already added to project, you can delete it (remove reference) and add it once again with including to multiple targets.
For example, my category NSString+color in project works correctly in iOS app and Watch App.
Upd: You can also do it in right panel (Utilities). See the link bellow: cs621620.vk.me/v621620973/13f86/9XYDH1HL5BI.jpg

A: There are two main ways to 'communicate' between your WatchKit Extension and iOS application depending on the what you are trying to accomplish.
1. openParentApplication:reply:
This will open your iOS application in the background and allow you to perform logic from your iOS code and send a response back to your Extension. For example -
    [InterfaceController openParentApplication:@{ @"command": @"foo" }
                                         reply:^(NSDictionary *replyInfo, NSError *error) {
                                         self.item = replyInfo[@"bar"];
    }];

Checkout the Framework Reference -https://developer.apple.com/library/prerelease/ios/documentation/WatchKit/Reference/WKInterfaceController_class/index.html#//apple_ref/occ/clm/WKInterfaceController/openParentApplication:reply:
MMWormhole is a library that you can use to manage these communications
2. Shared Container
If you just need access to the same data that your iOS application has access to you can implement shared containers across both targets.
This could range from just using accessing a shared NSUserDefaults, as you've mentioned or all the way up to using Core Data and accessing a shared persistence stack across both iOS and WatchKit.
Programming Reference - https://developer.apple.com/library/ios/technotes/tn2408/_index.html
3. Singleton
Perhaps you just need to access shared logic from your WatchKit Extension but don't need the complexity of the above two options. As long as you're not persisting any data across both targets you could create a Singleton class that you can call from your Extension to perform the methods you need.

A: According to Apple's WatchKit Programming Guide you can communicate with the iOS app on the iPhone by using openParentApplication and pass a dictionary. The parent application handles this call via handleWatchKitExtensionsRequest in its AppDelegate. From there you can call other methods depending on the passed parameters.
handleWatchKitExtensionRequest then calls the reply method to pass back parameters to the WatchKit Extension:
Watchkit Extension:
// Call the parent application from Apple Watch

// values to pass
let parentValues = [
    "value1" : "Test 1",
    "value2" : "Test 2"
]

WKInterfaceController.openParentApplication(parentValues, reply: { (replyValues, error) -> Void in
    println(replyValues["retVal1"])
    println(replyValues["retVal2"])
})

iOS App:
// in AppDelegate.swift
func application(application: UIApplication!, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]!, reply: (([NSObject : AnyObject]!) -> Void)!) {
    // retrieved parameters from Apple Watch
    println(userInfo["value1"])
    println(userInfo["value2"])

    // pass back values to Apple Watch
    var retValues = Dictionary<String,String>()

    retValues["retVal1"] = "return Test 1"
    retValues["retVal2"] = "return Test 2"

    reply(retValues)
}

Note that this seems to be broken in Xcode 6.2 Beta 3.

A: For WatchOS2 openParentApplication is deprecated. The replacement for it is WCSession in Watch Connectivity Framework
First, initialize WCSession in both watch(ExtensionDelegate)& iOS(AppDelegate) with following code
if WCSession.isSupported() {
  let session = WCSession.defaultSession()
  session.delegate = self
  session.activateSession()
}

Send a notification from watch to Phone using
session.sendMessage(msg, replyHandler: { (responses) -> Void in
  print(responses)
 }) { (err) -> Void in
 print(err)
}

Handle the message in AppDelegate using
func session(_ session: WCSession,
             didReceiveMessage message: [String : AnyObject],
             replyHandler replyHandler: ([String : AnyObject]) -> Void)
{
   //do something according to the message dictionary
   responseMessage = ["key" : "value"] //values for the replyHandler
   replyHandler(responseMessage)
}


text:
Q: How can I create a javascript to show and hide info according option value selected? I'm trying to create a combobox to show moths, when I do click on january I only need to see div1 and febraury need to see div 2 like this:
   January........

 It will show info when only january  is selected

   Febraury........

 It will show info when only febraury is selected

Here is my information:
 <select id="month" name="month">
   <option value="1">January</option>
   <option value="2">Febraury</option>
   <option value="3">March</option>
 </select>

 <-------ALL MY DIVS WILL BE HIDE  -------------->

 It will show info when only january  is selected

 It will show info when only Febraury is selected

 It will show info when only March    is selected

 <----- It should show each div according option div is selected ----->

Here is my demo
 http://jsfiddle.net/q2E5e/

Please somebody can help me with this?
I will really appreciate help

A: FIDDLE
You need to give id to your div, then use:
divJan.style.display = "block";

block will show your div, none will hide it.
You just need a function that will determine wich element is selected and an event to track the changes. Here's an example:
var cmbMonth = document.getElementById('month');
var divJan = document.getElementById('divJan');
var divFeb = document.getElementById('divFeb');
var divCoo = document.getElementById('divCoo');

cmbMonth.addEventListener('change', function (e) {

    if (cmbMonth.value == 1) {
        divJan.style.display = "block";
        divFeb.style.display = "none";
        divCoo.style.display = "none";

    } else if (cmbMonth.value == 2) {
        divJan.style.display = "none";
        divFeb.style.display = "block";
        divCoo.style.display = "none";

    } else if (cmbMonth.value == 3) {
        divJan.style.display = "none";
        divFeb.style.display = "none";
        divCoo.style.display = "block";
    }

});

A: A jQuery solution using
$('#month').change()

and
$(some id).hide()

JSFiddle

A: At first, instead of hidden div elements with text, would be better if you create an array with text values, that should be shown after selecting appropriate values.
var divTextValues = [
    "You selected January",
    "You selected February",
    "You selected March",
];

Second, for simplicity start values of dropdown list from 0.
<select id="month" name="month">
    <option value="0">January</option>
    <option value="1">February</option>
    <option value="2">March</option>
</select>

Third, hide div element by default.

And then add event handler.
var month = document.getElementById("month"),
    displayMonth = document.getElementById("displayMonth");

month.addEventListener("change", function (e) {
    var selected = this[this.selectedIndex];
    if (selected.value > -1) {
        displayMonth.textContent = divTextValues[selected.value];
        displayMonth.style.display = "block";
    } else {
        displayMonth.style.display = "none";
    }
});

Demonstration


text:
Q: Command docker-compose (re)build does not build fresh instance of container I created ./docker/app/Dockerfile with sth like this:
FROM php:7.3-apache
RUN a2enmod rewrite
RUN docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql
(...)

My docker-compose:
  app:
    build: './docker/app/'
    image: php:7.3-apache
    ports:
      - 80:80
    volumes:
    (...)

I'm trying to build clean instance of my container. I wish it will look like first build (I want to test if my Dockerfile is ok and will install all required packages).
But after making command:
docker-compose build app I see warnings like:
Module rewrite already enabled
warning: pdo_mysql (pdo_mysql.so) is already loaded!

Commands docker-compose build --force-rm app and docker-compose build --force-rm --no-cache app works the same. Packages installed once still persists and my Dockerfile's commands has no sense during the build.
So I have 2 questions:
1) How to build new clean version of my app container from scratch?
2) What commands docker-compose build and  docker-compose build --force-rm are for if they don't build new image?

A: try to reforce the build using:
docker-compose up -d --force-recreate

or delete every thing before you build:
docker-compose rm
docker image prune


text:
Q: APK's package name must be in the following format "com.example.myapp". It may contain letters (a-z), numbers, and underscores (_) I got this error while uploading apk to playstore.
Your APK's package name must be in the following format "com.example.myapp". It may contain letters (a-z), numbers, and underscores (_). It must start with a lowercase character.
I created apk in eclipse   ( file -> export -> export android application )
I have attached packag structures of the application and the manifest file. please help me out .
Thanks

A:
Your APK's package name must be in the following format
  "com.example.myapp". It may contain letters (a-z), numbers, and
  underscores (_). It must start with a lowercase character.

Your package name should be in lowercase characters. Uppercase characters are not allowed.


text:
Q: How do I link a library using CMake? I'm trying to add a new library to a project built using CMake and am having trouble. I'm trying to follow this. I've made a test project that looks like this:
cmake_test/
    test.cpp
    CMakeLists.txt
    liblsl/
        include/
            lsl_cpp.h
        CMakeLists.txt
        liblsl64.dll
        liblsl64.so
    build/

the CMakeLists.txt in cmake_test looks like this:
cmake_minimum_required(VERSION 3.10)

# set the project name and version
project(Tutorial VERSION 1.0)

# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

add_executable(Tutorial test.cpp)
add_subdirectory(liblsl)
target_link_libraries(Tutorial PUBLIC ${LSL_LIBRARY})

and the CMakeLists.txt in liblsl looks like this:
find_path(LSL_INCLUDE_DIR lsl_cpp.h)
find_library(LSL_LIBRARY liblsl64)
include_directories(${LSL_INCLUDE_DIR})

But I keep getting the error No rule to make target '.../liblsl64.lib', needed by 'Tutorial.exe'. Stop.
Any idea what I'm doing wrong?
I'm on Windows 10 using mingw-w64 v5.4.0 if that makes any difference.

A: CMakeLists.txt in cmake_test:
cmake_minimum_required(VERSION 3.10)
project(Tutorial VERSION 1.0)

add_subdirectory(liblsl)

add_executable(Tutorial test.cpp)
target_compile_features(Tutorial PUBLIC cxx_std_11)
target_link_libraries(Tutorial PUBLIC liblsl)

CMakeLists.txt in liblsl:
add_library(liblsl SHARED IMPORTED GLOBAL)
set_target_properties(liblsl PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/include")
set_target_properties(liblsl PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.so")

For Windows use:
set_target_properties(liblsl PROPERTIES IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.dll")
set_target_properties(liblsl PROPERTIES IMPORTED_IMPLIB "${CMAKE_CURRENT_SOURCE_DIR}/liblsl64.lib")

In add_library, you say SHARED because your library is a shared one (so/dll), you say IMPORTED because you don't want to build the library, and you say GLOBAL because you want it to be visible outside liblsl.


text:
Q: How to resize text based on screen size in Flutter? I am developing an app on Flutter, I have a Column which contains two Text Widgets in my Home Page. the problem is that on a mobile phone, the text size is normal, but on a tablet, the text is way too small to see. Could you please suggest a way to enlarge the text dynamically based on the screen size?
The Widget:
Column(
    children: [
      Text(
        widget.label,
        style: TextStyle(
            fontFamily: 'Roboto',
            color: Colors.white,
            fontWeight: FontWeight.bold),
      ),
      Text(
        widget.description,
        style: TextStyle(
            fontFamily: 'Roboto',
            color: Colors.white,
            fontWeight: FontWeight.w100),
      )
    ],
  ),

Thanks

A: This package here :
auto_size_text , https://pub.dev/packages/auto_size_text
Would help.

A: you can have two approaches:

*

*use auto_size_text package

*use  MediaQuery.of(context).size.width and MediaQuery.of(context).size.height to access width and height of screen, then use them to resize a SizedBox and pass your text as a FittedBox(child:YourTextWidget) to this widget. for example:

SizedBox(
width: 0.5 * screenWidth, // change 0.5 to whatever your want
child:FittedBox(
child: Text("Your Text")
))


text:
Q: MVC3: Attribute for not mapping a property to a DB column I'm using ASP.NET MVC3. I have a model that has one property that I don't want to store in the database. Is there an attribute that I can put on the property to achieve this? Thanks.

A: public class Person
{
    [Key]
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [NotMapped]
    public string FullName { get; set; }
}

The attribute are in the namespace System.ComponentModel.DataAnnotations

A: Just to add more options... this is why I prefer to keep my domain model separate from my view model. My view model often has additional fields necessary for rendering the view which does not belong in the domain model. The design I typically use is described pretty well here.


text:
Q: What C compilers have pointer subtraction underflows? So, as I learned from Michael Burr's comments to this answer, the C standard doesn't support integer subtraction from pointers past the first element in an array (which I suppose includes any allocated memory).
From section 6.5.6 of the combined C99 + TC1 + TC2 (pdf):

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

I love pointer arithmetic, but this has never been something I've worried about before.  I've always assumed that given:
 int a[1];
 int * b = a - 3;
 int * c = b + 3;

That c == a.
So while I believe I've done that sort of thing before, and not gotten bitten, it must have been due to the kindness of the various compilers I've worked with - that they've gone above and beyond what the standards require to make pointer arithmetic work the way I thought it did.
So my question is, how common is that?  Are there commonly used compilers that don't do that kindness for me?  Is proper pointer arithmetic beyond the bounds of an array a defacto standard?

A: MSDOS FAR pointers had problems like this, which were usually covered over by "clever" use of the overlap of the segment register with the offset register in real-mode. The effect there was that the 16-bit segment was a shifted left 4 bits, and added to the 16-bit offset which gave a 20-bit physical address that could address 1MB, which was plenty because everyone knew that noone would ever need as much as 640KB of RAM. ;-)
In protected mode, the segment register was actually an index into a table of memory descriptors. A typical DOS extending runtime would usually arrange things so that many segments could be treated just like they would have been in real mode, which made porting code from real mode easy. But it had some defects. Primarily, the segment before an allocation was not part of the allocation, and so its descriptor might not even be valid.
On the 80286 in protected mode, just loading a segment register with a value that would cause an invalid descriptor to load would cause an exception, whether or not the descriptor was actually used to refer to memory.
A similar issue potentially occurs at one byte past the allocation. The last ++ on the pointer might have carried over to the segment register, causing it to load a new descriptor. In this case, it is reasonable to expect that the memory allocator could arrange for one safe descriptor past the end of the allocated range, but it would be unreasonable to expect it to arrange for any more than that.

A: This is not "implementation defined" by the Standard, this is "undefined" by the Standard. Which means that you can't count on a compiler supporting it, you can't say, "well, this code is safe on compiler X". By invoking undefined behavior, your program is undefined.
The practical answer isn't "how (where, when, on what compiler) can I get away with this"; the practical answer is "don't do this".

A: Another reason is that there are optional conservative garbage collectors (like the boehm-weiser GC) that assume a pointer is always inside the allocated range and if not they are allowed to free the memory at any time.
There is one popular commercial quality and used library that does break this assumption and it is the Judy Trees Library from HP which uses pointer algorithms to implement a very complex hash structure.

A: ZETA-C for the TI Explorer; pointers are implemented as arrays and indexes or displaced arrays, IIRC, so your example probably wouldn't work.  Start from zcprim>pointer-subtract in zcprim.lisp to figure out what the behavior would be.  No idea whether this was correct per the standard, but I get the impression that it was.


text:
Q: Testing the UI of web applications? I am already using unit testing to ensure that all critical bits and pieces in my current web application works well. But what about testing the UI to ensure that the proper response occurs when an user hits a button for instance? - I mean, it's really going to make a mess if suddenly the signup button disappears or stops working, so I guess that it's common sense to perform this sort of UI testing as well.
From what I've read this far. Selenium, PhantomJS & Zombie seems to do what I want, but I know very little about them.
But what other alternatives are available and what should one consider before doing this type of unit testing?

A: Phantom and Zombie are essentially the same thing. Both are headless browsers. Headless means that it behaves as a simple browser (opens the page, runs scripts, renders the content, handles cookies etc.) but no output is displayed to the user.
You define a test case using JavaScript

*

*Open www.example.com page

*Insert text "Bob" in "UserName" text field

*Click on "Good morning" button

*Check (assert) that the "output" field contains "Good morning Bob"

Selenium is a set of tools:

*

*Selenium IDE - a Firefox add-in that can record and play actions performed by you. It means that no scripting language knowledge is necessary to create and run test cases!

*Selenium WebDriver - a library that can "take control" over some supported browsers. It actually opens a selected browser (say Firefox) and performs the actions described in the test case code. (Note that Phantom headless browser is one of the browsers WebDriver can control).

*Some more like Grid for load testing, but don't know much about that

To sum up

*

*If you want to test the front-end only, and are experienced with JavaScript - take Phantom or Zombie

*If you don't want to use JavaScript, choose Selenium IDE

*If you want to create more complicated tests (e.g. put some content into the database and then perform some operations in the browser) - use Selenium WebDriver

A: I ended up using zombie.js which was a pretty nice fit as we already had javascript knowledge inhouse.

A: You would be better of with Selenium as its got the stregth of powerful languages


text:
Q: How to clear TFS Cache in a linux machine After removal of existing account all the workspaes for old account was deleted in my linux Jenkins server. But when changed configuration to new Account credentials. I am finding old workspaces could not be overrided with new account details. where on server side we could not find that workspace details.
Is there a way we can clear linux client cache?

A: According to my understand, seems you want to migrate all workspaces from your old user to another user. This can be accomplished by command line tool tf.exe
tf workspaces /updateUserName:OldUserName /collection:collectionurl

This should be done with your new account, and will assign all workspaces from old account to current account.

/updateUserName
Updates security identification information on the Team Foundation
  server for a user whose network user name has been changed. If you
  specify this option, you must also specify a team project collection
  by using the /collection option.

More details please refer  Workspaces Command For Linux machine, you could use Team Explorer Everywhere (TEE) an Eclipse plug-in and a command-line client to run the command.
Another way is creating the server workspace on Windows, then use the /template option on Linux to setup the same configuration.