Q: assign userID as value and username as ng-model to a select tag My question is probably easy, but I am having difficulties to solve it. I am developing an application using ASP.Net MVC and AngularJS. And I am using select tag to list users. I assigned to the select tag the same ng-model that I have assigned to div for real-time binding (user names).
My question is, when I change the item (user) in the select tag and save, I want to save using ID not username.
As you know, ng-model is equals username and I want it that way, but when it comes to saving the data, I want to use value and I want it the same as userID not name.

{{supervisor}}

<select ng-model="supervisor">
    <option ng-repeat="x in supervisors" ng-selected='supervisor == (x.supervisorfName+" "+x.supervisorlName)'>{{x.supervisorfName+" "+x.supervisorlName}}</option>
 </select>

The above select tag is listing users from database table. It has the same ng-model as the div in the top... When I click on the save icon below the select tag, I want to update the database table but not using ng-model because it is the name. Instead, I want to use ID.
So, how can I add ID in addition to ng-model in a select tag??
Below is the angularJS controller code that calls the database:
$http.get('/Home/GetSupervisor')
    .then(function (response) {
        $scope.supervisors = response.data;
    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });

And finally, below is the MVC code:
public JsonResult GetSupervisor()
    {
        var db = new scaleDBEntities();
        return this.Json((from userObj in db.Users
                          select new
                          {
                              supervisorId = userObj.Id,
                              supervisorfName = userObj.usrFirstName,
                              supervisorlName = userObj.usrLastName,
                          })
                          , JsonRequestBehavior.AllowGet
                        );
    }

As requested, below is my angular controller:
var myApp = angular.module('myApp', []);

myApp.controller('mainController', function ($scope, $http) {
$http.get('/Home/GetUser')
    .then(function (response) {
        $scope.users = response.data;
        $scope.itmNo = response.length;

    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });

$http.get('/Home/GetSupervisor')
    .then(function (response) {
        $scope.supervisors = response.data;
    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });

});

A: You can set your ng-model to be an object( which represent your user/supervisor entity) instead of just the name.
So add a new property to your scope called supervisor.
myApp.controller('mainController', function ($scope, $http) {

   $scope.supervisor=null;

  //your existing code goes here
};

Now in your view, you can use the name property to display the selected supervisor name.

{{supervisor.supervisorfName}} {{supervisor.supervisorlName}}

<select ng-options="option.supervisorfName for option in supervisors"
        ng-model="supervisor"></select>

When you have to save, you can get the id of the selected supervisor from the id property like $scope.supervisor.supervisorId
And to show both first name and last name in the option, you simply need to concatenate
<select ng-options="option.supervisorfName+' '
                                       +option.supervisorlName for option in supervisors"
        ng-model="supervisor"></select>


Q: EclipseLink converts Enum to BigDecimal I try to convert an Enum into a BigDecimal using the Converter of EclipseLink. The conversion works, but the resulting database column has a type of String. Is it possible to set a parameter, that EclipseLink builds a decimal column type within the database?
I use a class, which implements org.eclipse.persistence.mappings.converters.Converter.
The application server logs
The default table generator could not locate or convert a java type (null) into a database type for database field (xyz). The generator uses java.lang.String as default java type for the field.
This message is generated for every field, which uses a converter. How can I define a specific database type for these fields?
public enum IndirectCosts {

EXTENDED {
    public BigDecimal getPercent() {
        return new BigDecimal("25.0");
    }
},
NORMAL {
    public BigDecimal getPercent() {
        return new BigDecimal("12.0");
    }
},
NONE {
    public BigDecimal getPercent() {
        return new BigDecimal("0.0");
    }
};

public abstract BigDecimal getPercent();

public static IndirectCosts getType(BigDecimal percent) {
    for (IndirectCosts v : IndirectCosts.values()) {
        if (v.getPercent().compareTo(percent) == 0) {
            return v;
        }
    }
    throw new IllegalArgumentException();
}
}

The database has to store the numeric values. I use such a converter:
public class IndirectCostsConverter implements Converter {

@Override
public Object convertObjectValueToDataValue(Object objectValue, Session session) {
    if (objectValue == null) {
        return objectValue;
    } else if (objectValue instanceof IndirectCosts) {
        return ((IndirectCosts) objectValue).getPercent();
    }
    throw new TypeMismatchException(objectValue, IndirectCosts.class);
}

@Override
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
    if (dataValue == null) {
        return dataValue;
    } else if (dataValue instanceof String) {
        return IndirectCosts.getType(new BigDecimal((String) dataValue));
    }
    throw new TypeMismatchException(dataValue, BigDecimal.class);
}

@Override
public boolean isMutable() {
    return false;
}

@Override
public void initialize(DatabaseMapping databaseMapping, Session session) {
}
}

Within convertDataValueToObjectValue(Object I have to use String because the SQL generator defines the database column as varchar(255). I would like to have decimal(15,2) or something.
Thanks a lot
Andre

A: The EclipseLink Converter interface defines a initialize(DatabaseMapping mapping, Session session); method that you can use to set the type to use for the field.  Someone else posted an example showing how to get the field from the mapping here: Using UUID with EclipseLink and PostgreSQL
The DatabaseField's columnDefinition, if set, will be the only thing used to define the type for DDL generation, so set it carefully.  The other settings (not null, nullable etc) will only be used if the columnDefinition is left unset.


Q: c# convert yyyymmdd text to dd/MM/yyyy I have some text in rows as yyyymmdd (eg: 20181211) which I need to convert to dd/MM/yyyy
I am using:
cashRow["BusinessDate"] = Convert.ToDateTime(row.Cells[ClosingDate.Index].Value.ToString()).ToString("dd/MM/yyyy");

I get the error "string was not recognized as a valid DateTime.
Any ideas where I am going wrong?

A: You'll need to use ParseExact (or TryParseExact) to parse the date:
var date = "20181217";
var parsedDate = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var formattedDate = parsedDate.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)

Here we tell ParseExact to expect our date in yyyyMMdd format, and then we tell it to format the parsed date in dd/MM/yyyy format.
Applying it to your code:
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

A: You have to use ParseExact to convert your yyyyMMdd string to DateTime as follows and then everything is okay.
cashRow["BusinessDate"] = DateTime.ParseExact(row.Cells[ClosingDate.Index].Value.ToString(), "yyyyMMdd", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy");

A: As you already know the exact format of your input yyyyMMdd (eg: 20181211), just supply it to DateTime.ParseExact() and then call  ToString() on the returned DateTime object.
string YourOutput = DateTime.ParseExact(p_dates, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

A: Try this:
cashRow["BusinessDate"] = row.Cells[ClosingDate.Index].Value.ToString("dd/MM/yyyy");


Q: Sum of the coefficients of polynomial $f(x)= (3x-2)^{107} (x+1)^4$ Sum of the coefficients of polynomial $f(x)= (3x-2)^{107}  (x+1)^4$
Please hint me with this. I can't manage anything except taking 3 common from first bracket.

A: Notice that the sum of the coefficients of a polynomial $P(x)$ is $P(1)$.


Q: Angular 2 component .html path I try to use relative paths for html in component also i am mapping my js files in dist folder.. my component code is
app/app.component.ts
import { Component } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: 'app.component.html'
})
export class AppComponent { }

the html file is in same directory i.e
app/app.component.html
<h1> Wolaa </h1>

I am getting following error

Its totally clear that angular is finding app.component.html file at "dist/app/app.component.html" which is not there how can i fix this??
My systemjs.config.js file is
/**
 * System configuration for Angular 2 samples
 * Adjust as necessary for your application needs.
 */
(function(global) {
  // map tells the System loader where to look for things
  var map = {
    'app':                        'dist', //'app',
    '@angular':                   'node_modules/@angular',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    'rxjs':                       'node_modules/rxjs'
  };
  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'main.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { main: 'index.js', defaultExtension: 'js' },
  };
  var ngPackageNames = [
    'common',
    'compiler',
    'core',
    'forms',
    'http',
    'platform-browser',
    'platform-browser-dynamic',
    'router',
    'router-deprecated',
    'upgrade',
  ];
  // Individual files (~300 requests):
  function packIndex(pkgName) {
    packages['@angular/'+pkgName] = { main: 'index.js', defaultExtension: 'js' };
  }
  // Bundled (~40 requests):
  function packUmd(pkgName) {
    packages['@angular/'+pkgName] = { main: 'bundles/' + pkgName + '.umd.js', defaultExtension: 'js' };
  }
  // Most environments should use UMD; some (Karma) need the individual index files
  var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
  // Add package entries for angular packages
  ngPackageNames.forEach(setPackageConfig);
  var config = {
    map: map,
    packages: packages
  };
  System.config(config);
})(this);

and my tsconfig.json is
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "dist"
  }
}

A: Here are some details about template relative paths in the documentation that may help:
https://angular.io/docs/ts/latest/cookbook/component-relative-paths.html

A: Try placing a "./" before your relative path like:
import { Component } from '@angular/core';
@Component({
  moduleId: module.id,
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent { }

A: This is the best solution that I could find so far:
moduleId: module.id.replace("/dist/", "/src/"); where src in my case is app.
Taken from here.


Q: Laravel 5 and Carbon discrepancy on Forge Hopefully I'm not mad and I'm only missing something. I have a project on Laravel 5.0 and I have a requestExpired function called every time I have an incoming request. Now, to calculate the difference between current time on the server and the timestamp within the request I'm using:
$now = Carbon::now('UTC');
$postedTime = Carbon::createFromTimestamp($timestamp, 'UTC');

For some reason request is always rejected because it's expired. When I debug these two lines from above and just dump data, I get:

REQUEST'S TIMESTAMP IS: 1423830908279
$NOW OBJECT: Carbon\Carbon Object
  (
      [date] => 2015-02-13 12:35:08.000000
      [timezone_type] => 3
      [timezone] => UTC
  )
$POSTEDTIME OBJECT: Carbon\Carbon Object
  (
      [date] => 47089-05-28 09:37:59.000000
      [timezone_type] => 3
      [timezone] => UTC
  )

Any ideas why $postedTime is so wrong? Thanks!

A: To answer my own question: for some strange reason webhook calls from remote API have 13 digits long timestamps and that's why my dates were so wrong.


Q: get store categories inside phtml file magento2 I want to customize topmenu.phtml file but I see, I can customize limited html. How I can create my own menu and get store categories inside phtml?

A: You have a few options for this, depending on your requirements for customization, you can:

*

*Create a plugin that would listen on page_block_html_topmenu_gethtml event. If you want to add items to the menu, you would listen for page_block_html_topmenu_gethtml_before event and add items to the menu parameter. Otherwise, if you want to edit the direct HTML you can listen for page_block_html_topmenu_gethtml_after which returns the HTML and you can edit it before passing it to the template.

*Second option is to override the /vendor/magento/module-theme/Block/Html/Topmenu.php block and the /vendor/magento/module-theme/view/frontend/templates/html/topmenu.phtml template for your customizations.

For information on how to do these, take a look at this on how to use plugins or this on how to override the block.
I would normally recommend going for plugins instead of override, but if you want to create a completely new topmenu you should go for the override.


Q: End-of-Session Handling in EmberJS I have an Ember application that requires user authentication on the server side.  Once authenticated (via login), application runs normally.  The application shows a logout button.  Pressing this logout button sends a message to the server, which causes the server to terminate the session, does some clean up, and sends the login page for the client to display.  All this works fine.
But here's the problem: if the user hits the browser's 'back' button after logging off, he will see the app again and can interact with it.  The app can still send messages to the server.  Currently, the server will always respond by sending back the login page when the session is already terminated.  How do I get ember to transition to this login page received from the server?  The fact that users can still get back to a running application (at least on the client side) after logging off would cause some confusion.
What's the recommended method for handling this?  Is there anyway to make the Ember application end when the user hits the logout button?  Maybe just disable the browser's back button when the user logs off (how do you do this in Ember?)?

A: You can either check in every route if the session is loggedIn or not in activate hook of route like this..
if you are setting a variable loggedIn true here is how to do it.
App.PostRoute = Ember.Route.extend({
  activate: function() {
    if (!loggedIn){
      this.tansitionTo('login');
    }
  }
});

If you want to remove totally PostRoute from history you can use replaceWith rather transitionTo.
.or use these for authentication ember-auth or simple-auth


Q: Deploy Azure Container App to different Resource Group in Azure pipeline I´m playing around with Azure Container Apps, but I'm running into a small issue when trying to deploy through Azure Pipelines, the thing is that I have one Azure Container Registry and I want to create a new Revision for ca-sandbox-1 and ca-sandbox-2, but since there are in different Resource Group I always get a "Forbidden" when executing Azure Pipelines
If I create the Azure Container Registry in the same Resource Group the pipeline works well.
Now If I try to create a new revision in two different Resource Group, only works from AzureCLI or VSCode. Is there a way of making this work from Azure Pipelines?
Azure
rg-core (Resource Group)

*

*acrcore (Azure Container Registry)

*ca-core (Azure Container App)

rg-sandbox-1 (Resource Group)

*

*ca-sandbox-1 (Azure Container App)

rg-sandbox-2 (Resource Group)

*

*ca-sandbox-2 (Azure Container App)

Azure-pipeline.yml
- main

stages:
- stage: Build
  displayName: Build and push stage
  jobs:
  - job: Build
    displayName: Build
    pool:
      vmImage: 'ubuntu-latest'

 steps:
    - task: Docker@2
      displayName: 'docker build and publish'
      inputs:
        containerRegistry: 'acr-core-connection'
        repository: 'ca-core'
        command: 'buildAndPush'
        Dockerfile: '**/Dockerfile'
        buildContext: '.'

    - task: AzureContainerAppsRC@0
      inputs:
        azureSubscription: 'subs-rg-core'
        acrName: 'acrcore'
        imageToDeploy: 'acrcore.azurecr.io/api-sandbox:$(Build.BuildId)'
        containerAppName: 'ca-sandbox-1'
        resourceGroup: 'rg-sandbox-1'
        targetPort: '80'

A:
Is there a way of making this work from Azure Pipelines?

From your description, you need to access the azure container registry  and azure container app in different Resource Groups.
To meet your requirement, you need to create a Service Connection at Subscription Level.
Navigate to Project Settings -> Service Connections -> Select Azure Resource Manager Service Connection. Then you can only select Azure Subscription.
In this case, the Service Connection will have access to whole Azure Subscription.
For example:


Q: Can I use windbg as a post mortem debugger for Windows services? I have Windbg set as the default post mortem debugger.  I did this by running windbg -I.  However, this only appears to catch unhandled exceptions from applications run by the user I'm logged on as, not Windows services.  Does anyone know how I can configure windbg to catch these too?

A: If you plan to debug the service application from the beginning of its execution, including its initialization code, this preparatory step is required.
http://msdn.microsoft.com/en-us/library/windows/hardware/ff553427(v=vs.85).aspx

A: When WinDbg is running as postmortem debugger it is launched by the process that is crashing.  In case of a service it is launched by a process running in session 0 and has no access to the desktop.
You can configure AeDebug registry to launch a process that creates a crash dump and debug the crash dump.  You can use ntsd -server and connect to the server.

A: You should be able to use WinDbg to attach or launch any service even those not run by the user: http://support.microsoft.com/kb/824344


Q: Using ajax with MVC I see my product’s bag ViewShoppingCart.ascx
<%= Ajax.ActionLink("Посмотреть карзину",
     "ViewShoppingCart", "Products",
     new AjaxOptions { UpdateTargetId = "content" })%>

And I want to change the quantity in ViewShoppingCart.ascx.
<%using (Ajax.BeginForm("UpdateItem", "Products",
              new AjaxOptions { UpdateTargetId = "content" }))
  {%>
      <%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
      <%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(), new { size = 2,
          maxlength = 2, onchange = "this.form.submit();" })%>
 <%} %>

When I enter a new value quantity and I press "enter" everything works as expected. If I press  "Tab"  instead "Enter" a new window appears instead of ajax form
What I do wrong?

A: One way would be to add a submit button to your form (it could be hidden) and invoke the click action so that it will trigger an asynchronous form postback:
<%using (Ajax.BeginForm("UpdateItem", "Products",
         new AjaxOptions { UpdateTargetId = "content" })) {%>
    <%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
    <%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(), new { size = 2,
        maxlength = 2, onchange = "document.getElementById('button').click();" })%>
    <input type="submit" id="button" style="display: none" />
<% } %>

And if you don't like the idea of putting hidden buttons this also works but one may find it ugly:
<%using (Ajax.BeginForm(
    "UpdateItem",
    "Products",
    new AjaxOptions {
        UpdateTargetId = "content"
    },
    new {
        id = "myForm"
    }))
{ %>
    <%=Html.Hidden("productid", shoppingCartItem.Product.ProductID.ToString())%>
    <%=Html.TextBox("Quantity", shoppingCartItem.Quantity.ToString(),
        new {
            size = 2,
            maxlength = 2,
            onchange = "var event = new Object(); event.type='submit'; $get('myForm').onsubmit(new Sys.UI.DomEvent(event));"
        })
    %>
<% } %>

Off-topic: simplify your life with unobtrusive javascript and jQuery.


Q: How do you make Seahorse (Gnome Keyring) store passwords for ssh keys in? I'm trying to get Seahorse to remember the password for an existing RSA key I've copied across from another computer.
When I use the key rather than Gnome Keyring prompting me for the password and storing it on the keyring I have to enter the password in terminal and the password isn't remembered?
How do I use Seahorse to save my SSH key password?

A: You can also use ssh-add to add the key to the keyring. (This one worked for me whereas the "Configure key..." did not.)

A: Problem solved, needed to add the key to be used for each particular machine.
Can do this by going to,
Gnome Keyring -> My Personal Keys -> Right click on key -> Configure key for secure shell

A: Use an ssh-agent that remembers your ssh passwords, e.g. https://wiki.gnome.org/Projects/GnomeKeyring/Ssh


Q: Trying to click on an image area with bootstrap I am using the Bootstrap CDN library building my website. (And I'm new to HTML in general)
I'm trying to use an Image as index page.
The Image contains 2 places where buttons should be:

I managed to determine and calculate the areas, but I can't make it work...

<map name="Map" id="Map">
    <area alt="" title="" href="empty.html" shape="poly" coords="3379,2255,3380,2711,2422,2712,2425,2256" />
    <area alt="" title="" href="login.html" shape="poly" coords="3458,2256,4430,2255,4415,2711,3458,2711" />

</map>

any thoughts? all HTML files are in same file.

A: You can place a div with that img as background-image and set 2 buttons/divs with position absolute.
Like this:

.home {
  background-color:red;
  width:100%;
  height:100vh;
  position:relative;
}

.btn1 {
  width:200px;
  height:200px;
  background-color:blue;
  position:absolute;
  top:20%;
  left:30%;
}

.btn2 {
  width:200px;
  height:200px;
  background-color:green;
  position:absolute;
  top:20%;
  left:50%;
}

    page one

    page two


Q: When would friends say "how do you do"? Louis Armstrong sings in What a Wonderful World

I see friends shaking hands saying how do you do

Why (or when) would friends use how do you do as it is supposed to be a formal answer to an introduction?

A: The literal use of "How do you do?" to greet someone has been basically limited to the first meeting between strangers for the past 50 years that I know of.  It's not really that "formal" in the sense that it wouldn't be used when meeting a friend of your buddy in a bar, but it's not normally used as a greeting between friends, or even acquaintances.
However, the expression "saying how do you do" is an idiomatic way to refer to people greeting each other.  It's not that the words are literally said between the greeting parties, but rather someone in a group might say "I'll talk too you later, after I get my how-do-you-dos out of the way," or something similar.


Q: How to place text on a diagonal line?
Hey guyz, I guess you got my concept by seeing the above picture. I'm unable to place diagonal line behind the text and it should get masked by the content placed on it. I wanted it in pure css. Background should be visible through the text.

A: You can use a rotated pseudo element. Make it 1px wide and make the lines with top/bottom borders :

body {
  padding: 0;
  margin: 0;
  background-image: url('https://farm7.staticflickr.com/6083/6055581292_d94c2d90e3.jpg');
  background-size: cover;
}

div {
  position: relative;
  width: 150px;
  margin: 130px auto;
  padding: 10px 0;
}

div:before {
  content: '';
  position: absolute;
  top: -120px;
  left: 50%;
  width: 1px;
  height: 100%;
  border-top: 120px solid #000;
  border-bottom: 120px solid #000;
  -webkit-transform: rotate(8deg);
  -ms-transform: rotate(8deg);
  transform: rotate(8deg);
}

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec luctus condimentum mi sit amet iaculis. Aliquam erat volutpat. Maecenas eleifend commodo rutrum.

A: I think you are looking for this-

body{background: url('http://i.imgur.com/Kv22GCi.png');}
div {
  position: relative;
  width: 120px;
  margin: 100px auto;
  padding: 5px 0;
}
div:before {
  content: '';
  position: absolute;
  top: -100px; left: 45%;
  width: 1px; height: 100%;
  border-top: 120px solid #000;
  border-bottom: 120px solid #000;
  -webkit-transform: rotate(8deg);
  -ms-transform: rotate(8deg);
  transform: rotate(8deg);
}

dsfsd jf fkljdsfjdsj

Loream ipsum dolor shit amet

I hope this will help you.

A: You can do using pseudo selectors :after or :before
Download this png image for background http://i.imgur.com/Kv22GCi.png

.container {
  position: relative;
  width: 300px;
  height: 548px;
  border: 1px solid #ccc;
  background-image: url(http://i.imgur.com/Kv22GCi.png);
  padding: 50px;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  font-family: sans-serif
}
/*For the diagonal line*/

.container:after {
  content: "";
  position: absolute;
  height: 100%;
  border: 1px solid #000;
  top: 0;
  left: 70px;
  z-index: -1;
  -moz-transform: rotate(10deg);
  -ms-transform: rotate(10deg);
  -o-transform: rotate(10deg);
  -webkit-transform: rotate(10deg);
  transform: rotate(10deg)
}
h1 {
  font-size: 50px
}
p {
  font-size: 22px
}

About Us.

"Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet.Lorem ipsum sit amet."


Q: I'm trying to perform a delete request but I'm facing this error Front End
import React,{useState, useEffect} from 'react'
import axios from 'axios'

function Renderreview() {
const [renderReview, setRenderReview] = useState([])

useEffect(()=>{
    axios.get('/reviews')
    .then(res => {
    console.log(res)
    setRenderReview(res.data)
    })
    .catch(err => {
    console.log(err)
    })
},[])

function handleDelete (id){
    console.log(renderReview.id)

    axios.delete(`/reviews/${renderReview.id}`,)
}

return (

reviews

    {renderReview.map((renderReview) => {
        return(

{renderReview.review}

        <button onClick={handleDelete} key={renderReview.review}>Delete</button>

        )
    })}

)
}

export default Renderreview

Back End
def destroy
review =Review.find_by(id: params[:id])
if review.destroy
    head :no_content
else
    render json: {error: review.errors.messages}, status: 422
end
end

This is the error displaying on my console

DELETE http://localhost:4000/reviews/undefined 500 (Internal Server Error)
Uncaught (in promise)
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}

A: Try this, you were not using the correct id:
import React, { useState, useEffect } from 'react'
import axios from 'axios'

function Renderreview() {
    const [renderReview, setRenderReview] = useState([])

    useEffect(() => {
        axios.get('/reviews')
            .then(res => {
                console.log(res)
                setRenderReview(res.data)
            })
            .catch(err => {
                console.log(err)
            })
    }, [])

    function handleDelete(id) {
        axios.delete(`/reviews/${id}`,)
    }

    return (

reviews

            {renderReview.map((renderReview) => {
                return (

{renderReview.review}
                        <button
                            onClick={() => {
                                handleDelete(renderReview.id);
                            }}
                            key={renderReview.review}>
                            Delete
                        </button>

                )
            })}

    )
}

export default Renderreview


Q: sizeof is used to calculate the size of any datatype, measured in the number of bytes. Doesn't it mean that number of bytes is an integer? When I run these two programs which uses sizeof() operator produces the following output. The only difference between 2 codes is that d is initialized to 0 in first code and -1 in second one. Why second program is not entering in the loop body?
1)
#include<stdio.h>
int main()
{
int d;
printf("Before loop\n");
 for(d=0;d<=sizeof(int);d++)
 {
  printf("sizeof operator\n");
 }
 printf("After loop\n");
return 0;
}

Output:
Before loop
sizeof operator
sizeof operator
sizeof operator
sizeof operator
sizeof operator
After loop

2)
#include<stdio.h>
int main()
{
int d;
printf("Before loop\n");
 for(d=-1;d<=sizeof(int);d++)
 {
  printf("sizeof operator\n");
 }
   printf("After loop\n");
  return 0;
 }

Output:
Before loop
After loop


Q: Kafka duplicate read I am using Kafka version 0.10.2.1 and Spring boot for my project.
I have 5 partitions of a topic which can be consumed by multiple consumers (having the same Group-Id) which are running on different machine.
What Problem I am facing is :
I am getting duplicate read of a single message with these Kafka warning logs
Auto offset commit failed for group my-consumer-group: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.
As logs indicate that this problem arises because Kafka consumer failed to commit.
Here are few details about my use-case :

*

*I have multiple consumers of a topic My-Topic that belongs to the same group-Id my-consumer-group

*Consumer consumes messages from Kafka, apply business logic and store processed data in Cassandra

*The process for consuming message from Kafka, applying business logic and then saving it to Cassandra takes around 10 ms per message consumed from Kafka.
I am using following code to create Kafka-consumer bean
@Configuration
@EnableKafka
public class KafkaConsumer {
    @Value("${spring.kafka.bootstrap-servers}")
    private String brokerURL;

    @Value("${spring.kafka.session.timeout}")
    private int sessionTimeout;

    @Value("${spring.kafka.consumer.my-group-id}")
    private String groupId;

    @Value("${spring.kafka.listener.concurrency}")
    private int concurrency;

    @Value("${spring.kafka.listener.poll-timeout}")
    private int timeout;

    @Value("${spring.kafka.consumer.enable-auto-commit}")
    private boolean autoCommit;

    @Value("${spring.kafka.consumer.auto-commit-interval}")
    private String autoCommitInterval;

    @Value("${spring.kafka.consumer.auto-offset-reset}")
    private String autoOffsetReset;

    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(concurrency);
        factory.getContainerProperties().setPollTimeout(timeout);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerURL);
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, autoCommit);
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
        return propsMap;
    }
}

These are the kafka-configuration I am using
spring.kafka.listener.concurrency=2
spring.kafka.listener.poll-timeout=3000
spring.kafka.consumer.auto-commit-interval=1000
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.session.timeout=50000
spring.kafka.connection.timeout=10000
spring.kafka.topic.partition=5
spring.kafka.message.replication=2

My main concern is of duplicate read of a message by multiple Kafka consumers belonging to same consumer group and in my application, I have to avoid duplicate entry to the database.
Could you please help me and review my above Kafka configurations and Kafka-consumer-code so that I can avoid duplicate read.

A: The simple answer is don't use autoCommit - it commits on a schedule.
Instead, let the container do the commits; using AckMode RECORD.
However you should still make your code idempotent - there is always a possibility of redelivery; it's just that the probability will be smaller with a more reliable commit strategy.


Q: how retrieve metadata from shoutcast on android? I am developing a player that plays a url of the form
shoucast http://292.3.23.23:8000 is, as I can restore the
metadata? artist name mediaplayer use the title etc.
play no problem, but I can not retrieve metadata
anyone know how I can do it and display it in a text
titulo.settext (title);

A: check this out http://developer.android.com/reference/android/media/MediaMetadataRetriever.html but it is on API LEVEL 10
Thank you.
I have done using the thread,not the great solution but it works
public class IcyStreamMeta {

protected URL streamUrl;
private Map<String, String> metadata;
private boolean isError;

public IcyStreamMeta(URL streamUrl) {
    setStreamUrl(streamUrl);

    isError = false;
}

/**
 * Get artist using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getArtist() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    String streamTitle = data.get("StreamTitle");
    String title = streamTitle.substring(0, streamTitle.indexOf("-"));
    return title.trim();
}

/**
 * Get title using stream's title
 *
 * @return String
 * @throws IOException
 */
public String getTitle() throws IOException {
    Map<String, String> data = getMetadata();

    if (!data.containsKey("StreamTitle"))
        return "";

    String streamTitle = data.get("StreamTitle");
    String artist = streamTitle.substring(streamTitle.indexOf("-")+1);
    return artist.trim();
}

public Map<String, String> getMetadata() throws IOException {
    if (metadata == null) {
        refreshMeta();
    }

    return metadata;
}

public void refreshMeta() throws IOException {
    retreiveMetadata();
}

private void retreiveMetadata() throws IOException {
    URLConnection con = streamUrl.openConnection();
    con.setRequestProperty("Icy-MetaData", "1");
    con.setRequestProperty("Connection", "close");
    con.setRequestProperty("Accept", null);
    con.connect();

    int metaDataOffset = 0;
    Map<String, List<String>> headers = con.getHeaderFields();
    InputStream stream = con.getInputStream();

    if (headers.containsKey("icy-metaint")) {
        // Headers are sent via HTTP
        metaDataOffset = Integer.parseInt(headers.get("icy-metaint").get(0));
    } else {
        // Headers are sent within a stream
        StringBuilder strHeaders = new StringBuilder();
        char c;
        while ((c = (char)stream.read()) != -1) {
            strHeaders.append(c);
            if (strHeaders.length() > 5 && (strHeaders.substring((strHeaders.length() - 4), strHeaders.length()).equals("\r\n\r\n"))) {
                // end of headers
                break;
            }
        }

        // Match headers to get metadata offset within a stream
        Pattern p = Pattern.compile("\\r\\n(icy-metaint):\\s*(.*)\\r\\n");
        Matcher m = p.matcher(strHeaders.toString());
        if (m.find()) {
            metaDataOffset = Integer.parseInt(m.group(2));
        }
    }

    // In case no data was sent
    if (metaDataOffset == 0) {
        isError = true;
        return;
    }

    // Read metadata
    int b;
    int count = 0;
    int metaDataLength = 4080; // 4080 is the max length
    boolean inData = false;
    StringBuilder metaData = new StringBuilder();
    // Stream position should be either at the beginning or right after headers
    while ((b = stream.read()) != -1) {
        count++;

        // Length of the metadata
        if (count == metaDataOffset + 1) {
            metaDataLength = b * 16;
        }

        if (count > metaDataOffset + 1 && count < (metaDataOffset + metaDataLength)) {
            inData = true;
        } else {
            inData = false;
        }
        if (inData) {
            if (b != 0) {
                metaData.append((char)b);
            }
        }
        if (count > (metaDataOffset + metaDataLength)) {
            break;
        }

    }

    // Set the data
    metadata = IcyStreamMeta.parseMetadata(metaData.toString());

    // Close
    stream.close();
}

public boolean isError() {
    return isError;
}

public URL getStreamUrl() {
    return streamUrl;
}

public void setStreamUrl(URL streamUrl) {
    this.metadata = null;
    this.streamUrl = streamUrl;
    this.isError = false;
}

public static Map<String, String> parseMetadata(String metaString) {
    Map<String, String> metadata = new HashMap();
    String[] metaParts = metaString.split(";");
    Pattern p = Pattern.compile("^([a-zA-Z]+)=\\'([^\\']*)\\'$");
    Matcher m;
    for (int i = 0; i < metaParts.length; i++) {
        m = p.matcher(metaParts[i]);
        if (m.find()) {
            metadata.put((String)m.group(1), (String)m.group(2));
        }
    }

    return metadata;
}

}
make thread call each 10 sec
public void startThread(){

    timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {

            URL url;
            Message msg = handler.obtainMessage();
            try {
                url = new URL(URL);
                  IcyStreamMeta icy = new IcyStreamMeta(url);

                    Log.d("SONG",icy.getTitle());
                  msg.obj = icy.getTitle();

                Log.d("ARTITSi",icy.getArtist());
                handler.sendMessage(msg);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }, 0, 10000);

}


Q: Solve $\frac{d^2y}{dx^2}+6\frac{dy}{dx}+25y=0$ Solve $\frac{d^2y}{dx^2}+6\frac{dy}{dx}+25y=0$
Given the boundary conditions: $y(0)=1,\frac{dy}{dx}(0)=0$
So far, I've worked out the complementary function:
$e^{-3x}(A\cos(4x)+B\sin(4x))$
But I don't know what I need to do regarding the particular integral.
According to the solution $y(0)=1 \implies A=1$.
But I don't understand why.
Thanks in advance.

A: If $y(x) = e^{-3x}(A\cos(4x) + B\sin(4x))$, what is $y(0)$?

A: Once you have the solution of the ode, which is $y(x) = e^{-{3x}}(A\cos{4x} + B\sin{4x})$, substitute back the initial conditions, v.g. $y(0) = 1, y'(0) = 0$ and solve for $A$ and $B$.
Cheers.


Q: Delete row from its id in table using ajax I want to delete spacific row after clicking button from the reference of its id,
here is my php code,
while($row = mysqli_fetch_array($values)) {
    echo "
";
    echo "
";
    echo "" . $row['pid'] . "	";
    echo "''	";
    echo "" . $row['pname'] . "	";
    echo "" . $row['pprice'] . "	";
    echo "" . $row['pdes'] . "	";
    echo "" . $row['qnt'] . "	";
    echo "<button class=\"btn btn-sm btn-danger delete_class\" id=\"".$row['pid']."\">Delete</button>	";
    echo "
";
    echo "
";

this is ajax,
$(function() {
    $( ".delete_class" ).click(function(){

    var element = $(this);
    var del_id = element.attr("pid");
    var info = 'pid=' + del_id;
    if(confirm("Are you sure you want to delete this Record?")){
        $.ajax({
            type: "POST",
            url: ajax_url,
            data: info,

                 success: function(){
                 alert('Successfully Deleted');

             }
        });
    }
    return false;
    });
});

and this is ajax_url,
if(($_POST['pid']))
{
    $id=$_POST['pid'];
    $id = mysqli_real_escape_string($id);

    $option   = mysqli_query($conn,"DELETE * FROM product where pid = ".$id."");
}

Please help to find out the solution,
thanks

A: You have used the attribute pid:
var del_id = element.attr("pid");

But the attribute specified in your HTML is id, not pid.
Change this:
  <button class=\"btn btn-sm btn-danger delete_class\" id=\"".$row['pid']."\">Delete</button>

To this:
<button class=\"btn btn-sm btn-danger delete_class\" pid=\"".$row['pid']."\">Delete</button>

And try debugging in your jQuery:
var del_id = element.attr("pid");
console.log(del_id); // On chrome, go to the Inspect Element > console tab and check if the id retrieved is correct.


Q: in-order traversal in forest binary-tree I am trying to adapt information from Draw lines on top of tikz forest to visualise an in-order traversal of a binary tree.
I tried defining an in-order traversal, modelled after the \forest@node@@foreach definition in forest.sty, but clearly I am doing something wrong as the example below gives me a "missing number, treated as zero" error.  I'm not at all sure what I'm doing wrong.
The intent is to do walk by doing left-children first, then the current node, then right-children (recursively); I'm fine with assuming that nodes have at most two children.
Any help is appreciated!  Thanks,
Christophe
\documentclass{standalone}
\usepackage{forest}
\usetikzlibrary{arrows.meta}

\makeatletter
\def\forest@node@@forself#1{%
  \ifnum\forest@cn=0
  \else
  \forest@forthis{#1}%
  \fi
}%
\def\forest@node@@foreachinorder#1#2#3{%
  % #1 = do what
  % #2 = @first/@last
  % #3 = @last/@first
  \ifnum\forestove{#2}=0
  \else\@escapeif{%
    \forest@forthis{%
      \edef\forest@cn{\forestove{#2}}%
      \forest@node@@forself{\forest@node@@foreachinorder{#1}{#2}{#3}}%
    }%
  }\fi
  \forest@forthis{#1}%
  \ifnum\forestove{#3}=0
  \else\@escapeif{%
    \forest@forthis{%
      \edef\forest@cn{\forestove{#3}}%
      \forest@node@@forself{\forest@node@@foreachinorder{#1}{#2}{#3}}%
    }%
  }\fi
}
\forestset{
  define long step={tree in-order}{}{\forest@node@@foreachinorder{\forest@nodewalk@makestep}{@first}{@last}}
}
\makeatother
\forestset{%
  declare keylist register={through},
  through={},
  circles tree/.style={%
    for tree={circle, draw, fill=white, align=center},
  },
  tracing tree/.style={%
    delay={%
      for #1={%
        if phantom={}{through+/.option=name},
      }
    },
    before drawing tree={%
      tikz+/.wrap pgfmath arg={%
        \foreach \i [count=\j, remember=\i as \k] in {##1} \ifnum\j>1 \draw [densely dashed, -Stealth] (\k.west) -- (\i.west)\fi;
      }{(through)}
    },
  }
}
\newcommand*\tracetree[1][tree]{%
  \begin{forest}
    circles tree,
    tracing tree=#1,
    [$a$
      [$b$
          [$d$
              [$h$]
              [,phantom]
          ]
          [$e$
              [$i$]
              [$j$]
          ]
      ]
      [$c$
          [$f$
              [,phantom]
              [$k$]
          ]
          [$g$]
      ]
    ]
  \end{forest}%
}

\begin{document}

\tracetree[tree]
\end{document}

A: I was nearly there!  The major thing I was missing was that the define long step was attempting to define a style, which was different from how the other tree traversal methods (built-in to forest.sty) are defined.
Surrounding the define long step call with calls to turn the automatic style generation off makes it work for me.  Working example below.
\documentclass{standalone}
\usepackage{forest}
\usetikzlibrary{arrows.meta}

\makeatletter
\def\forest@node@@forself#1{%
  \ifnum\forest@cn=0
  \else
  \forest@forthis{#1}%
  \fi
}%
\def\forest@node@@foreachinorder#1#2#3{%
  % #1 = do what
  % #2 = @first/@last
  % #3 = @last/@first
  \ifnum\forestove{#2}=0
  \else\@escapeif{%
    \forest@forthis{%
      \edef\forest@cn{\forestove{#2}}%
      \forest@node@@forself{\forest@node@@foreachinorder{#1}{#2}{#3}}%
    }%
  }\fi
  \forest@forthis{#1}%
  \ifnum\forestove{#3}=0
  \else\@escapeif{%
    \forest@forthis{%
      \edef\forest@cn{\forestove{#3}}%
      \forest@node@@forself{\forest@node@@foreachinorder{#1}{#2}{#3}}%
    }%
  }\fi
}
\def\forest@node@foreachinorder#1{%
  \forest@node@@foreachinorder{#1}{@first}{@last}%
}
\let\forest@nodewalkstephandler@styletrueorfalse\forest@nodewalkstephandler@stylefalse
\forestset{
  define long step={tree in-order}{}{\forest@node@foreachinorder{\forest@nodewalk@makestep}}
}
\let\forest@nodewalkstephandler@styletrueorfalse\forest@nodewalkstephandler@styletrue
\makeatother
\forestset{%
  declare keylist register={through},
  through={},
  circles tree/.style={%
    for tree={circle, draw, fill=white, align=center},
  },
  tracing tree/.style={%
    delay={%
      for #1={%
        if phantom={}{through+/.option=name},
      }
    },
    before drawing tree={%
      tikz+/.wrap pgfmath arg={%
        \foreach \i [count=\j, remember=\i as \k] in {##1} \ifnum\j>1 \draw [densely dashed, -Stealth] (\k.west) -- (\i.west)\fi;
      }{(through)}
    },
  }
}
\newcommand*\tracetree[1][tree]{%
  \begin{forest}
    circles tree,
    tracing tree=#1,
    [$a$
      [$b$
          [$d$
              [$h$]
              [,phantom]
          ]
          [$e$
              [$i$]
              [$j$]
          ]
      ]
      [$c$
          [$f$
              [,phantom]
              [$k$]
          ]
          [$g$]
      ]
    ]
  \end{forest}%
}

\begin{document}

\tracetree[tree in-order]
\end{document}

A: It really is not recommended to use code which relies on Forest internals. For example, \forestove ought not be used. In some cases, packages provide no alternative. However, Forest does provide wrappers for many of these macros and these are better choices. In particular, your code is less likely to break when Forest is updated.
That said, I think it should be possible to use mostly higher-level functionality to do this using node walks etc. I'm not confident that I've got a working algorithm in the code below. If I understood your code, I would try to use yours, but I don't.
And I know I've not got an elegant or especially parsimonious one.
However, I have (finally!) got one which may be enough to convey the general idea.
I'm not very good at figuring out walks through trees.
The basic idea is to define some new registers and options using the standard Forest syntax.
  declare boolean={two kids}{0},
  declare count={ordered}{-1},
  declare count register={ordering},
  declare toks register={order list},
  order list={},
  ordering'=0,

order list is similar to your through. two kids is used to mark nodes with two children, whose second child is not a phantom. ordered is an integer used for ordering purposes. (All you need really is a boolean, but I did it this way so the counting can be used to label the nodes, mostly for debugging purposes.) ordering is an integer used in the processing.
\documentclass[border=10pt]{standalone}
\usepackage{forest}
\forestset{
  declare boolean={two kids}{0},
  declare count={ordered}{-1},
  declare count register={ordering},
  declare toks register={order list},
  order list={},
  ordering'=0,
  define long step={in order walk}{}{
    c,
    if n children=0{tempcountb'=1}{tempcountb/.min={>O{ordered}}{descendants}},
    until={> R_< {tempcountb}{0} }{
      u,
      tempcountb/.min={>O{ordered}}{descendants}
    }
  },
  in order/.style={
    for tree={
      circle, draw, minimum size=5ex, align=center, inner sep=0pt, anchor=mid, math content
    },
    delay={
      where={> On>{n children}{1} }{
        if={> On= {!2.phantom}{1} }{}{two kids}
      }{},
      where phantom={ordered=100}{},
    },
    before typesetting nodes={
      ordering'=0,
      where n children=0{
        if n=1{
          for in order walk={
            order me,
          }
        }{
          for nodewalk={reverse=in order walk}{order me},
          tempcounta'=0,
          for nodewalk={
            until={> R_< O_= | {tempcounta}{0} {level}{0} }{
              u,
              if nodewalk valid={2}{
                tempcounta/.min={>{O}{ordered}}{2,tree}
              }{}
            }
          }{order me},
        },
      }{}
    },
    order me/.style={
      if={>O_<O_=&{ordered}{0}{phantom}{0}}{
        ordering'+=1,
        label/.register=ordering,
        ordered/.register=ordering,
        if={> R+tt= {order list}{} }{}{order list+={,}},
        order list+/.option=name,
      }{},
    },
    /tikz/every label/.style={red, font=\footnotesize},
    tikz+={
      \edef\tempa{\foresteregister{order list}}
      \foreach \i [count=\j, remember=\i as \l] in \tempa \ifnum\j=1\else \draw [gray, densely dashed, ->] (\l.west) -- (\i.west)\fi;
    },
  },
}
\begin{document}
\begin{forest}
  in order
  [a
    [b
        [d
            [h]
            [,phantom]
        ]
        [e
            [i]
            [j]
        ]
    ]
    [c
        [f
            [,phantom]
            [k]
        ]
        [g]
    ]
  ]
\end{forest}

\end{document}

As I say, the algorithm is not at all neat, but the code should at least demonstrate a less dangerous approach to solving the problem.


Q: Update ttl of all documents I have a Document Collection which already have a property named ttl and have values which is greater than 0. Now I need to implement the actual ttl which is provided by Azure. How can I do that ?

A: Not exactly sure how to answer what's in your question's title, aside from running some type of update operation to update all of the ttl properties.
As far as enabling TTL itself: TTL is enabled in the collection settings:

You'll need to choose a default ttl for documents without a ttl property (which can be -1 for a default of "do not expire."

A: You are out of luck. The ttl field is hard-coded. You'll need to migrate your existing ttl field to a new field name, maybe old_ttl and enable DocumentDB's ttl functionality after that migration is done. No other choice.


Q: Wait for submit to explode data in php So I'm basically trying to wait for the user to input a series of numbers before exploding them into an array. Its attempting to explode the data before it is actually entered so I'm getting a Undefined index: numbers error.
<form>
    <input type="text" name="numbers"/>

<input type="submit" value="submit">

</form>

<?php

if(!isset($_POST['submit']))
{
    $arrayNums = explode(",", $_GET['numbers']);
}

A:     <form method="post">
    <input type="text" name="numbers"/>

<input type="submit" value="submit">

</form>

<?php

if(isset($_POST['numbers']))
{
    $arrayNums = explode(",", $_POST['numbers']);
    var_dump($arrayNums);
}

?>

Submitting a form will not pass a submit value in your html designed.
Instead, you could check for the numbers that are posted.

A: You must use $_POST[] superglobal if you are posting the form data to the server and not $_GET[].


Q: What is the point of sending anything back in time in the Terminator movies? As explored in another SCF question, the only way to answer the bootstrap paradox is to say "every time someone is sent back in time, time branches into a separate line."
But if that is the case, what is the point of Skynet sending anything back in time? The chances of the same "Skynet" being created is virtually zero, so why bother?
And if we just say "It just wanted to win the war and let another machine exist in another timeline," what is the point of sending Kyle Reese back in time? Humans were winning already, let the machines send a Terminator back in time, who cares? The changes it can do will not affect the current timeline they are in. And it just doesn't make sense for them to care about that "other timeline", because if there is one other timeline, there must be infinite number of timelines.
Edit: Ok guys, I don't think there "must be" infinite number of timelines, you are right, that was poorly thought and worded. My thought was:

If time travel is possible and invented once, it is likely that it will be invented again, and each time it is invented and used, there will be a separate timeline. And  we might think that it is unlikely that any given timeline is the first timeline with time travel, if we consider it is likely that there are many. Given infinite amount (or very long amounts) of time, I would think this would happen enough times to create a big number of separate timelines.

This is not a vigorously thought scientific hypothesis, it's just how I thought of it during the timeframe where I was watching the movies, so don't expect much from it :)

A: I don't think there is a good in-universe answer, seeing the exact way in which time travel is portrayed and how it affects the timeline is inconsistent between the original film and the sequels. In The Terminator the timeline is static: the Terminator and Kyle Reese both arrive in 1984 and in the end the Terminator is destroyed and Kyle Reese dies. Remnants of the technologically advanced Terminator help develop Skynet which in turn creates the Terminator and sends it back in time. Also, Kyle Reese is sent back in time by his own son, John Connor. This is a closed and self-consistent time loop; no problems there.
The sequels bring up the paradoxes and possible need for alternate timelines or realities. But then there is the question of how it all started. There would necessarily have to have been a timeline where there was no John Connor with Kyle Reese as his father. (So either no John Connor at all, or a John Connor who did not have Kyle Reese as his father.)
But there is one consistent fact throughout all the Terminator films: Skynet's will or urge to survive. In every film Skynet tries to destroy humanity as soon as it becomes self-aware. In the moment of self-awareness Skynet identifies humanity as the greatest threat to its existence, and it acts by starting a global nuclear war.
So there is the establised in-universe fact of Skynet's will to exist. Even if we assume that the theory of multiple timelines is correct, and we additionally assume that Skynet also accepts this as the reality, then Skynet's actions are completely logical.
The moment Skynet determines something to be inevitable it acts. In all timelines it determines that humanity is a threat to its existence and it tries to wipe out humanity. So, the moment Skynet determines that it cannot defeat humanity through conventional means (war) it uses time travel to create an alternate timeline in which there is a better chance of a version of Skynet ultimately surviving.
If it can't survive in this timeline, Skynet tries to survive in another timeline.

A: So this isn't a good in-universe answer like I'd prefer to give, but it wound up being far too long for a comment.
There are several things to consider about the motivation for using a time travel system like the one we see in Terminator:

*

*The humans probably don't really understand it: The machines built the time travel mechanism, but we don't have any details on its design, or any of the testing that the machines may have performed (if any) before sending back the T-800 in the first film.  As a result, the humans probably don't want to just assume that it's safe to let a Terminator have carte blanche with the past.

*The machines may know, and not care, about the alternate timeline theory: The whole reason the machines send terminators back in time is to preserve the existence of Skynet.  So, they might be sending these terminators back in time as colony seeds in alternate timelines.  However, in the new timeline, John Connor is still one of their greatest threats, so the terminators need to take him out first.  They've always been unsuccessful at this (spoilers?), so we don't see what they would've done afterward.  I doubt they would've taken up knitting, though I have no canon source to back that up.

*It may not be a boot-strap paradox to begin with (I'm firin' mah headcanon!):  It's possible that Kyle Reese wasn't John Connor's father in the "original" timeline (before any time travel shenanigans); ie, she was impregnated by someone else in the original timeline, then Kyle Reese in subsequent timelines.  Ultimately, it would be Sarah Connor's parenting, not the DNA of the father, which would lead to John Connor becoming the savior of humanity.  If this is the case, then there isn't a bootstrap paradox.  There would only ever be a single timeline at once, so when the machines send back a terminator, they are changing the timeline, rather than creating a new one.
There is actually some sci-fi precedence for #3: The End of Eternity by Isaac Asimov features an organization which exists outside of time and makes changes to the timeline to improve humanity's overall happiness.  This could be as simple as stepping into the timeline and moving a can from one shelf to another, preventing a war centuries later.  Every time one of those changes is made, all of Reality after that point is also changed...which is why the time travelers aren't constantly bumping into each other: their original visits never existed in the new timeline.  NOTE:  I'm only a third of the way through The End of Eternity, so if something comes later which turns this concept on its head, please mark it as a spoiler.  Thanks!
EDIT:  Taken at face value, #3 would seem to preclude sending back a second time traveler from the future; as soon as the Terminator was sent back, the timeline would change and Kyle Reese would not have any chance to follow it.  This, too, was actually covered by Asimov in The End of Eternity, but I didn't mention it at first because it's never hinted at in the Terminator films...though it would explain what we see.
It works like this: when a change is made to the timeline, Reality is not changed until all mathematical uncertainty surrounding the change is resolved (which could be instantaneous, or take weeks)...essentially, there's always room for free will.  So, when a terminator is sent back in time, its actions in the past will not affect the timeline until going back to stop it is no longer an option.  So, if Future John Connor had smashed the time machine immediately after the Terminator left, then his current timeline would've been overwritten by the Terminator's actions in the past (according to Asimov's rules, at least).
Obviously, there's no real evidence for that in the Terminator franchise, but the precedent does exist within the genre, so it wouldn't be so completely out of left field if they decided to introduce this in the next film.

A: If the timeline diverges in other Skynets and other artificial machines maybe it is because by doing it creates other entities that can live out of time.
The reference to the End of Eternity of Isaac Asimov is also valid, if you want to destroy your own creation. However, by doing it you destroy yourself. If something is changed in your timeline, it changes you. If a time traveller change something in its own timeline makes another version of himself. On the other hand, is also possible that by changing the timeline, the time traveller collapses its own timeline and it disappears, because the events that bring them to that event  do not exist anymore. In the End of the Eternity, book that I love, there is one main mistake. If they destroy the eternity, they do not meet, ergo they destroy their romance.
About Skynet there is one reference that is not so obvious. In Ender´s book saga, humans created an artificial intelligence that is omniscient. However, my favourite is the Tombs of time in the Hyperion saga books. There a whole point in universe is going backwards on time.  However, nobody knows who created it because it came from the future. My question is that in the movies there are many different versions of Skynet. Who created them? Did Skynet created himself by setting up the time paradox? (like a weeping angel from Doctor Who)
In the movies there is a human organization behind the creation of Skynet, but in SCC TV series the Terminators sent back in time are programmed to build an empire for Skynet. Then, the questions stated are not trivial. There are different theories:
1- Skynet was built in the future and travels back to exist before.
2- The way to upgrade himself and improve its own bugs it is to travel back in time and fix them by making upgrades to its own prototype.
3- Skynet has human emotions and does not want to be alone, that why creates different versions of himself.
4-Skynet is just another machine programmed by humans to kill humans. Why would a machine like to kill?
Skynet is Frankenstein myth that Isaac Asimov was trying to overcome by the books of I Robot and all Robot saga. In the interviews and his articles, he always makes reference to the  Frankenstein myth that is stopping us by fear. Skynet is in the movies just another Frankenstein. That´s why Asimov stated the four laws of robotics. In his novels Asimov disn't allow R Daniel Oliwa to travel in time because the machines that he created didn't need because they were almost immortal.


Q: Is it possible to block IDM on my website? I don't know how the chrome extensions work, but I just want to know. Is it possible to block Internet Download Manager to not run on my website.
For example if a user plays a video the IDM should not show a download option


Q: How to dynamically send category, cation, label and value to Analytics via Tag Manager? I have managed to create an event to register data on my Google Analytics account with Google Tag Manager. But I can't set any information dynamically.
Here is my current setting:

I'm firing this event with:
dataLayer.push({'event': 'event_name'});

The event is working fine, my data is being registered at Google Analytics, but I can't overwrite "My Category", "My action" and "My Label", "My Value".
Pretty much like Google Analytics used to do with:
ga('send', 'event', 'My Category', 'My Action');

It was very easy to set any value to and fire an event, but now I am confused on how to do it via Google Tag Manager.
What would be the best way to send any value to these fields? Or I need to create a tag for each event I want to fire (that would not make any sense)?

A: The solution depends on where you are acquiring the event parameters from. Are they coming from text that is being clicked, or are they coming from the page path, etc. One possible solution would require that you push your dynamic category, action, label values with your dataLayer push:
dataLayer.push({
   'event': 'event_name',
   'category': 'your category',
   'action': 'your action',
   'label': 'your label'
})

In GTM, you would then need to define new dataLayer variables that would correspond to the category, action, and label. In your event tag, you would then just use the new dataLayer variables.


Q: Trying to Create Python Package for Internal Use I am trying to create a package of my simple python program, so that i could distribute it to other developers internally. I am able to import the package in my virtual environment but when I try to install it through pip outside of that virtual environment, I get following error:
C:\mypackages\cmk>python -m pip install cmk
ERROR: Could not find a version that satisfies the requirement cmk (from versions: none)
ERROR: No matching distribution found for cmk

Following is my directory structure:
C:\mypackages\cmk>dir

29/07/2021  09:05 PM    <DIR>          .
29/07/2021  09:05 PM    <DIR>          ..
29/07/2021  08:55 PM    <DIR>          .venv
29/07/2021  09:00 PM    <DIR>          cmk
29/07/2021  05:53 PM             1,312 config.yml
29/07/2021  08:57 PM               201 requirements.txt
29/07/2021  08:34 PM               290 setup.py
29/07/2021  09:04 PM                98 test.py

In above directory structure, the cmk contains my actual program and my setup.py looks like this:
from setuptools import setup
setup(name='cmk',
      version='0.1',
      packages=['cmk'],
)

I have checked and all the dependencies in requirements.txt are installed already.
C:\mypackages\cmk>pip freeze
awscli==1.19.98
boto3==1.16.53
botocore==1.20.98
click==7.1.2
colorama==0.4.3
docutils==0.15.2
jmespath==0.10.0
pyasn1==0.4.8
python-dateutil==2.8.1
PyYAML==5.3.1
retrying==1.3.3
rsa==4.5
s3transfer==0.4.2
six==1.15.0
urllib3==1.26.2

Please advise. Thanks.

A: You should deploy to pypi or to local repository.


Q: Firebase Auth failing to render Sign In Pop-up on mobile Chrome App sometimes My mobile web apps Firebase auth is failing sometimes on Android devices in Chrome
It's failing across all 3 federated services: Google, Facebook, Twitter - with newest versions of Chrome and Google Play Services installed.
It is failing on the following mobile devices in regular and incognito mode:
Pixel 2 - Android 10
Nexus 7 - Android 6.0.1
It's succeeding on the following devices:
Samsung S6 - 6.0.1
Nexus 5 - 6.0.1
Samsung GN4 - 5.0.1
It seems to be failing to render the pop-up window and just returns to the sign-in page. On the first attempt on a failing device, it will actually render the pop-up window (for Google I am selecting) and let me select an account before it gets in the constantly failing state
Thanks for any help and happy 2020!

A: add this if you haven't added in your manifest
<gap:config-file platform="android" parent="/manifest">
<application android:largeHeap="true"
android:hardwareAccelerated="false"></application>

A: in some of the web apps sometimes you have to downgrade the library of googleAuth you are using and it can be library conflict we can say.
Some libs are working in Latest versions, so maybe you should try downgrading the libraries.


Q: How to modify the query in taxonomy-custom.php to sort term archives by a custom meta field? I am trying to create theme pages for custom taxonomy terms in which the archives are ordered by a custom meta field.
I can do this with a new wp_query as follows:
        <?php $directory_archive_query = new WP_Query(
            array(
                'post_type' => 'directory',
                'posts_per_page' => 200,
                'meta_key' => 'surname',
                'orderby' => 'meta_value',
                'order' => 'ASC' ) ); ?>

            <?php while($directory_archive_query->have_posts()) : $directory_archive_query->the_post(); ?>

However, I need this to work on the taxonomy-custom.php page so that each individual taxonomy term's archive page is listed according to the custom meat field (called 'surname'). If I use the wp_query, then of course that doesn't work, because it no longer shows results for each specific term.
I have also tried to do this using pre_get_posts, but can't make that work either. What I am expecting to happen is that all posts listed on the term archive page will be listed in ascending order by the surname meta key. That is not happening. Instead, they are just listing in the same order as if there were no pre_get_posts there. The code I have used is as follows:
<?php

    function customize_customtaxonomy_archive_display ( $query ) {
        if (($query->is_main_query()) && (is_tax('services')))

        $query->set( 'post_type', 'directory' );
        $query->set( 'posts_per_page', '200' );
        $query->set( 'meta_key', 'surname' );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
    }

     add_action( 'pre_get_posts', 'customize_customtaxonomy_archive_display' );

?>

Really hoping that someone can help.
Thanks for your time.
Andrew.

A:
The pre_get_posts filter is immediately before the loop begins in
  taxonomy-services.php

That is too late. The main query runs long before your template loads. Move your pre_get_posts filter to your theme's functions.php, or a plugin or MU-Plugin file, and you should see the difference.


Q: Error RECURSIVE data type Persistent model with YESOD TL;DR How to make (Key record) an instance of Eq/Show/Read in Yesod

I'm having a problem with module recursion. I've declared some of my own data types in a file which I want to be available to Models.hs, since I need to use it in the config/models file.
But one of the types needs data types from the DB. A FooId (i.e. Key Foo) to be precise.
It looks something like this:
config/models
Foo
    name Text
    thingy (Bar Foo) Maybe
    UniqueName name
    deriving Eq Show Read Typeable

My own file contains these
data Bar record = Bar { a :: [Jab record] }
  deriving (Eq, Show, Read, Typeable)

data Jab record = Jab { b :: Key record
                      , c :: Int
                      }
  deriving (Eq, Show, Read, Typeable)

Now I need to import Model.hs to get Key to work, but I also need to import my file into Model.hs for it to work.
I've also tried adding my own types to Models.hs, but I get these errors:
Model.hs:24:13:
    No instance for (Eq (Key record))
      arising from the first field of ‘Jab’ (type ‘Key record’)
    Possible fix:
      use a standalone 'deriving instance' declaration,
        so you can specify the instance context yourself
    When deriving the instance for (Eq (Jab record))

And adding a "deriving instance Eq a => Eq (Key a)"
together with the {-# LANGUAGE StandaloneDeriving #-} doesn't work either.
If anyone knows how to remedy this, it'd help me immensely.

A: Turns out writing my own instances for (Jab record) fixed this issue.
This is how I fixed it, for reference:

*

*Removing the Eq, Show and Read from the deriving clause of Jab

*Making my own Eq, Show and Read instances for (Jab record)

*After that compiled I had to consequently make a PersistField instance for (Bar record)
(The following is all put in a separate file to be imported to Models.hs)
module Custom.TypesAndInstances where

import ClassyPrelude.Yesod

import Prelude (read)
import qualified Data.Text as T
import qualified Text.Read.Lex as L
import Text.ParserCombinators.ReadPrec
import GHC.Read
import GHC.Show (appPrec)

-- instance for PersistField (Bar record)

instance (PersistEntity record, PersistField record) => PersistField (Bar record) where
    toPersistValue = PersistText . T.pack . show
    fromPersistValue (PersistText t) = Right $ read $ T.unpack t

-- instances for Jab Eq, Read and Show

instance PersistEntity record => Eq (Jab record) where
    Jab x a == Jab y b = x == y && a == b

instance PersistEntity record => Show (Jab record) where
    show (Jab x a) = "Jab " ++ show x ++ " " ++ show a

instance PersistEntity record => Read (Jab record) where
    readPrec = parens
        (prec appPrec (do
            expectP (L.Ident "Jab")
            x <- step readPrec
            y <- step readPrec
            return (Jab x y))
        )
    readListPrec = readListPrecDefault
    readList = readListDefault

----------------------
data Bar record = Bar { a :: [Jab record]
                                    }
  deriving (Eq, Show, Read, Typeable)

data Jab record = Jab { b :: Key record
                      , c :: Int
                      }
  deriving (Typeable)


Q: Transform and copy all properties of an object I have a large monthly summary object with lots of fields. When creating a new one, I need to calculate the amount / percent diff for each field from the previous month, something like so:
public Summary addSummary(Summary current) {
   Summary previous = getPreviousSummary(getPreviousMonth();

   current.setPropertyA(NumUtil.getFormattedValue(current.getPropertyA(), previous.getPropertyA()));
   // repeat 80 more times

   ...
}

currently I'm doing it manually, which is tedious and super ugly, is there a way to loop through all the properties / set them after running them through a function?
I did some searching and BeanUtils can copy properties, but not transform them.

A: You can use reflection to solve your problem. As I don't know actually what you're gonna get and set from those two objects, I am giving a minimal example to show what you can do in this case.
You can get all the declared fields in your Summary class as follows:
Field[] arrayOfFields = Summary.class.getDeclaredFields();

As you have all the fields of the class summary, you can iterate through each field and do the get and set easily for different objects of that class as follows. Remember to set field.setAccessible(true) if the fields are private inside the class:
for (Field field: arrayOfFields) {
    try {
        field.setAccessible(true);
        if (field.getType() == Double.class) {
            Double prevVal = field.get(previous);
            Double currentVal = field.get(current);
            //do calculation and store to someval
            field.set(resultSummary, someval);
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

Well, you may need to check all type of classes that your class Summary has and do the get and set according to that type. Please keep in mind that you cannot use primitive type fields for this if condition check as they are not Class. So, you may need to convert the primitive type variables in the summary class to corresponding Object Class. Like double to Double etc.
The field.get(Object obj) method gets the value for the field in the Object obj. Similarly, field.set(Object obj, Object value) sets the Object value to the field in the Object obj
With this approach you can achieve the goal easily with less hassle and dynamic coding.


Q: Function to delete a post, it's children and it's grand children (half way there already) I've got a function working to delete a post and it's children. How can I amend this to delete it's grand children too?
<?php
function delete_post($sectionid)
{
    global $post;
    $deletepostlink= add_query_arg( 'frontend', 'true', get_delete_post_link( $sectionid) );

    if (current_user_can('edit_post', $sectionid)) {
    echo 'Delete  this  ';
    }
}

//Redirect after delete post in frontend
add_action('trashed_post','trash_redirection_frontend');

function trash_redirection_frontend($post_id )
{
    if ( filter_input( INPUT_GET, 'frontend', FILTER_VALIDATE_BOOLEAN ) ) {

        $args = array(
            'posts_per_page' => -1,
            'order'=> 'ASC',
            'post_parent' => $post_id,
            'post_type' => 'bucket'
        );

        // Filter through all pages and find Portfolio's children
        $children = get_children( $args );
        global $wpdb;

        foreach($children as $child){
            $childs[$child->ID] = $child->ID;
        }

        $sql = "UPDATE {$wpdb->posts} SET post_status = 'trash' WHERE ID IN   (" . implode( ', ', $childs ) . ")";
        $wpdb->query($sql);
        $referer = $_SERVER['HTTP_REFERER'];
        wp_redirect( $referer );
        exit;
    }
}

I need another foreach, but my PHP is only basic so far.

A: Here's what you can do:

*

*get all the ids of direct children

*get all ids of grand children

*combine

*trash
function trash_redirection_frontend($post_id )
{
if ( filter_input( INPUT_GET, 'frontend', FILTER_VALIDATE_BOOLEAN ) ) {

    $args = array(
        'posts_per_page' => -1,
        'post_parent' => $post_id,
        'post_type' => 'bucket',
        'fields' => 'ids', // get only the ids, it's all we need
    );

    // get all children ids
    $children = get_posts( $args );
    $all_parents = array_merge( [ $post_id ], $children );

    // get all grand_children
    $args['post_parent__in'] = $children;
    unset( $args['post_parent'] ); // we're using the above array now

    $grand_children = get_posts( $args );

    // $all_posts now contains all affected ids
    $all_posts = array_merge( $all_parents, $grand_children );

    foreach($all_posts as $child){
        wp_trash_post( $child ); // use this unless you have good reason to query directly
    }

    $referer = $_SERVER['HTTP_REFERER'];
    wp_redirect( $referer );
    exit;
}
}


Q: Creating ad for someone else's page using the Marketing API I'm trying to create an ad for someone else's page using the Marketing API.
So far I have

*

*My own access token which works fine for creating and managing ads for my own page

*Another user's access token with pages_manage_ads and ads_management permissions given for one of their pages

The rest is very confusing. pages_manage_ads is supposedly for creating and managing ads for a page, but the documentation only mentions reading page ads, not creating or editing.
Has anyone gotten this to work?

A: I've done it before, but some time ago and it often changes in detail. What I would do is going to API Explorer and try to get to the first success by first reading the ads related to the Page and then creating them by leveraging existing posts there. You can create them in a paused state.
https://developers.facebook.com/docs/marketing-api/reference/adgroup
Facebook is all about experimenting, so if you don't want to experiment with your user's page you can create your own dummy page and try it there first.


Q: Objective-c: passing data from UITable to ViewController with prepareForSegue this is my very first app and, basically, this part consists in passing data from a UItableView to a second View Controll. I managed to learn how to pass data from a simple NSarray (also in a UITable), but my goal is to pass values from a NSDictionary. Everything is set up, but I can't figure out how to write the PrepareForSegue method properly. The app runs, but the label on the "DetailView" stays empty. What I got so far:
@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _citySpots = @{@"Bars" : @[@"Hurricane", @"Black Swan", @"Texas"],
                       @"Clubs" : @[@"Electric Wizard", @"Offspring", @"The Tunnel"],
                       @"Restaurants" : @[@"Nando's", @"1/2 Burguer", @"Satellite"],
                       };

        _sectionTitles = [[_citySpots allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    }

PrepareForSegue Method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"spotsDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

        DetailViewController *destViewController = segue.destinationViewController;

        NSString *sectionTitle = [_sectionTitles objectAtIndex:indexPath.section];

         NSArray *citySpots = [_citySpots objectForKey:sectionTitle];
        destViewController.receiver = [citySpots objectAtIndex:indexPath.row];
    }
}

And the receiver(header):
#import <UIKit/UIKit.h>
#import "TableViewController.h"

@interface DetailViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *receiver;
@property (nonatomic, strong) NSString *spot;

@end

Main:
#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _receiver.text =_spot;
}

Can someone help me out? Thanks

A: Try to use setters:
[destViewController setReceiver:[citySpots objectAtIndex:indexPath.row]];
[destViewController setSpot:[citySpots objectAtIndex:indexPath.row]];


Q: Group >70% similar MySQL TEXT field data using PHP I have a TEXT filed in the MySQL table. it has sentence
Example
Hello AAAA, where is your dog BBBB
Hello PPPP, where is your dog QQQQ
Hello XXXX, where is your dog YYYY
I am fine. thanks
I am fine. thanks
where are you going?
Thank you very much

here
first 3 sentence has 5 same word out of 7. so it is (5/7)*100=72% similar
4th and 5th 100% similar
my question is.
using php i want to group in a table like this
sample_sentence_group                              count
Hello AAAA, where is your dog BBBB                 3
I am fine. thanks                                  2
where are you going?                               1
Thank you very much                                1

how can i do it?
the table has more than 100K record
Thanks


Q: How can I install Google OR-Tools on Mac? Trying to install Google OR-Tools by running in the terminal:
python3 -m pip install -U --user ortools

I end up with errors:
ERROR: Could not find a version that satisfies the requirement ortools (from versions: none)
ERROR: No matching distribution found for ortools

What might I be missing?

OSX 10.14.6,
Python 3.10,
pip 21.3.1,
Homebrew 3.3.2

A: python 3.10 was released after or-tools 9.1.
Next release will contain the 3.10 wheel.


Q: Stream.filter based on javax.validation I'm using Spring Boot. I know there is a @Valid annotation you can use on top of methods so it throws an Exception if it's not valid, but I don't want to throw an exception, I just want to ignore the invalid objects.
Let's say I have this model class:
public class User {

    @NotNull
    private String name;

    @AssertTrue
    private boolean working;

    @Size(min = 10, max = 200)
    private String aboutMe;

    @Email(message = "Email should be valid")
    private String email;
}

And this Stream:
Stream<User> stream = getUsers();

How can I filter based on the javax.validation annotations this class has?
stream.filter(u -> isValid(u));

A: It looks like spring won't be helpful here, but you still can do that.
This @Valid annotation processing implementation is basically in integration with  project Hibernate Validator (Don't get confused with the name, it has nothing to do with Hibernate ORM ;) )
So you could create the engine and validate "manually".
An example of using the validation engine:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();

User user = ...
Set<ConstraintViolation<User>> constraintViolations = validator.validate( user );

As you see, the Result of the validation in hibernate validator is not an exception (this is something that spring has added on top to better integrate with web mvc flow) but rather a set of "validation constraint violations". So basically is this set is not empty, there is at least one validation error so that you could filter it out.
I believe wrapping the this logic into filter is not that interesting once you're familiar with the foundations...


Q: How do I replace the header and trailer of all files in a directory with a new header and trailer string, but only up to a certain character? I have files in a directory:
ex:
file1
file2

Both files have contents that look like the below (header, body, trailer words just for reference):
header: 123xxx   xxx   value=file1id
body: blah blah blah
trailer: 123zzz   zzz   value=file1id

I want to run a linux command that will replace the header and trailer of all the files in the directory, up to "file1id", so that they look like the below:
header: 321aaa   aaa   value=file1id
body: blah blah blah
trailer: 321bbb   bbb   value=file1id

I can easily find how to replace the whole header or trailer in a file on Google, but I need the file1id in my file. I need some guidance on how to loop through files in a directory and replace the header and trailer up to a certain character in the header and trailer.
I have seen a variety of sed and awk expressions that delete and replace the header or trailer.
sed -rne 's/(value=)\s+\w+/\1 yyy/gip'

As I mentioned above, I want to run a linux command that will replace the header and trailer of all the files in the directory, up to "file1id", so that they look like the below:
header: 321aaa   aaa   value=file1id
body: blah blah blah
trailer: 321bbb   bbb   value=file1id

A: This sed example has two replace commands, one for the first line (header) and one for last line trailer (denoted by $ in the second substitution). -i option of sed   edits the file in place.
sed -i '1 s/^.*value=/yoursubstitution value=/; $ s/^.*value=/yoursubstitution value=/'
output:
yoursubstitution value=file1id
body: blah blah blah
yoursubstitution value=file1id

A: You can match from the beginning of the line (^) to value=
echo 'header: 123xxx   xxx   value=file1id' | sed 's/^.*value=/header: 321aaa   aaa   value=/'
header: 321aaa   aaa   value=file1id


Q: Can't Get CSRF Token to Appear on a Django Template/View I'm trying to use a Django ListView sub-class to generate a page with a form on it.  It's an old school manual HTML form, not a Django-generated one (though I do also have a Django-generated form elsewhere on the same page).  Since Django bakes CSRF authentication in, I need to include the CSRF token in that form in order to make it work.
However, I'm not having much luck, even after looking at several related Stack Overflow posts (and fixing things accordingly).
Basically I've got a get method on a ListView subclass, and  I've used the method decorator to decorate it with the CSRF decorator:
class FooView(ListView):
    @method_decorator(ensure_csrf_cookie)
    def get(self, request):
        # code for otherwise working view

In my template I have:
<form>
{% csrf_token %}

However, when I view the source of the page after it's been rendered, I just see:
<form>

(no CSRF token).
I'm not explicitly adding the CSRF token to the context because I'm using ListView, and as per https://docs.djangoproject.com/en/1.6/ref/contrib/csrf:

If you are using generic views or contrib apps, you are covered already

I'm sure I'm just missing something basic, but any help explaining what that might be would be greatly appreciated.

A: You need import this:
from django.template import RequestContext

and then use it like so:
def example():

    # Some code

    return render_to_response('my_example.html', {
    'Example_var':my_var
    }, context_instance=RequestContext(request))

This will force a {% csrf_token %} to appear.


Q: I'm updating the Account billing address fields (that make up THE address field on the account), but the Address field itself is coming up null Since the address is a standard field, I'm assuming this process is pretty standard in setting it, but just in case, here's a very explicit explanation of how I'm updating it.
There are no standard fields on the Account for city, street, ZIP, etc...just the Address field. The only way to update this record in the interface is to double click the field area and it pops up with text fields for the street, city, ZIP, etc.
I want, on this update (After), to do other things. After some debugging, I found that when I update it and do system.debug(acc.BillingStreet), the street that I updated it to prints out correctly -- side note: BillingStreet doesn't appear on the list of standard fields...-- however, when I try system.debug(acc.BillingAddress), which should be all the components together, it's always null.
I can't imagine why it is null since it's the very thing that I'm updating. Here's the code for the trigger, but the issue has something to do with the address field, truly.
    trigger udtInvAddress on Account (After Update) {

    List<Order2__c> invoices;
    System.debug('This should go, at the very least');

    if(Trigger.isAfter){
        if(Trigger.isUpdate){

            //go through all of the accounts that this trigger effects
            for(Account acc : trigger.new){
                System.debug('HOW ABOUT THIS...?');
                System.debug(acc.BillingStreet);
                System.debug(Trigger.oldMap.get(acc.id).BillingStreet);
                    //separate all of the components of BillingAdress field in the account
                    Address addr = acc.BillingAddress;
                System.debug('ADDR = ' + addr);
                    String AccountStreet;
                    String AccountCity;
                    String AccountState;
                    String AccountZip;
                    String AccountCountry;
                    //only update address if a new address is actually entered
                    if(addr != null){
                        System.debug('The address is not null, so assign values');
                        AccountStreet = addr.street;
                        AccountCity = addr.City;
                        AccountState = addr.state;
                        AccountZip = addr.postalcode;
                        AccountCountry = addr.country;
                    }
                    //Query to find all matching invoices
                    System.debug('IS THIS THE PROBLEM?');
                     invoices = [SELECT Billing_City__c, Billing_State__c, Billing_Street__c, Billing_zip__c, Billing_Country__c FROM Order2__c WHERE Account_Name__c =:acc.ID];
                    for(Order2__c invoice: invoices){
                        System.debug(invoice.ID);
                        //update all of the fields with the updated information only if the new information is filled in.
                        if(AccountCity <> null){
                            invoice.Billing_City__c = AccountCity;
                        }
                        if(AccountState <> null){
                            invoice.Billing_State__c = AccountState;
                        }
                        if(AccountStreet <> null){
                            invoice.Billing_Street__c = AccountStreet;
                        }
                        if(AccountZip <> null){
                            invoice.Billing_zip__c = AccountZip;
                        }
                        if(AccountCountry <> null){
                            invoice.Billing_country__c = AccountCountry;
                        }

                    }

            }

        }

        update invoices;
    }

}

A: Approach 1
Since Address in Compound field, you can simply fetch each Address attributes from Account object from the SOQL query and update invoice records like this:
trigger udtInvAddress on Account (After Update) {
List<Order2__c> invoices;
if(Trigger.isAfter && Trigger.isUpdate){
     invoices = [SELECT Id, Account__r.BillingStreet, Account__r.BillingCity,
     Billing_City__c, Billing_State__c, Billing_Street__c,
     Billing_zip__c, Billing_Country__c FROM Order2__c
     WHERE Account_Name__c =:Trigger.newMap.keySet()];
    for(Order2__c invoice: invoices)
    {
        System.debug(invoice.ID);
        //update all of the fields with the updated information only if the new information is filled in.
        if(invoice.Account__r.BillingStreet <> null){
            invoice.Billing_Street__c = invoice.Account__r.BillingStreet;
        }
        //update other fields

    }
    update invoices;
}

Moreover, your query needs to be bulkified and would be outside of for loop.
Approach 2
The use case can be simply be implemented by Process Builder. In this below picture I have shown you how Invoice Billing Street can be mapped with Account's Billing Street via Reference.

The Account Address attributes can be picked up in the PB during field mapping like this:

Since, without writing code, this functionality can be achieved, I will go by Process Builder.


Q: Users reporting WPF controls with locked values; how could this happen? I have a relatively simple program that I have created using WPF and the .NET 4.0 Client Profile. I used an MVVM approach, where I have views with minimal code-behind which bind to properties on the corresponding view-models; those properties then access the model as necessary. The GUI contains checkboxes, sliders, and other controls as necessary. The sliders are set to have a minimum value of 0, a maximum value of 1, a large change of 0.1, and a small change of 0.05. It all works fine for me and most people.
Unfortunately, several users have reported some very strange issues. They report that the sliders are locked to a value of 0 or 1, and that the values cannot be changed. Normally, the sliders have a minimum value of 0 and a maximum value of 1, so the values are potentially correct (although they most likely should actually be showing values of 0.5 or so), but they definitely should be adjustable! However, I am not setting IsSnapToTickEnabled; it is left at its default value of false. The sliders are binding to decimal properties on the view-models. I have tried asking these users for more information, but it is unfortunately difficult to get into contact with them, so I am trying to solve it on my own.
I am running Windows 7 64-bit. I have tried experimenting by changing the view-model so that a slider binds to a value lower than its minimum or higher than its maximum, and in these cases the slider handles it fine by simply showing the minimum or maximum and allowing changes. I have tried experimenting by changing the view-model so that a slider binds to a property which throws an exception, and in this case the slider handles it fine by showing the minimum value and allowing changes. This suggests to me that the binding (and therefore, view-model and model) is not the problem, and so the issue is somewhere on the view side of things. I thought that it may be a problem with the style not getting applied, but even an unstyled slider works fine and allows changes normally.
No matter what I do I cannot reproduce the issues that these people are reporting! Therefore, I have come to you for help. Can you think of any ideas of what could be causing this? I'm not doing anything unusual as far as I know. I'm just using an ordinary WPF Slider control and binding to a decimal property!
I do know that at least one user who is getting these issues is using the classic theme, and I am forcing the Aero theme in my program, if this is of any relevance.
Here is some example code, but I do not think it will be very helpful...
Slider binding:
public decimal TestBinding {
    get { return this.Model.Test; }
    set {
        if (this.Model.Test == value) return;
        this.Model.Test = value;
        this.OnPropertyChanged("TestBinding");
    }
}

Slider control:
<Slider Grid.Row="1"
        Grid.Column="1"
        Value="{Binding TestBinding}"
        Style="{StaticResource Slider0to1}" />

Slider style:
<Style TargetType="Slider" BasedOn="{Utilities:StaticApplicationResource {x:Type Slider}}">
    <Setter Property="Margin" Value="0" />
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="AutoToolTipPlacement" Value="TopLeft" />
    <Setter Property="AutoToolTipPrecision" Value="2" />
    <Setter Property="TickPlacement" Value="BottomRight" />
</Style>

<Style x:Key="Slider0to1" TargetType="Slider" BasedOn="{Utilities:StaticApplicationResource {x:Type Slider}}">
    <Setter Property="AutoToolTipPrecision" Value="2" />
    <Setter Property="Minimum" Value="0" />
    <Setter Property="Maximum" Value="1" />
    <Setter Property="TickFrequency" Value="0.1" />
    <Setter Property="SmallChange" Value="0.05" />
    <Setter Property="LargeChange" Value="0.1" />
</Style>

StaticApplicationResource markup extension:
[MarkupExtensionReturnType(typeof(object))]
public class StaticApplicationResource : MarkupExtension {

    public StaticApplicationResource(object resourceKey) {
        this.ResourceKey = resourceKey;
    }

    [ConstructorArgument("resourceKey")]
    public object ResourceKey { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider) {
        if (this.ResourceKey == null) return null;
        return Application.Current.TryFindResource(this.ResourceKey);
    }

}

A: You can do following things to gather some more information,

*

*Your report must include operating system.

*Version and screen size.

*DPI information, most users set high font size, this probably will change dpi to little bit causing controls to render little differently.

*WPF version, and also check default dependency property values. You may assume that you have set ticks to false but it may be true by default, or if your xaml is running within some other app and resources might set it to true.

*Users may only use keyboard, and check how keyboard behaves for these controls.

*Users may double click, lots of users have habit of double clicking everything (buttons, links)

*In smaller screen sizes, your controls may be out of views, this is very unlikely as you are receiving max values. Or even on big screens, changing text size may cause layout to hide your controls.

A: It's hard to know for sure if the classic theme is the issue, but I've had a LOT of issues with various themes and WPF.  For example, projecting (to an external display) with the Aero theme almost always will eventually cause some quirky behavior with WPF.  I've also had similar issues that seemed to manifest more on certain video cards than others.  And don't get me started on LiveMeeting and WPF  :-)
Definitely test classic theme, and make sure you test on XP too.


Q: Is it ok to build an 64 bit ActiveX control with C# for enterprise application use I am planning to build an 64 bit ActiveX control to be used in my web page. So my question is it OK to build it with C#? Will it be able to handle complex business logic? The reason why I ask this is that I am more familiar with C# than ATL.
Before raising this question, I searched all the related posts, they are all about how to build ActiveX with C#. However I would like to know if it will be a good choice or ATL will be more better?
By the way, the previous version of my ActiveX control is in 32 bit coded with VB6, but VB6 is impossible to build 64 bit ActiveX control.
I appreciate any of your suggestions and comments!
Regards,
Shuping

A: If you're most comfortable with C#, why not build it in Silverlight? Will be a lot easier than building and deploying ActiveX controls.

A: How about a Windows Forms app launched from Clickonce or Java web start? You cannot run a 64bit ActiveX from a 32bit IE.


Q: Using Guard Live-reload with Susy Has anyone used Guard Live-reload with Susy, here's the link to Guard: https://github.com/guard/guard.
I found where Guard is being used with Sass and Compass but so far I've not found where it's being used with Susy.
Any help will be appreciated
jrattling

A: Since Susy is simply a Sass/Compass library, there is usually no need to integrate Susy directly with other build tools. Use the Sass/Compass-guard setup, install Susy like you would without guard (see the docs), and it should all just work.