text:
Q: SSRS display label at base of column chart columns I am trying to get the labels of this column chat to appear at the columns base much like in the second image below. However that solution doesn't completely work as it skews the rest of the information.
Does anybody know the appropriate way to accomplish this, it's madding that this isn't straight forward.

A: I'm using the following data:

Take a standard Chart:

The first Chart Series is our data series, with a Chart Type of standard Column, and the second Chart Series based has a Chart Type of Line, based on a target value to get the required line in the Chart Area.
As you've probably seen, you do have some control over label placement, but not to meet your requirements. The best we can do is use the Bottom position for the label position, which isn't even close:

What can we do? First, remove the labels from the existing Series.
Next, add a new Series to the Chart:

Basically we're using a constant here, which should be the lower bound of the Y axis. I'm using 0 in this case.
This new Chart Series needs to be first in the order of all the Chart Series.
Change the Chart Type for the first two Chart Series to Stacked Column:

Add Series labels to this new Chart Series. Set the Label data expression under the Series Label Properties. The expression I've used is:
=Sum(Fields!val.Value, "CategoryGroup")
Since the two Chart Series share the same Scope, we can leverage this to get the values of the data group as above.
Here, CategoryGroup is the name of the Category Group:

The updated chart looks like:

And the result is labels at the base of each column as required:

Seems like the required result, even if it took a while to get there.
So, by using a dummy Chart Series which is at the base of the Y axis for each group, we can anchor the label at the bottom as required, and by using the label expression to display a different Chart Series value, it looks a label on the actual data group!
Edit after comment
You can definitely use expressions to set the minimum axis value and also the dummy Chart Series, it's just a case of whether you can get the exact one required.
In my example, say we change the axis value to the minimum in the Dataset:

i.e. =Min(Fields!val.Value)
Since the Dummy Chart Series would be looking at the Scope of each individual Category Group, we need a slightly different expression to get the same value:
=Min(Fields!val.Value, "DataSet1")

This changes the chart as we would expect:

You could also add a buffer to the value, something like:
=Min(Fields!val.Value) - 1

So you don't get columns with no height.
For more complex expressions, there may be issues, i.e. in 2008 you cannot get aggregates on aggregates, which might be useful, and even then it's difficult to bring this into the dummy Chart Series.
Sometimes, if possible, it's easiest to add columns to your Dataset with these values pre-generated and use these fields instead of trying to calculate it in the report.


text:
Q: How to perform type coercion with Relay? Is relay capable of knowing that a field should be a Date, for example, and converting that value from a string to a Date? Is there a place that this kind of logic can be placed?

A: Maybe, it depends on where you want the conversion to happen.
If it's a variable, Relay containers have a prepareVariables prop that takes a function. I doubt this is what you're after, though, because you can't (afaik) pass a Date object as a var. If it's something like that,
 though, here's an example adapted from the docs:
module.exports = Relay.createContainer(ProfilePicture, {
  initialVariables: {size: 5},
  prepareVariables: prevVariables => {
    return {
      ...prevVariables,
      size: typeof prevVariables.size === 'number'? * prevVariables.size : Number(prevVariables.size),
    };
  },
});

If you're hoping to coerce the output of a Relay container, you'll have to either do it in the component that's consuming the props, or in a Higher Order Component. Here's the same example using the superlative recompose (and the recompose relay-container, by the same author):
export default compose(
  createContainer({
      fragments: {
        widget: () => Relay.QL`
          fragment on Widget {
            myDate
          }`
      }
  }),
  withProps(props => ({myDate: props.widget.myDate instanceof myDate ? props.widget.myDate : new Date(props.widget.myDate)}))
)(ProfilePicture)

redpajama_set_name: RedPajamaStackExchange


text:
Q: My app does not appear in the iOS notification center - Appcelerator I'm having serious headaches with push for iOS with titanium appcelerator.
I generated several versions in testflight, but none of them appear in the iOS notification center, however, when I swipe directly into the device, it works normally on my iPad Mini.
I am currently using these settings:
Operating System
  Name                        = Mac OS X
  Version                     = 10.12

  Architecture                = 64bit
  # CPUs                      = 4
  Memory                      = 4294967296

Node.js
  Node.js Version             = 4.6.0
  npm Version                 = 2.15.9

Titanium CLI
  CLI Version                 = 5.0.9

Titanium SDK
  SDK Version                 = 5.5.1.GA
  SDK Path                    = /Users/silvio/Library/Application Support/Titanium/mobilesdk/osx/5.5.1.GA
  Target Platform             = iphone

Xcode Version: 8.2 (8C38)
My code in Alloy.js:
if (Ti.Platform.name === 'android') {
  // set android-only options
  var pnOptions = {
    senderId: 'xxxx', // It's the same as your project id
    notificationSettings: {
      sound: 'mysound.mp3', // Place soudn file in platform/android/res/raw/mysound.mp3
      smallIcon: 'appicon.png', // Place icon in platform/android/res/drawable/notification_icon.png
      largeIcon: 'appicon.png', // Same
      vibrate: true, // Whether the phone should vibrate
      insistent: true, // Whether the notification should be insistent
      group: 'Edufy', // Name of group to group similar notifications together
      localOnly: false, // Whether this notification should be bridged to other devices
      priority: 2 // Notification priority, from -2 to 2
    }
  };

} else { // set ios-only options.
  // Sets interactive notifications as well if iOS8 and above. Interactive notifications is optional.
  if (parseInt(Ti.Platform.version.split(".")[0], 10) >= 8) {
    var thumbUpAction = Ti.App.iOS.createUserNotificationAction({
      identifier: "THUMBUP_IDENTIFIER",
      title: "Aceitar",
      activationMode: Ti.App.iOS.USER_NOTIFICATION_ACTIVATION_MODE_BACKGROUND,
      destructive: false,
      authenticationRequired: false
    });

    var thumbDownAction = Ti.App.iOS.createUserNotificationAction({
      identifier: "THUMBDOWN_IDENTIFIER",
      title: "Regeitar",
      activationMode: Ti.App.iOS.USER_NOTIFICATION_ACTIVATION_MODE_BACKGROUND,
      destructive: false,
      authenticationRequired: false
    });

    var thumbUpDownCategory = Ti.App.iOS.createUserNotificationCategory({
      identifier: "THUMBUPDOWN_CATEGORY",
      // The following actions will be displayed for an alert dialog
      actionsForDefaultContext: [thumbUpAction, thumbDownAction],
      // The following actions will be displayed for all other notifications
      actionsForMinimalContext: [thumbUpAction, thumbDownAction]
    });

    var pnOptions = {
      types: [Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT, Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND],
      categories: [thumbUpDownCategory]
    };
  } else { //No support for interactive notifications, omit categories
    var pnOptions = {
      types: [Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT, Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND]
    };
  }
}

// set cross-platform event
var onReceive = function(event) {};

// Create instance with base url
var tiPush = require('ti-push-notification').init({
  backendUrl: "http://xxxx.com.br/painel/ws/push_test.php"
});

// register this device
tiPush.registerDevice({
  pnOptions: pnOptions,
  onReceive: onReceive,
  extraOptions: {
    action: 'register',
    user_id: 123
  }
});

My certificates in the apple store are all valid, as in the prints below:
Push Notifications Enabled:

Certificates:

Prov Profiles:

Also, I tried adding the Entitlements.plist in these locations:

*

*Project / Entitlements.plist

*Project / app / Entitlements.plist

*Project / app / platform / ios / Entitlements.plist

*Project / app / platform / ios /  .plist

I also added the lines from within the  tag to tiapp.xml, but it did not work ... below the Entitlements.plist code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>aps-environment</key>
    <string>development</string> <!-- Either development or production -->
    <key>application-identifier</key>
    <string>xxxx.com.colegiokennedy</string>
    <key>keychain-access-groups</key>
    <array>
      <string>xxx.com.colegiokennedy</string>
    </array>
</dict>
</plist>

I've also tried changing the development environment to production, but it did not work too.

A: You can try including Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE.
Make sure that in your iOS device, go to Settings -> Notifications -> Your_App -> Show in Notification Centre is selected. You can check that what kind of settings are on/off for your app's notifications.


text:
Q: How to inject and use Serilog (Ilogger) when web-api startup I'm developing a .NET core 3.1 Console application (web-api).
I use a Serilog service (it is basically using the Microsoft.Extensions.Logging).
The Serilog is injected and can be used in the FW Controllers methods.
Now - I need something a little bit different - Whenever the system is starting up (after being down) I need to make an http post request - you can see it when executing the ConnectionInitiator.Initiate(), in the startup method. In that same scope (method\class) - I need to use the logger, in order to log some data. Now - If the request would be through the controller - the logger, would be available (by the DI).
To make a long story short - I need somehow to inject the Ilogger to the class or to make it available in some other way. I've tried use the logger in the startUp, but this seems to be impossible (since .net core 3.0 - if I understand correctly)
See my code:
Program.cs:
public class Program
    {
        public static void Main(string[] args)
        {
            var loggerConfig = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            //Reading the appconfig.json
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(loggerConfig).CreateLogger();
            try
            {
                Log.Information("System Started up");
                CreateWebHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "THE APPLICATION FAILED TO START UP");
            }
            finally
            {
                Log.CloseAndFlush();
            }

        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args).ConfigureLogging((context, logging) =>
            {
                logging.ClearProviders();
            }).UseSerilog().UseStartup<Startup>();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

StartUp.cs
public class Startup
{
    public Startup(IConfiguration configuration/*, Microsoft.Extensions.Logging.ILogger logger*/)
    {
        Configuration = configuration;
        ConnectionInitiator.Initiate(configuration/*, logger*/);
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddControllers();
        services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed((host) => true).AllowCredentials());
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();
        app.UseAuthentication();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

ConnectionInitiator.cs:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

using System.Threading.Tasks;

namespace AAA.BL
{
    public static class ConnectionInitiator
    {

        private static readonly object threadlock = new object();
        private static MyConfig myConfig;
        private static ILogger ilogger;
        /*
        public ConnectionInitiator(ILogger _logger)
        {
            ilogger = _logger;
        }
        */
        public static void/*async Task*/ Initiate(IConfiguration configuration/*, ILogger ilogger*/)
        {
            HttpRequester httpRequester = new HttpRequester();
            if (myConfig == null)
            {
                myConfig = new myConfig(configuration);
            }

            IssueOTPResponse response = /*await*/ httpRequester.PostSomething(myConfig, ilogger).Result;            //Double check thread safe singleton implementation
            if (response.ststuacode != 200)
            {
                ilogger.logcritical($"critical error when initiate connection (connectioninitiator): {response.statusdescription}");
            }

        }
    }
}

A: It seems like the answer is much simpler that I expected - By using the Serilog and was added as a service in the Configure method - It can be reached globally (in every place of the namepsace) by using the static class Log and its static method Logger, for example:
Log.Logger.Information("XXXXX");


text:
Q: The sum of contraction with identity map has a continuous inverse In $(\mathbb R, d(x,y)=|x-y|)$, suppose $f:\mathbb R \to \mathbb R$ is a contraction, that is for all $x,y \in \mathbb R$, there exists a constant $A$ between 0 and 1 such that $|f(x)-f(y)| \leq A|x-y|$.
Then let $G(x)=x+f(x)$. I have already proved that $G:\mathbb R \to \mathbb R$ is a bijection and $G$ is continuous, how to show that the inverse of $G$ is also continuous?
I have tried to find connection between $| G^{-1}(x)-G^{-1}(y) |$ and $|x-y|$ but failed, any hint?

A: $g$ is monotone, indeed $\forall x,y \in \mathbb R, x>y$ consider
$|f(x)-f(y)|<A(x-y)<(x-y)$ $\implies -(x-y)<f(x)-f(y)<(x-y)\implies g(x)-g(y)>0$ by using left part of the inequality. Now you have a continuous bijective monotone function from $\mathbb R \to \mathbb R$ what can you say about $g^{-1}$?


text:
Q: Is possible to store & load UITableViewCells & stand-alone nibs from storyboard? I have some nibs that are UITableViews & also custom controls. This controls have actions that will launch storyboard sieges.
So, I have 3 normal UIViewControllers that are connected by the storyboard, then some subViews that are composited on top of some of them and from this subviews I like to connect the other UIViewControllers.
Is this possible? Everything in the same storyboard? Currently I store in standalone nibs the controls & cells but need manually present the other controllers in the storyboard.


text:
Q: Page doesn't detect changes? Good day, everyone. Please I've got a page that binds to a variable for content. But I'm noticing the page does not update when the variable changes. unless I navigate to another page and back before the changes reflect. Please I need your help. Thanks
my edit page
// am using ionic modal popup
// this page update user data
 async updateUserData(){

    let loading = await this.loadingCtrl.create({
      message: 'Updating...'
     });

     loading.present();
    this.isUserLoggedIn = localStorage.getItem('currentUserId');

    let customerDataUpdated = {
      "first_name": `${this.user.first_name}`,
      "last_name": `${this.user.last_name}`,
      "email": `${this.user.email}`,
      "username": `${this.user.username}`,
      "billing": {

        "address_1": `${this.user.billing.address_1}`,
       "phone": `${this.user.billing.phone}`
      },
    }

   console.log('new update', this.user);

   //update user data

   this.WC.updateCustomerData(this.isUserLoggedIn, customerDataUpdated).then((data)=>{

    this.changedetector.detectChanges();
    loading.dismiss();

          setTimeout(()=>{
          this.modalCtrl.dismiss({
            'dismissed': true
          });
      }, 3000);

     });

profile page
// update on edit page does not reflect here unless I navigate to another tab and back

      constructor(private changedetector: ChangeDetectorRef, private WC: WoocommerceService,) {

    // this retrieve user data from api call
         ngOnInit() {

   this.isUserLoggedIn = localStorage.getItem('currentUserId');
    this.WC.getUserInfo(this.isUserLoggedIn).subscribe((data)=>{
      this.customerData = data;
    });

    this.WC.profileSubjects.subscribe((data) => {
 //    this.customerData = data;
     console.log('change update ', data);
  });

woocommerce.service.ts
    //getting authenticated users details from woocommerce

    getUserInfo(id){
      this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
      console.log('API url for retrive customer: ', this.apiUrl);
      this.customerData = this.http.get(this.apiUrl).pipe( retry(1),catchError(this.handleError) );
      return this.customerData;
    }

    // this update user data
        updateCustomerData(id, customerDataUpdated){
          let headers = new HttpHeaders ({
            "Content-Type" : "application/json"
          });
          this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
         // console.log('API url for retrive customer data: ', this.apiUrl);
          return new Promise((resolve, reject) => {
            this.http.put(this.apiUrl, customerDataUpdated, {headers} ).subscribe(
              response => {
                resolve(response);
                console.log('Customer Data Updated: ', response);
            },
            error => {
              resolve(error);
             console.log('Customer Data Updated failed ', error);
            }
            )
          });
        }

updateCustomerData(id, customerDataUpdated){
  let headers = new HttpHeaders ({
    "Content-Type" : "application/json"
  });
  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
 // console.log('API url for retrive customer data: ', this.apiUrl);

  return new Promise((resolve, reject) => {
    this.http.put(this.apiUrl, customerDataUpdated, {headers} ).subscribe(
      response => {
        resolve(response);

        console.log('Customer Data Updated: ', response);
    },
    error => {
      resolve(error);
     console.log('Customer Data Updated failed ', error);
    }
    )
  });

A: Your method in the constructor of the page is only firing once when the class is first constructed i.e. page load, which is why you need to do a reload to make it fire again.
What you need to do is use a Subject and store data in it in the service and then subscribe to it in the profile page.
WooCommerceService code:
import { Subject } from 'rxjs';

let profileSubject = new Subject<any>();

getUserInfo(id){
  this.apiUrl = `${this.siteUrl}${this.woocommercePath}customers/${id}?
    consumer_key=${this.consumerKey}&consumer_secret=${this.consumerSecret}`;
    console.log('API url for retrive customer: ', this.apiUrl);
    this.customerData = this.http.get(this.apiUrl);

    // STORE WHATEVER DATA YOU WANT IN THE SUBJECT
    this.profileSubject.next(this.customerData)
 .pipe(retry(1),catchError(this.handleError) );
   return this.customerData;
}

Profile page:

ngOnInit() {
     this.wc.profileSubject.subscribe(data => {
        // do something with the data
     }
}

Now, using the Subject method, anything that subscribes to the profileSubject will get updated data as it becomes available i.e. you call getUserInfo from anywhere in the app and the new data is pushed to anything that has subscribed.
There is also the BehaviorSubject which acts almost exactly the same but always has the last piece of data available, so a new subscriber always receives something at the time it subscribes instead of having to wait. It may be useful.
Also, keep the constructor lean, most code that you want to fire at page load should go in the ngOnInit to make sure that everything is available by the time the code tries to access it. This isn't guaranteed in the constructor.
Hope that helps.


text:
Q: MySql Try to create a table from columns from two other tables I am trying to created a table from a few columns from two other tables. I want this table to get data from the other two tables.
This is what I have so far
insert into crm_customer_coupon (barcode, customer_id,customer_name, coupon_name, number_of_times_used, product_sku)
select barcode, name, sku
From crm_coupons
Inner left Join crm_customer_extra_information where customer_id = 88

This is one of the tables rm_coupons set up
id: Barcode: Name : Description: Type : Amount : sku

This is the table rm_customer_extra_information
id : name: customer_id : ect...

and this is the table I want to put them into
 barcode: customer_id : customer_name: coupon_name: product_sku

How do I go about combining them together, also how are they linked so I can get information from the other tables via a endpoint in spring later on.
Thank you for any help with this

A: Try this:
insert into crm_customer_coupon (barcode,name,sku)
select crm_coupons.barcode, crm_customer_extra_information.coupon_name, crm_coupons.sku
from crm_coupons
left Join crm_customer_extra_information on crm_coupons.id=crm_customer_extra_information.id
where customer_id = 88

You forgot to mention you join field (i guess it's id),
also you didn't mention which name field you want to insert, i put coupon_name, you can change the filed name in the subquery select.

A: It's easy:
   CREATE TABLE new_table
      SELECT barcode, name,sku
      FROM crm_coupons
      // your code here


text:
Q: Get the key when the value is an array function getObjKey(obj, value) {
  return Object.keys(obj).find(key => obj[key] === value);
}

const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};

console.log(getObjKey(obj, ['Santiago','Germany']));

I want to get the key of ['Santiago','Germany'] this array value as city1
console.log(getObjKey(obj, 'Chicago'));

When I try the above code, I am getting the key of 'Chicago' as city2.
Same way I want to get the key of ['Santiago','Germany'] as well. How can I do that?
Any suggestions?
Thanks for the response.
Now my Object looks like
const obj = {city1: ['Santiago','Germany'], city2: 'Chicago', level1:
{level2 : [{level3:chennai},{level4:madurai}]};

when I pass
[{level3:chennai},{level4:madurai}]

as an argument, I need to get its key level2 . I wasn't able to find that. Any suggestions for this.

A: Idea:
You need to check whether obj[key] is an Array or not if Array then use every to check it matches with all values and if it's not just check obj[key]===value
Checking two arrays equal or not by every() leads to a common bug like ['A', 'B'] !same ['A', 'B', 'C'] but if we use every() for ['A', 'B'] it returns true although these two arrays are not the same. so we need to check the lengths beforehand.

const getObjKey = (obj, value) => {

  return Object.keys(obj).find(key => {
    const currVal = obj[key];

    return Array.isArray(currVal) && Array.isArray(value) && currVal.length === value.length ? value.every(val => currVal.includes(val)) : currVal === value
  });
}

const obj = {
  city1: ['Santiago', 'Germany'],
  city2: 'Chicago',
  city3: 'Berlin'
};

console.log(getObjKey(obj, ['Santiago', 'Germany']));
console.log(getObjKey(obj, 'Chicago'));
console.log(getObjKey(obj, ['Santiago', 'Germany', 'Erlangen']));
console.log(getObjKey(obj, ['Berlin']));

A: You can use Object.entries(), check if the value is an array or not and Check if the value exists like so:

function getObjKey(obj, value) {
  return Object.entries(obj).find(([k, v]) => {
    if(Array.isArray(value)) {
       return value.every(item => v.includes(item));
    }

    return v === value;
  })?.[0];
}

const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};

console.log(getObjKey(obj, ['Santiago','Germany']));
console.log(getObjKey(obj, 'Chicago'));

A: You can check to see it value is an array and if it is, use Array#every to check if value is found as follows:

function getObjKey(obj, value) {
  return Object.keys(obj).find(
      key => Array.isArray(value) ?
      value.every((val,i) => val === obj[key][i] || '') &&
      obj[key].every((val,i) => val === value[i] || '') :
      obj[key] === value
  ) || '';
}

const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};

console.log(getObjKey(obj, ['Santiago','Germany']));
console.log(getObjKey(obj, 'Chicago'));
console.log(getObjKey(obj,['Santiago','Germany', 'Chicago','Santiago']));

A: Basically, You are trying to compare the same array by using comparison operator (===). They looks identical but they are two distinct people :)
For the Arrays or Objects, It isn't pointing to the SAME object, but different objects with the same values.
So by comparing, we are comparing the references but not the values. That's the reason it will always return false.

console.log(['Santiago','Germany'] === ['Santiago','Germany']); // false

To compare the values, We have to do something like this :

function getObjKey(obj, value) {
  return Object.keys(obj).find(key => {
    if (typeof obj[key] === 'object' && obj[key].length === value.length) {
      return obj[key].every(item => value.includes(item))
    }
  });
}

const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};

console.log(getObjKey(obj, ['Santiago','Germany']));

A: You can't compare arrays with === , a temporary solution can be parse the values as strings and then check if they are equal:
function getObjKey(obj, value) {
  return Object.keys(obj).find(key => JSON.stringify(obj[key]) === JSON.stringify(value));
}

But as I said, this should be a temporary solution since it would be slow for larger objects and JSON.stringify do unnecessary work.

A second option can be having different procedures for different data strucutes, is adequate if the order in the array matters and you aren't dealing with objects inside the lists:
function getObjKey(obj, value) {
  return Object.keys(obj).find(key =>  {
      if (Array.isArray(obj[key])) {
          return obj[key].every((element, index) => element === value[index]);
      }

      return obj[key] === value;
  });
}

A: Here is my version probably with the least change:

function getObjKey(obj, value) {
  const valueToCompare = (rawValue) => (rawValue && rawValue.constructor === Array) ? rawValue.join('-') : rawValue;

  return Object.keys(obj).find(key => valueToCompare(obj[key]) === valueToCompare(value));
}

const obj = {city1: ['Santiago','Germany'], city2: 'Chicago'};

console.log(getObjKey(obj, ['Santiago','Germany']));

console.log(getObjKey(obj, 'Chicago'));

This conversion might be a hint to structure the data being processed before doing analysis on it and separate the code for each part for easier understanding


text:
Q: Get percentage value out of bracket at end of line I got a string like
Just a text (12%)

Now I want to get the percentage value and remove the bracket. So far I got this regEx:
$result = array();
$content = preg_replace_callback('~\(([^)]*)\)~', function ($m) use (&$result) {
    $percentage = $m[1]/100;
    return '';
}, $content);
echo trim($content)."|".$percentage;

This should give me the output Just a text|0.12. The current regEx doesn't drop the %-character.
Update
And I need to check if the percentage-value is a correct integer - as sometimes there are
text (10-15%)

In this case, nothing should happen at all. The string keeps as it is.

A: Put % in your regex:
$result = array();
$content = preg_replace_callback('~\((\d+)%\)~', function ($m) use (&$result) {
//                                 here __^
    $percentage = $m[1]/100;
    return "|".$percentage;
}, $content);
echo trim($content);

A: You need to pass the $percentage var as a reference to a closure so that you can use it later.
$content = preg_replace_callback('~\(([^)]*)\)~', function ($m) use (&$result, &$percentage) {
    $percentage = $m[1]/100;
    return '';
}, $content );


text:
Q: How do I find folders without a certain name? I'm trying to find a lot of folders, all without a certain bracket.
They're movie folders, like so:
Zombie Flesh Eaters (1979) [tmdb-7219]
Zombieland (2009) [tmdb-19908]
Zombieland Double Tap (2019) [tmdb-338967]

But I need to find the ones WITHOUT the [tmdb] bracket.
I'm not sure how to do this?
Quick edit:
Tried using the reg-ex \[.*?\] to find everything with a bracket in it, but I'm not sure if that works properly (I'm not that good at regex, but using a reg-ex tester confirms it looks for anything inside brackets).
But I need to find the folders WITHOUT the brackets.. And I don't know how to do this

A: find features the -not operator. Tell it where to search, what kind of item to find (e.g. -type d to find only folders) and what should not be in the name, i.e -not -name '*\[*\]'. Thus
find /somewhere -type d -not -name '*\[*\]'

A: This could be done easily.
ls -Aq1 | grep -Pv '.*\[tmdb-\d+\].*'

Piping after ls is considered a bad thing in general however, I assume all the folders aren't weirdly named because they're just movie folders, so I think piping after ls is fine here.
I haven't tested it but I'm pretty confident that it should work.
Also, I'm guessing that you'll be putting those folders in a loop to add the id to the name. Pure guess but I assume. Then this is handy because the ls output (because of the -..1) will be in a list. So you can easily do this to process the folders one by one:
ls -Aq1 | grep -Pv '.*\[tmdb-\d+\].*' | \
while read -r level
do
   ...
done

or
ls -Aq1 | \
while read -r level
do
   if ! echo "$level" | grep -Pq '.*\[tmdb-\d+\].*'
   then
      ...
   fi
done

A: If you don't need to search recursively, then the bash shell's extglob can do negation using !(pattern) ex.
shopt -s extglob

printf '%s\n' !(*\[tmdb-*\]*)/

The extglob option is probably enabled by default in your interactive bash shell. The trailing / is only necessary if you need to exclude plain files from the match - equivalent to the find command's type -d.
Ex. given a directory with contents
$ ls
'Zombie Flesh Eaters (1979) [something else here]'  'Zombieland (2009) [tmdb-19908]'
'Zombie Flesh Eaters (1979) [tmdb-7219]'            'Zombieland Double Tap (2019) [tmdb-338967]'
'Zombieland (2009)'

then
$ printf '%s\n' !(*\[tmdb-*\]*)/
Zombie Flesh Eaters (1979) [something else here]/
Zombieland (2009)/

or
$ ls -d !(*\[tmdb-*\]*)/
'Zombie Flesh Eaters (1979) [something else here]/'  'Zombieland (2009)/'

Unlike find, this won't match hidden directories by default (although you can include them by setting shopt -s dotglob).
If you do need to search recursively, you can add shopt -s globstar and use **/!(*\[tmdb-*\]*)/ although I'd likely choose find in this case.


text:
Q: How can I fix my CSS code to work with IE (where it shows scroll bars)? I have the following CSS code, works fine with Firefox, Chrome but breaks like hell when I run it in IE7!
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"

"http://www.w3.org/TR/html4/strict.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <title>Box Test</title>

    box 1

box1 label

box 2

box 3

Why do i get scroll bars on the first box in IE7 and NOT in any other browser?

A: I suspect overflow:auto in .mybox but I can't test it because I do not have access to IE7 at the moment.

A: Either increase the width of .mybox to 60px or set overflow:hidden. This is because IE7 show the scrollbars with a different calculation of width, it is highly annoying...

A: .small has a width of 45px and left and right padding of 10px. .boxfont has a left-margin of 15px.
45px-10px-10px-15px leaves you with only 10px of space for your text.  The other browsers are showing the text, IE is putting in the scrollbars.
Put overflow:hidden on .boxfont to see where it is cut off in Firefox.
To fix this, you can put overflow:visible on .small to have IE show the text but that will make your box a little bigger. Or you can just increase the width of your box a bit.

A: The problem you are experieinceing is due to the IE Box Model issue.
You can fix the display issue in your code by replacing the .boxfont definition as below.
.boxfont{font-weight:bold; font-size:16px; margin-left:10px;}

A: If you can remove the overflow:auto property it can work. But better you setup IE7 cross css style to fix the scroll bar issue.


text:
Q: How to create a torchtext.data.TabularDataset directly from a list or dict torchtext.data.TabularDataset can be created from a TSV/JSON/CSV file and then it can be used for building the vocabulary from Glove, FastText or any other embeddings. But my requirement is to create a torchtext.data.TabularDataset directly, either from a list or a dict.
Current implementation of the code by reading TSV files
self.RAW = data.RawField()
self.TEXT = data.Field(batch_first=True)
self.LABEL = data.Field(sequential=False, unk_token=None)

self.train, self.dev, self.test = data.TabularDataset.splits(
    path='.data/quora',
    train='train.tsv',
    validation='dev.tsv',
    test='test.tsv',
    format='tsv',
    fields=[('label', self.LABEL),
            ('q1', self.TEXT),
            ('q2', self.TEXT),
            ('id', self.RAW)])

self.TEXT.build_vocab(self.train, self.dev, self.test, vectors=GloVe(name='840B', dim=300))
self.LABEL.build_vocab(self.train)

sort_key = lambda x: data.interleave_keys(len(x.q1), len(x.q2))

self.train_iter, self.dev_iter, self.test_iter = \
    data.BucketIterator.splits((self.train, self.dev, self.test),
                               batch_sizes=[args.batch_size] * 3,
                               device=args.gpu,
                               sort_key=sort_key)

This is the current working code for reading data from a file. So in order to create the dataset directly from a List/Dict I tried inbuilt functions like Examples.fromDict or Examples.fromList but then while coming to the last for loop, it throws an error that AttributeError: 'BucketIterator' object has no attribute 'q1'

A: It required me to write an own class inheriting the Dataset class and with few modifications in torchtext.data.TabularDataset class.
class TabularDataset_From_List(data.Dataset):

    def __init__(self, input_list, format, fields, skip_header=False, **kwargs):
        make_example = {
            'json': Example.fromJSON, 'dict': Example.fromdict,
            'tsv': Example.fromTSV, 'csv': Example.fromCSV}[format.lower()]

        examples = [make_example(item, fields) for item in input_list]

        if make_example in (Example.fromdict, Example.fromJSON):
            fields, field_dict = [], fields
            for field in field_dict.values():
                if isinstance(field, list):
                    fields.extend(field)
                else:
                    fields.append(field)

        super(TabularDataset_From_List, self).__init__(examples, fields, **kwargs)

    @classmethod
    def splits(cls, path=None, root='.data', train=None, validation=None,
               test=None, **kwargs):
        if path is None:
            path = cls.download(root)
        train_data = None if train is None else cls(
            train, **kwargs)
        val_data = None if validation is None else cls(
            validation, **kwargs)
        test_data = None if test is None else cls(
            test, **kwargs)
        return tuple(d for d in (train_data, val_data, test_data)
                     if d is not None)


text:
Q: Difference in output on Azure I've run into a little problem here. What I get on my local environment and my cloud result is different... I've tried using IntelliTrace, but everytime I want to debug a track it gives me a No source available message.
There aren't any exceptions or anything like that, everything loads perfectly fine... it just seems like the 4th case of the switch-case is screwed. I'm using 4 const ints in a static Common.cs file to populate these 4 possibilities; I know I could be using an enum, but it shouldn't really matter, right?
If this helps, I am also using Telerik's RadChart control. In other words, these 4 options manipulate the data in 4 different ways. People have told me that there is no way to debug code hosted within Azure, and that I could probably use Azure Diagnostics and keep tracing every few lines or so...
Does anyone have any pointers on which direction I should go? or have faced similar problems before? Many thanks... I am pretty much clueless in here.
EDIT: The problem lay with the localization on Azure. On my local machine the date format is dd/mm/yyyy, whereas on Azure it is mm/dd/yyyy. Hence, the problem arose...

A: It seems to me you're using a web role. If that's the case, the quickest way to explore differences between local deployment and azure deployment is to enable Web Deploy on your cloud project.
Once you've done that, use the Publish option on the Web project (NOT on the cloud project) to quickly upload your code changes to Azure, and explore doing old-fashioned Response.Write.
Ugly, but quite efficient when you don't get what's happening.
Pierre


text:
Q: IoT speed sensor Do you know any IoT sensor for speed detection of a human and sending it to a mobile application?
In other words, I am looking for a very small IoT sensor that sends the speed data of players of a sports team to a mobile application.

A: I am not sure if your budget allows it, but I know Garmin has a few APIs for collecting data from their fitness trackers, like speed. They call it Flexible and Interoperable Data Transfer Protocol or "FIT". The only downside is that the data must be collected from their Garmin Connect site, not direct from device. It also has a pretty hefty one time fee to access the data for your application. But depending on your budget and audience, perhaps it is worth looking in to! Hope this helps.
You can check out the SDK for FIT here to see if it is worth your time:
https://www.thisisant.com/resources/fit
More Info:
https://developer.garmin.com/garmin-connect-api/sample-data/


text:
Q: Why does my bitmap image appears behind the alertdialog? Code:
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    image_person = (ImageView) findViewById(R.id.dialog_imageview);
}

public void checkBox_checker(String checkerID, String checkerName, String checkerSurname, String
checkerDescription, Blob picture) throws SQLException
{
    int blobLength = (int) picture.length();
    byte[] bytes = picture.getBytes(1,blobLength);

    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

    Log.d(TAG, "Checker box");

    LayoutInflater factory = LayoutInflater.from(MainActivity.this);

    final View alertDialog= factory.inflate(R.layout.sample, null);
    image_person.setImageBitmap(bitmap);

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    builder.setCancelable(true);
    builder.setView(alertDialog);
    builder.setTitle("Information");
    builder.setMessage(message);

    builder.setNegativeButton("Report", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });

    builder.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
    builder.show();
}

Sample.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">

<ImageView
    android:id="@+id/dialog_imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

</RelativeLayout>

My problem is that the image is inserted behind the alert dialog and not inside the alert dialog. Can someone help me as to why this is happening?
I have entered the image in the xml file and it does get displayed in the alert dialog. So not too sure why this is happening.

A: It looks like you have a separate ImageView called dialog_imageview inside the layout activity_main. Otherwise, the activity wouldn't be able to find a View here:
image_person = (ImageView) findViewById(R.id.dialog_imageview);

which then would cause a Null Pointer Exception a few lines below:
image_person.setImageBitmap(bitmap);

To fix all of this, delete the dialog_imageview from activity_main XML layout.
Then, find the correct ImageView in your inflated sample layout rather than in the activity by calling findViewById on it:
final View alertDialog = factory.inflate(R.layout.sample, null);
image_person = (ImageView) alertDialog.findViewById(R.id.dialog_imageview);
image_person.setImageBitmap(bitmap);

A: You cannot do a "findViewById()" before have Inflated its Layout...
I think you have a "dialog_imageview" in your MainActivity's Layout and then the Image is updated in the wrong ImageView.
You just have to move "image_person = (ImageView)alertDialog.findViewById(R.id.dialog_imageview);" after the "factory.inflate(R.layout.sample, null);" row.

A: Firstly as Hoffman pointed out correctly, I did duplicate the ImageView in the activty_man.xml.
However, the problem still persisted.
After much investigations, I realized I missed a single line of code,
Before:
image_person = (ImageView) findViewById(R.id.dialog_imageview);

After/Correction:
image_person = (ImageView) alertDialog.findViewById(R.id.dialog_imageview);


text:
Q: Angular - run block vs bootstrap I want to upgrade an angular 1.5 application to angular 2. Starting to sequentially migrate the code, I am trying to set it up as a hybrid, as described in the official docs.
However, I started learning angular with 2.0 beta, so I am not quite familiar with the angular 1.x world.
What does the app.run() block do in comparison to angular.bootstrap()?
From the docs:
Run blocks

get executed after the injector is created and are used to kickstart the application.

angular.bootstrap

Use this function to manually start up angular application.

Someone can explain the difference?
The current app uses app.run(require('run.js')) and the ng-app="myApp" directive so I can simply use upgradeAdapter.bootstrap(document.body, ['myApp']) instead?

A: The run block is an optional function which is equivalent to:

*

*dojo/domReady! in Dojo

*$.ready in jQuery

*connectedCallback in Web Components

*componentWillMount in react.js

*oncreate in mithril.js

*onReady in Ext.js

*ko.components.register in knockout.js

whereas bootstrap is a required binding between the DOM and the framework(but is implicitly bound via the ng-app declaration by default) which is equivalent to:

*

*<xsl:stylesheet> in XSLT

*<svg> in SVG

*<canvas> in HTML5 Canvas

*<object> in Flash

*new Vue in vue.js

References

*

*Custom Elements - Web Components | MDN

*dojo/domReady! - The Dojo Toolkit - Reference Guide

*XSL Transformations (XSLT) Version 3.0

*jQuery.ready | jQuery API Documentation

*Document Structure - SVG 1.1 (Second Edition)

*The Vue Instance - Vue.js 2.0

*The Vue Instance - vue.js 1.0

*Lifecycle Methods: oncreate - mithril.js

*onReady: Ext JS 6.2.0

*Apply tag attributes in Adobe Flash Professional

*Comparing Web Components and React, part one: Custom Elements and React lifecycle hooks #usetheplatform / blog unblock

*Tutorial: Create reusable and future-proof UI components with Custom Elements v1 and Web Components

*Custom Elements That Work Anywhere

*Introducing Custom Elements | WebKit

*Building Custom Elements That Work With AngularJS 1.x and Angular

*Integrating MDC-Web into Frameworks - Material Components for the Web

*Knockout : Component loaders


text:
Q: How to choose male voice in Google text to Speech API I want male voice output from google text to speech API, is there any parameter to send for male voice, Now i'm getting female voice(default). i'm Using below URL.
http://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&textlen=32&client=tw-ob&q=Hello+world&tl=en
Please help me to solve this.
Thanks & Regards
Thiru.

A: According to the official REST API documentation,
There is no way to configure the voice. Neither pitch, speed nor gender. However you can get the translated text and output it using Google's Text-to-speech. For this you need to manually download the male voice file. See Google Text-to-speech adds multiple male and female voices

A: you have to set pitch of voice you can not set male voice...
 TTS.setPitch();

value u can set but it is very bad u should try another texttospeech engine or stay with default female voice.


text:
Q: How to perform bulk field rename in CosmosDB Javascript Stored Procedure I've been following along the javascript stored proc examples shown here
The code below is an attempt at writing a modified version of the update stored proc sample.  Here's what I'm trying to do:

*

*Instead of operating on a single document, I'd like to perform the
update on the set of documents returned by a provided query.

*(Optional) Return a count of updated documents in the response body.

Here's the code:
function updateSproc(query, update) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var response = getContext().getResponse();
    var responseBody = {
        updated: 0,
        continuation: false
    };

    // Validate input.
    if (!query) throw new Error("The query is undefined or null.");
    if (!update) throw new Error("The update is undefined or null.");

    tryQueryAndUpdate();

    // Recursively queries for a document by id w/ support for continuation tokens.
    // Calls tryUpdate(document) as soon as the query returns a document.
    function tryQueryAndUpdate(continuation) {
        var requestOptions = {continuation: continuation};

        var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
            if (err) throw err;

            if (documents.length > 0) {
                tryUpdate(documents);
            }
            else if (responseOptions.continuation) {
                // Else if the query came back empty, but with a continuation token; repeat the query w/ the token.
                tryQueryAndUpdate(responseOptions.continuation);
            }
            else {
                // Else if there are no more documents and no continuation token - we are finished updating documents.
                responseBody.continuation = false;
                response.setBody(responseBody);
            }
        });

        // If we hit execution bounds - return continuation:true
        if (!isAccepted) {
            response.setBody(responseBody);
        }
    }

    // Updates the supplied document according to the update object passed in to the sproc.
    function tryUpdate(documents) {
        if (documents.length > 0) {
            var requestOptions = {etag: documents[0]._etag};

            // Rename!
            rename(documents[0], update);

            // Update the document.
            var isAccepted = collection.replaceDocument(
                documents[0]._self,
                documents[0],
                requestOptions,
                function (err, updatedDocument, responseOptions) {
                    if (err) throw err;

                    responseBody.updated++;
                    documents.shift();
                    // Try updating the next document in the array.
                    tryUpdate(documents);
                }
            );

            if (!isAccepted) {
                response.setBody(responseBody);
            }
        }
        else {
            tryQueryAndUpdate();
        }
    }

    // The $rename operator renames a field.
    function rename(document, update) {
        var fields, i, existingFieldName, newFieldName;

        if (update.$rename) {
            fields = Object.keys(update.$rename);
            for (i = 0; i < fields.length; i++) {
                existingFieldName = fields[i];
                newFieldName = update.$rename[fields[i]];

                if (existingFieldName == newFieldName) {
                    throw new Error("Bad $rename parameter: The new field name must differ from the existing field name.")
                } else if (document[existingFieldName]) {
                    // If the field exists, set/overwrite the new field name and unset the existing field name.
                    document[newFieldName] = document[existingFieldName];
                    delete document[existingFieldName];
                } else {
                    // Otherwise this is a noop.
                }
            }
        }
    }
}

I'm running this sproc via the azure web portal, and these are my input parameters:

*

*SELECT * FROM root r

*{$rename: {A: "B"}}

My documents look something like this:
{ id: someId, A: "ChangeThisField" }

After the field rename, I would like them to look like this:
{ id: someId, B: "ChangeThisField" }

I'm trying to debug two issues with this code:

*

*The updated count is wildly inaccurate.  I suspect I'm doing something really stupid with the continuation token - part of the problem is that I'm not really sure about what to do with it.

*The rename itself is not occurring.  console.log() debugging shows that I'm never getting into the if (update.$rename) block in the rename function.

A: I modified your stored procedure code as below and it works for me.I didn't use object or array as my $rename parameter, I used oldKey and newKey instead. If you do concern the construct of parameters, you could change the rename method back which does not affect other logic. Please refer to my code:
function updateSproc(query, oldKey, newKey) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var response = getContext().getResponse();
    var responseBody = {
        updated: 0,
        continuation: ""
    };

    // Validate input.
    if (!query) throw new Error("The query is undefined or null.");
    if (!oldKey) throw new Error("The oldKey is undefined or null.");
    if (!newKey) throw new Error("The newKey is undefined or null.");

    tryQueryAndUpdate();

    function tryQueryAndUpdate(continuation) {
        var requestOptions = {
            continuation: continuation,
            pageSize: 1
        };

        var isAccepted = collection.queryDocuments(collectionLink, query, requestOptions, function (err, documents, responseOptions) {
            if (err) throw err;

            if (documents.length > 0) {
                tryUpdate(documents);
                if(responseOptions.continuation){
                    tryQueryAndUpdate(responseOptions.continuation);
                }else{
                    response.setBody(responseBody);
                }

            }
        });

        if (!isAccepted) {
            response.setBody(responseBody);
        }
    }

    function tryUpdate(documents) {
        if (documents.length > 0) {
            var requestOptions = {etag: documents[0]._etag};
            // Rename!
            rename(documents[0]);

            // Update the document.
            var isAccepted = collection.replaceDocument(
                documents[0]._self,
                documents[0],
                requestOptions,
                function (err, updatedDocument, responseOptions) {
                    if (err) throw err;

                    responseBody.updated++;
                    documents.shift();
                    // Try updating the next document in the array.
                    tryUpdate(documents);
                }
            );

            if (!isAccepted) {
                response.setBody(responseBody);
            }
        }
    }

    // The $rename operator renames a field.
    function rename(document) {
        if (oldKey&&newKey) {
            if (oldKey == newKey) {
                throw new Error("Bad $rename parameter: The new field name must differ from the existing field name.")
            } else if (document[oldKey]) {
                document[newKey] = document[oldKey];
                delete document[oldKey];
            }
        }
    }
}

I only have 3 test documents, so I set the pagesize to 1 to test the usage of continuation.
Test documents:

Output:

Hope it helps you.Any concern,please let me know.


text: Q: Printing multiple copies of the same document C# I have Receipt printer Epson TM-T88V. This printer cuts paper when printing ends. I need to print 5 copies of same document and cut paper for each of them automatically. But now, it cuts paper when all 5 copies are printed. I use PrintDocument class for printing. I also tried to put my printing method into cycle but it works too fast and printer can't print all 5 copies, it prints only 1-2 copies. Using Thead.Sleep() does not help.


text:
Q: Get combination of CD and description for PXSelector I'm trying to use a Selector to lookup up customers, and I want it to show the CD along with the description in the field.  I've seen this many times in Acumatica - and I thought I knew how to do it, but it's not working.  Here is my code:
     #region CustomerLookup
     public abstract class customerLookup : PX.Data.IBqlField
     {
     }
     protected string _CustomerLookup;
     [PXDBString(100, IsUnicode = true)]
     [PXUIField(DisplayName = "Customer Lookup")]
     [PXSelector(typeof(Customer.acctCD)
                ,typeof(Customer.acctCD)
                ,typeof(Customer.acctName)
                ,DescriptionField=typeof(Customer.acctName))]
     public virtual string CustomerLookup
     {
         get
         {
             return this._CustomerLookup;
         }
         set
         {
             this._CustomerLookup = value;
         }
     }
     #endregion

I would have thought providing the DescriptionField would take care of this, but it does not.

A: Before answering the question, let me first mention 2 major issues with the code snippet above:

*

*In Acumatica Customers is one the specific system object types, that supports segmented keys. To create a look up for records, that support segmented keys, you should be using the PXDimensionSelectorAttribute instead of the PXSelectorAttribute. For Customer entity there are several attributes provided out of the box, like the CustomerAttribute or the CustomerActiveAttribute, that  you can use to create Customer lookups:

*CustomerLookup field must be of the Int32? (int?) type: in Acumatica users can change Customer ID with time (via the Change ID button on the Customers screen). To establish a foreign key for the Customer DAC, the better approach is to declare an integer field and associate your custom record with Customers though the Customer.BAccount field
Below is the recommended declaration of a DAC field, that creates Customer lookup in UI:
[Serializable]
public partial class DetailsResult : IBqlTable
{
    ...

    #region CustomerId
    public abstract class customerId : PX.Data.IBqlField
    {
    }
    [Customer(DescriptionField = typeof(Customer.acctName))]
    public virtual Int32? CustomerID { get; set; }
    #endregion

    ...
}

With the DescriptionField property specified, PXDimensionSelector placed on a form will by default format selected record according to the "{SearchKey/SubstituteKey} - {DescriptionField}" pattern:

To show DescriptionField in a grid cell, you have to define additional column for the CustomerID_description field (where _description part is a special key word for Acumatica used specifically in this type of requests):

A: I believe the answer is one that's obvious - I don't think the description field works the same way in the grid.  In a header field, it works to show the CD - Description when you navigate off of it.  Grid fields apparently don't work that way, even when you specify the description field in the selector the way you would in a header selector.


text:
Q: C# WPF MenuItem custom template In Main.xaml I have these two menu items:

*

*The first with the header = Disconnect from current

*The second with the header = Quit

*...

*More menu items with different header texts...

In order to edit some colors of the first item I created a custom template in App.xaml:
<!--Template for Menu Items-->
    <Style x:Key="MenuItemBaseStyle" TargetType="MenuItem">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" Value="#0a99f3" />
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type MenuItem}">
                    <Grid Background="{TemplateBinding Background}">
                        <MenuItem Header="DISCONNECT FROM CURRENT" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And in Main.xaml:
<MenuItem Header="CONNECTION">
    <MenuItem Style="{StaticResource MenuItemBaseStyle}" Header="DISCONNECT FROM CURRENT" />
    <MenuItem Header="QUIT"/>
</MenuItem>

Now I want to do the same for the second menu item. The problem is with the different header. If I delete the header from the template, it won't show any header even if the header text is still present in Main.xaml
How can I use this template for many menu items where the only thing that changes is the header text?

A: You could just use TemplateBinding on the Header property in the same way you've used it on the Background property:
<ControlTemplate TargetType="{x:Type MenuItem}">
    <Grid Background="{TemplateBinding Background}">
         <MenuItem Header="{TemplateBinding Header}" />
    </Grid>
</ControlTemplate>

A: You can make an individual style for every MenuItem using a StyleSelector.
public class MyStyleSelector : StyleSelector
{
    public override Style SelectStyle(object item, DependencyObject container)
    {
        var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
        var index = itemsControl.ItemContainerGenerator.IndexFromContainer(container);

        if (index == 0)
            return (Style)itemsControl.FindResource("FirstItemStyle");
        if (index == 1)
            return (Style)itemsControl.FindResource("SecondItemStyle");

        return base.SelectStyle(item, container);
    }
}

And in your XAML
<Window x:Class="Menus.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Menus"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <local:MyStyleSelector x:Key="MyStyleSelector" />

    <Style x:Key="FirstItemStyle"  TargetType="MenuItem">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" Value="#0a99f3" />
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style x:Key="SecondItemStyle"  TargetType="MenuItem">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
                <Setter Property="Background" Value="Red" />
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<Grid>
    <Menu ItemContainerStyleSelector="{StaticResource MyStyleSelector}">
        <MenuItem Header="Menu 1" />
        <MenuItem Header="Menu 2" />
        <MenuItem Header="Menu 3" />
    </Menu>
</Grid>

See StyleSelector here: StyleSelector


text:
Q: Error when updating Manjaro with pamac: snapd already present on file system Yesterday, i wanted to get install updates using the pamac updater.
I got an error saying something along the lines of
files in conflict: snapd-git: /snap already exists in file system.

Since I am running Manjaro with the german language option, this is not exactly the message but i suppose it should be similar in english.
Now what i did first was un-checking it for update, but now i still get the update notification only about the package snapd-git.
I am unsure what my actual problem is:

*

*either the update is unnecessary in which case i'd like to get rid of the notification

*or I have an old version installed and have to manually remove it and install the current version.

I do not know if snapd gets used from any other applications, so i figured I'd ask here first before removing anything critical.
It would be appreciated if anybody could help me out.

A: From; https://wiki.archlinux.org/index.php/snapd#Removal

Uninstalling the snapdAUR package will not remove directories and
  files created while using snap. It's best to remove your snaps with
  snap remove before uninstalling the package. At this time it is not
  possible to remove the core snap through the snap command. To remove
  the state, snap package cache and mount unit files completely, you can
  follow the instructions below.

*

*We unmount any currently active snap that is mounted to /var/lib/snapd/snap/.

  # umount $(mount | grep snap | awk '{print $3}')

*We remove the state directory and mount hook.

  # rm -rf /var/lib/snapd
# rm -rf /var/snap

*We remove any unit files, that try to mount snaps from /var/lib/snapd/snaps to /var/lib/snapd/snap at boot.

  # find /etc/systemd/system -name "*snap-*.mount" -delete
# find /etc/systemd/system -name "snap.*.service" -delete

You will have to do these unmounts, and reinstall snap from AUR using # yaourt snapd.
Then resume system updates as normally.


text:
Q: Does IronPython support C# dynamic type? I have a C# code that I would like to convert to IronPython. One part of the code uses dynamic type to construct an object similar to the following construct:
dynamic user32 = new DynamicDllImport("user.dll", callingConvention: CallingConvention.Winapi);
user32.MessageBox(0, "Hello World", "Platform Invoke Sample", 0);

Is it possible to make IronPython aware of the user32's type (it being dynamic) at runtime and how would I properly invoke a method on it?
Thank you.


text:
Q: Github não esta registrando contributions Estou com o seguinte problema com o Github, ele não esta registrando minhas contributions apesar de que no repositório mostra que as atualizações estão sendo realizadas sem nenhum problema.Alguem sabe o que pode ser?Atualmente estou usando o visual code.

A: Rode esse comando no terminal git config --global user.name e veja se está aparecendo 'Richard' ou 'Richar2', se aparecer 'Richard', rode o seguinte comando git config --global user.name "Richar2" e depois tente commitar algo novamente, e veja se está contabilizando suas contribuições.
O motivo disso é que os seus últimos commits vieram com o nome de usuário Richard, porém seu nome no GitHub está como Richar2, e quando os mesmos estão diferentes, os commits realizados não são considerados seus.
Caso isso não resolva seu problema, também confira seu email git config --global user.email e veja se o e-mail configurado é o mesmo que você tem vinculado a sua conta do github, caso não for, rode o seguinte comando git config --global user.email seuemailaqui. (Mas acredito que o e-mail já está correto)


text:
Q: C Macro to Test Set Bits in Range How would one go about writing a macro in C that checks if any bits of a long are set within a range? If all the bits of a long are set within a range?
Could you do something like
#define TEST_ALL(number, high, low)    (1 & (number << low))

But that would only check the lowest bit. I understand you could do a for loop and just keep incrementing from low until you get to high checking bit by bit, but I'm wondering if there is a simpler solution with a macro that would be just as effective.

A: Let's assume 32-bit unsigned int for simplicity. You can get a mask of all 1-bits to the right of a given position 32-0 (including that position) with:
#define maskFrom(p) ((p == 32) ? 0xffffffffU : (1U << p) - 1)

You can get a range of bits with some simple bitwise manipulation, assuming p1 >= p2:
#define maskFromTo(p1, p2) maskFrom(p1) & ~maskFrom(p2)

These macros can be tested with the following complete program:
#include <stdio.h>

#define maskFrom(p) (((p) == 32) ? 0xffffffffU : (1U << (p)) - 1)
#define maskFromTo(p1, p2) maskFrom(p1) & ~maskFrom(p2)

int main(void) {
    // Do "right-of" checking.

    int p1 = 32;
    do {
        printf ("%2d: %08x\n", p1, maskFrom(p1));
    } while (--p1 > 0);

    // Do range checking with four-bit width.

    p1 = 32;
    do {
        printf ("%2d: %08x\n", p1, maskFromTo(p1,p1-4));
    } while (--p1 > 3);

    return 0;
}

which outputs:
32: ffffffff
31: 7fffffff
30: 3fffffff
29: 1fffffff
28: 0fffffff
27: 07ffffff
  : : : : :
 7: 0000007f
 6: 0000003f
 5: 0000001f
 4: 0000000f
 3: 00000007
 2: 00000003
 1: 00000001
32: f0000000
31: 78000000
30: 3c000000
29: 1e000000
28: 0f000000
27: 07800000
  : : : : :
 7: 00000078
 6: 0000003c
 5: 0000001e
 4: 0000000f

Then, to check if any of the bits within that range are set, and you value with the mask and check if non-zero result:
#define hasSomeBits(val, p1, p2) (((val) & maskFromTo((p1),(p2))) != 0)

Of course, the usual caveats apply when using macros as functions (such as parenthesising all your arguments and ensuring side-effects don't cause issues when arguments are evaluated more than once). You should probably try to avoid it where possible and just use real functions, along the lines of:
#include <stdint.h>

uint32_t maskFrom (const int p) {
    // Silently treat invalid input as zero.

    if ((p < 0) || (p > 32))
        return 0;

    // Create lookup table first time through.

    static int firstTime = 1;
    static uint32_t lookup[33];
    if (firstTime) {
        firstTime = 0;
        lookup[32] = 0xffffffffU;
        for (int i = 31; i >= 0; --i) {
            lookup[i] = lookup[i + 1] >> 1;
        }
    }

    // Just return the lookup.

    return lookup[p];
}

uint32_t maskFromTo (const int p1, const int p2) {
    // Allow for unordered parameters.

    if (p1 < p2)
        return maskFrom (p2) & ~maskFrom (p1);

    return maskFrom (p1) & ~maskFrom (p2);
}

int hasSomeBits (const uint32_t val, const uint32_t p1, const uint32_t p2) {
    return (val & maskFromTo (p1, p2)) != 0;
}


text:
Q: Kernel panic while installing Fedora 28 I tried to install Fedora-Workstation-Live 28 from USB, at the start of the Installation as I choose [Start Fedora-Workstation-Live 28] I get the following error. Any solution?

[1.81660] ---[end Kernel] panic - not syncing: VFS: unable to mount root fs on unknown-block(0,0).

(Sys: Lenovo z51 70 - OS: Linux, Ubuntu 18.04 - kernel version: 4.15)
the following errors happened:
as i selected the [Start Fedora-Workstation-Live 28]:

as i selected [start this media & Test]:

i changed the USB and got the following errors:

as i selected the [Start Fedora-Workstation-Live 28]:

as i selected [start this media & Test]:

A: Table of contents

*

*Please use a method of writing to the USB which re-checks the written data. This is probably quite difficult, sorry.

*How to verify using cmp command after dd.

*The initramfs read from your USB is damaged.

*Why I blame the initramfs read from the USB.

1. Please use a method of writing to the USB which re-checks the written data. This is probably quite difficult, sorry.
You are having boot problems that look very much like bad data on the USB.  Therefore, please use a USB writing method that re-checks the written data.
dd on its own, does not re-check the written data.  Please re-check the data manually using cmp, by following the exact instructions in the next section.  Unfortunately I couldn't think of any easier method.

*

*GNOME Disks can be used to write a USB (the Fedora install instructions tell you how).  But it doesn't seem to re-check the written data.

*The official Fedora install instructions "default" to Fedora Media Writer.  At least the version of Fedora Media Writer I have, does automatically re-check the written data after writing it to the USB.  I don't know an easy way to install Fedora Media Writer on your Ubuntu OS :-(.
https://docs.fedoraproject.org/f28/install-guide/install/Preparing_for_Installation.html

*Ubuntu's "Startup Disk Creator" did not work at all for me. I think it is only willing to write Ubuntu ISOs, not Fedora ones.
2. How to verify using cmp command after dd
In principle this could be a simple cmp command.  Very sadly, there are some difficulties that will return useless results, so I need to explain these.
I believe cmp might also show differences if you ever allowed the written USB to be mounted on a Linux system :-(.  This is likely to happen if you ever plugged it in again to a Linux system after writing it!  (Or successfully boot the Fedora Live USB??)  You have to be careful with it!
So you want to run dd to write the data, and then cmp command to verify the USB data, without re-plugging the USB (or rebooting) in between.
First run your dd command.  Remember to take great care and don't wipe your internal hard drive :).
Then remember you should run sync, to make sure the data is finished writing.
Then, you will be able to run echo 3 | sudo tee /proc/sys/vm/drop_caches.  This step is required, to make sure that cmp won't just be reading back from caches in system RAM.
Then you can run
# cmp Fedora-Workstation-Live-28.iso /dev/sdb

I.e. where sdb is the name of your USB device, and the .iso file is the name of your ISO file.  This command could show IO errors, or differences, if the problem is that your USB stick needs replacing.
In principle you might want to go further, and test the USB keeps its data correctly after it is removed and loses power.  So this would require an alternative method which disables the auto-mount of your graphical login.  It can be very hard to know how to disable auto-mount temporarily :-(.  I think the simplest way is to log in on a text console and run your commands from there.  Make sure you do not switch back to a graphical login before you have finished!  For some information about logging in on a text console, see here.
3. The initramfs read from your USB is (probably) damaged
From the evidence so far, it looks like the initramfs read from your USB is damaged.  You could try to verify the USB data, on the same system that you wrote the USB.  This could be useful to confirm some sort of problem writing to your USB.
For completeness, the full list of possibilities is :-

*

*a problem with writing to your USB

*a problem in the ISO image you wrote to it

*a problem in your computer e.g. EFI/BIOS problems during the early boot

*"incompatibility" between your computer and this version of Linux.  (That is, if someone thinks your computer is not to blame, they would have to blame the specific version of Linux :).

4. Why I blame the initramfs read from the USB
I found other unsolved mysteries described with the same error message and very similar conditions:

*

*Fedora Live Usb won't boot

*I can't make a bootable USB [of Fedora 24]...

*kernel panic -not syncing VFS: unable to mount root fs on unknown-block(0,0) on Fedora 22 installation

[1.81660] ---[end Kernel] panic - not syncing: VFS: unable to mount root fs on unknown-block(0,0).

Unfortunately, this isn't the real, specific error.
I have double-checked; Fedora-Workstation-Live 28 uses an initramfs.  This is sometimes also called a type of initrd.
This error would be shown if you set up a boot with both a kernel and an initramfs, but some error prevents the initramfs being loaded.
For example, one way to trigger this error, would be if you pressed a special key at the boot menu to start a temporary edit of the boot options.  In theory you might have started editing the boot options, and unintentionally removed an initrd option.  So I have to mention this as a possibility :).  Note this type of edit is temporary.  So you can just boot again, and make sure you're not making an edit that disables the initramfs :).
In this case the kernel may "fall through" to an old-style boot without an initramfs, but then it doesn't have any "block device" that it was specified to mount as the root fs.  "(0,0)" means "unknown"; this device number is never a valid block device.
But I don't think that's what you (and some others) did.
Therefore, I think there is probably a more specific error earlier in the boot process.  Unfortunately, if there was an error message, it is possible you can't see it because it scrolled off the top of the screen, if there were too many messages since then :).
An image search for "unable to mount root fs on unknown-block(0,0)." shows that is very common for the kernel call trace to fill the screen.  When this happens you cannot see if there is any previous error message.
I found an example of such an error, posted regarding a different Linux:
https://bbs.archlinux.org/viewtopic.php?id=220178
Initramfs unpacking failed: junk in compressed archive
Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)
...
--- [end Kernel] panic - not syncing: VFS: unable to mount root fs on unknown-block(0,0).

EDIT: called it :-).  "Initramfs unpacking failed:" was the real error.  "XZ-compressed data is corrupt" makes it clear the initramfs is not being read correctly from the USB

A: Solved. obviously the problem was from the USB so i tried to format the USB again with this command:

sudo dd if=/dev/zero of=/dev/sdb

then burning the .iso file on it. now it shows the installing page with no problem.


text:
Q: How to use new slds charts in lightning componets I could see that, salesforce release new feature in SLDS charts under Design Guidelines.
https://www.lightningdesignsystem.com/guidelines/charts/
I cannot see any explanation of how we can use these charts in lightning components. Did anyone try it? Please share your inputs.
Thanks !!!

A: I am not entirely sure I understand your question, so thank you for your patience if I miss the mark. The Design Guidelines provide design principles for creating or implementing charts. They do not provide the actual code or functionality.


text:
Q: Image recognition, how to start out As part of my dissertation for my BSc degree, I have to utilize image recognition on a video feed.
I have identified openCV and Tensorflow - specifically the Inception trained model - as two options, however I wouldn't know how to go on from there. Basically what I'll need is to pass a string such as "keys" and if one of the top 5 outcomes is "keys" get a boolean back.
Just to mention, I did a python course online since both use python. Also I have pretty solid experience with Java, we've been using it the past two years in our uni.
Note that I do not need to create a whole new image recognition system, I need to use one to tell me what my camera is seeing.
Also, while it is video, I think that it will be tougher to process the actual video feed. What I thought of is to pick out 1 of 30 frames (assuming a 30fps video feed) and run image recognition on that.
Thanks in advance!

A: Your project should be fairly straightforward if you read through this tutorial, and specifically the section, "Usage with Python API". The top N outcomes produced by classify_image.py are converted into human readable text here in this block of code:
top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
for node_id in top_k:
    human_string = node_lookup.id_to_string(node_id)
    score = predictions[node_id]
    print('%s (score = %.5f)' % (human_string, score))

For your example, you'd want to set FLAGS.num_top_predictions to 5 and you'd want to accumulate the top 5 human_string values as something like:
top_k_strings = []
top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
for node_id in top_k:
    human_string = node_lookup.id_to_string(node_id)
    top_k_strings.append(human_string)
    score = predictions[node_id]
    print('%s (score = %.5f)' % (human_string, score))

Finally, you could check if "keys" is one of the top 5 strings that imagenet produced and pass back a boolean as
return "keys" in top_k_strings

Also if you're interested in the full list of human-readable categories you can find them here
With respect to video, you're probably right that you'll have to subsample the video sequence to keep up with the frame rate. Some experimentation and timing tests will give you a feel for the subsampling rate that is needed.
Good luck!


text:
Q: Java - How do I undo a hashCode() and read as string? In my code I want to store passwords... but since it's an online program, I want to keep the passwords secret (duh). So I used "Password Here".hashCode(). Perfect. I got a crazy new code. Now how to I see if the password (in the password field (JTextField)) matches the password. I DON'T WANT THE HASHCODE-ED PASSWORD! I WANT THE REAL PASSWORD! (The opposite of hashCode())
if (PasswordField.getText().equals("HASH NUMBER HERE!")) {
    login(username, password, address, port);

But here I put in the already hashCode()-ed number... And I want it to be able to get the password before I changed it to hashCode()
I want to read the hashCode()-ed password into a not hashCoded()-ed String. the How do I do that?
Thanks!

A: You cannot "undo" (or "decrypt") a hash code. Hash codes are not a form of encryption.
First of all, you should not use hashCode() for passwords. You should use a cryptographic hash function instead.
The whole point of a cryptographic hash function is that it's a one way algorithm - given some input, you can compute the hash, but it is (practically) impossible to compute the original input back when you have only the hash.
How this normally works, is like this:

*

*In a database, you store a user's name and the hash of the user's password.

*When the user logs in, you calculate the hash of the password that the user entered when logging in.

*You compare that hash to the hash in the database. If they are equal, the user entered the correct password.

As you see, it is not necessary to "decrypt" the hash when you do it this way.
In practice, there are a lot more details to it to make it really secure. You should use a strong cryptographic hash function and a salt to make it more secure. Make sure you study this carefully before using it in any serious application that's going to be available on the web.

A: There is no opposite of hashCode. To check if an entered password is equal to the hashed (stored) version, just hash the entered password and check it against the known (stored) hash. For instance, using the hashCode method, you compare the int values of the passwords:
int storedHash = getStoredHash();
String password = passwordField.getText();
if ( storedHash != password.hashCode() ){
    //wrong
}

And side note: you might consider using something more secure than hashCode (MD5, SHA, etc...).


text:
Q: How do I say something past/back in future? I want to say something about future. But then, since that something does not exist, I want to refer it to the past! How do I say that?

10 amazing futuristic things I wish were real or  10 amazing futuristic things I wish will be real

For example, I'm creating a hypothetical situation of having some unbelievable features in a smart gadget of future. Say -using a smartphone, you can disappear! Using a smartphone, you can actually shoot at someone. Using a smartphone, you can even fly!
How do I say that then?

Three futuristic smartphone features I wish will be real ORThree futuristic smartphone features I wish were real OR Three futuristic smartphone features I wish will have been real

A: "Were" is used here in the subjunctive mood, referring to an event that is not likely or is untrue; see http://en.wikipedia.org/wiki/Subjunctive_mood.
futuristic things I wish were real is acceptable, meaning they don't currently exist but you wish they did exist now.
futuristic things I hope will be real is how I would phrase the second, though wish might be acceptable, too. It implies a hope for the future.
So my vote is for "Three futuristic smartphone features I wish were real," if by that you mean you want those features now, but they don't exist.
If you plan on making that phone, though, then it will have those features.

A: If you mean, these are futuristic features that you wish existed now, then you would say, "Ten futuristic smart phone features I wish were real."
If you mean that you hope these will be invented in the future ... well, you probably would say "hope" rather than "wish", so you'd say ... "Ten futuristic smart phone features that I hope will be real." You'd probably also add some time frame, like "that I hope will be real within the next decade" or at least "that I hope will be real someday."
We don't normally say, "I wish this will happen". If there's a grammar rule that breaks, I'm not sure what it is, but no one says that. Rather we say, "I hope this will happen" or "I wish this would happen."


text:
Q: How to combine current element with the next element when elment is "-" in list in python? I split a string into a list according to space. When element value is "-", I want to combine it with next elment.
For example,
['x^3', 'x', '-', '4'] want to transformed to ['x^3', 'x', '-4'].
['-', 'x^3', 'x', '-', '4'] want to transformed to ['-x^3', 'x', '-4'].
    b = "x^3 + x - 4".split(" ")
    b = [x for x in b if x != '+']
    #combine "-" with next element

A: The replace method of str would be useful:
s = "x^3 + x - 4"
new_s = s.replace('- ', '-').replace('+ ', '')
b = new_s.split(" ")

This is more elegant than using a for loop.
By the way, avoid using for loop and append of list if list comprehension can be used, because repeatedly calling append method is much slower than list comprehension.

A: With for loop you can do:
l1 = ['x^3', 'x', '-', '4']
l2 = ['-','x^3', 'x', '-', '4']

def func(x):
    new_x = []
    temp = None
    for i in x:
        if temp:
            i = temp+i
            temp = None
        if i == '-':
            temp = "-"
            continue

        new_x.append(i)

    return new_x

print(func(l1))
print(func(l2))

Output:
['x^3', 'x', '-4']
['-x^3', 'x', '-4']

A: Try this:
def main(arr: list) -> list:
    """Combines '-' with next element in list"""

    for i in range(len(arr)):
        try:
            if arr[i] == '-':
                arr[i + 1] = '-' + arr[i + 1]

                arr[i] = ''
        except IndexError:
            pass

    while True:
        if '' in arr:
            arr.remove('')
        else:
            break

    return arr

print(main(['-', 'x^3', 'x', '-', '4']))

Also you can use eval() for calculation:
b = "x**3 + x - 4"

x = 2

print(eval(b))


text:
Q: Second order transfer function with second order numerator? I was wondering if this is even possible.
For example, if the standard form of a transfer function is

is it still possible to have:

I've only ever seen this done in one place where they said this had  to be the equation for a high pass filter, but every other place I've seen has said the standard form should have less of an order in the numerator.
Would this even be correct, and would it have to be a high pass filter or could it also possibly be a low pass filter?

A: This would be a high pass filter. You have two zeros at the origin which are manifested as differentiators. This means that in the frequency domain you start off with a slope of +40dB per decade. This implies that as frequency increase, magnitude increases. Inversely, as frequency decreases, magnitude decreases. You can verify this by setting s=0, the numerator is 0, denominator is non-zero, your magnitude response is 0 at DC.
Lets look at s-> inf now to see high frequency behaviour. At large values of s, s^2 >> s, so dropping lower order terms. This leaves you with \$\frac{ks^2}{s^2}\$, which is simply k, your high frequency gain. So zero response at DC, bounded flat response at high frequency.
There are many standard (canonical) forms. Among them are canonical 2nd order lowpass, highpass, and bandpass transfer functions. This is a 2nd order highpass. The highest degree of numerator is equal to highest degree of denominator, meaning this equation is proper. A strictly proper equation has the denominator being one degree higher.
https://en.wikipedia.org/wiki/Proper_transfer_function

A: It is important to verify the homogeneity of transfer functions. The first one is not unitless unless \$k\$ has the dimension of a frequency. The way to write a transfer function is to respect a so-called low-entropy format, a term forged by Dr. Middlebrook some years ago. What it means is simply to express the formula so that you gain insight in what the expression does just by looking at it, for instance inferring from the expression if there are poles, zeroes, some gain etc. Also, you write a transfer function for a design purpose. In a bandpass filter, what matters is surely the resonant frequency but also the gain at the resonance. It is important to account for this goal when writing the transfer function. This is called design-oriented analysis or D-OA.
A transfer function should be expressed with a leading term carrying the unit or the dimension of what you want to express. If this is a gain that you write, then the leading term is a unitless term [V]/[V] or [A]/[A] for instance. If you write an impedance, then the leading term is resistance expressed in [\$\Omega\$]. This is extremely useful to check homogeneity of the formulas. In the case of a bandpass filter, a possible canonical expression is this one:

In this expression \$Q\$ is unitless and \$\omega_0\$ is expressed in rad/s. \$H_0\$ represents the gain at the resonance.
This is truly the most compact form you can find where the gain appears as the leading term. I have built a quick Mathcad sheet showing the factorization steps in \$H_1\$, \$H_2\$ and \$H_3\$:

You have here a good source of information on the bandpass filters.

A: It is possible to perform polynomial division so that
\$\frac{ks^2}{s^2+\frac{\omega_0}{Q}s+\omega_0^2}\$ takes the form
\$A + \frac{Bs+C}{Ds^2+Es+F}\$


text:
Q: Why index Sphinx returns attributes with empty values? In my config are set 2 index. When I use users_index I get output attributes in PHP with values. But when use same index medicalfacilities I get only names of attributes without values.
#medicalfacilities
source medicalfacilities : lsParentSource
{

    sql_query_range = SELECT MIN(idMedicalFacilities), MAX(idMedicalFacilities) FROM

medicalfacilities
    sql_range_step  = 128

    sql_query       = SELECT idMedicalFacilities * 10 + 1 as id, 2000 as type,

idmedicalfacilities, MedicalFacilitiesName, medicalfacilitiesiduser, medicalfacilitiessite,

medicalfacilitiesemail, medicalfacilitiesphoto FROM medicalfacilities WHERE

idMedicalFacilities>=$start AND idMedicalFacilities<=$end

    sql_attr_uint    = idmedicalfacilities
    sql_attr_uint     = type
    sql_attr_uint    = MedicalFacilitiesIdUser
    sql_field_string = MedicalFacilitiesSite
    sql_field_string = MedicalFacilitiesName
    sql_field_string = MedicalFacilitiesPhoto
    sql_field_string = MedicalFacilitiesEmail
    sql_query_info     = SELECT MedicalFacilitiesName, MedicalFacilitiesDescription \
                         FROM medicalfacilities WHERE idMedicalFacilities = ($id - 1) / 10

    # Время засыпания в миллисекундах (sleep) перед отправкой запросов серверу (может быть

полезно для разгрузки сервера базы данных)
    sql_ranged_throttle = 0
}

#users
source users : lsParentSource
{

    sql_query_range   = SELECT MIN(idDetailToUsers), MAX(idDetailToUsers) FROM detailtousers
    sql_query         = SELECT idDetailToUsers as id, 1000 as type, UsersTypeAccount,

idDetailToUsers, SpecializationName, DetailToUsersName, DetailToUsersPhoto, city, country FROM

detailtousers join users ON users.idUsers = detailtousers.idDetailToUsers left join

usersspecialization ON usersspecialization.UsersSpecializationIdUser =

detailtousers.idDetailToUsers left join specializationtousers ON

specializationtousers.idSpecialization = usersspecialization.UsersSpecializationIdSpecialization

WHERE idDetailToUsers >= $start AND idDetailToUsers <= $end GROUP BY idDetailToUsers

    sql_attr_uint     = type
    sql_attr_uint     = idDetailToUsers
    sql_attr_uint     = UsersTypeAccount
    sql_field_string  = SpecializationName
    sql_field_string  = DetailToUsersName
    sql_field_string  = DetailToUsersPhoto
    sql_attr_uint     = city
    sql_attr_uint     = country

    sql_query_info    = SELECT idDetailToUsers, DetailToUsersName, UsersTypeAccount,

SpecializationName, DetailToUsersPhoto, city, country \
                        FROM detailtousers WHERE idDetailToUsers = $id
    sql_ranged_throttle = 0
}

Indexes:
 index medicalfacilities {

        source = medicalfacilities

        path = /var/data/sphinx/medicalfacilities
        #enable_star = 1
        charset_type        = utf-8
        html_strip = 1
        #morphology = stem_ru
        min_word_len = 3
        min_prefix_len = 3
        #min_infix_len = 3
    }

    index users_index {

        docinfo       = extern
        source = users
        path = /var/data/sphinx/users
        charset_type  = utf-8
        html_strip    = 1
        morphology    = stem_enru
        min_word_len            = 1
        min_prefix_len          = 0
        min_infix_len           = 1
        enable_star = 1
    }

For index users return attributes with values, and for medicalfacilities - is not. Why?
I use PHP extension for Sphinx.


text:
Q: Open Gmail from Android application I'm trying to create an application that symply open Gmail. I use two function: startApplication and launchApp:
public void startApplication(String packageName){
            try
            {
                Intent intent = new Intent("android.intent.action.MAIN");
                intent.addCategory("android.intent.category.LAUNCHER");
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);

                for(ResolveInfo info : resolveInfoList)
                    if(info.activityInfo.packageName.equalsIgnoreCase(packageName))
                    {
                        toast = Toast.makeText(MainActivity.this, "Gmail opened", Toast.LENGTH_LONG);
                        toast.show();
                        launchApp(info.activityInfo.packageName, info.activityInfo.name);
                        return;
                    }
            }
            catch (Exception e)
            {
                toast = Toast.makeText(MainActivity.this, "Can't find Gmail", Toast.LENGTH_LONG);
                toast.show();
            }
        }

This is launchApp function:
private void launchApp(String packageName, String name)
    {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        intent.setComponent(new ComponentName(packageName, name));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

I call from my onCreate function of MainActivity

startApplication("com.gmail");

I try to run this application on emulator and smartphone, but the program crash. What is the error?

A: Finally I solved changing startApplication("com.gmail") with startApplication("com.google.android.gm")


text:
Q: Using a different value than the 'label' for a combobox I am looking to use a 'value' for my combo box lists similar to how you can do in HTML where you can have the label (whatever is shown in the combo box) and the value (being the returned value) like so:
List 1:
label="9am - 12pm", value="Morning"
label="12pm - 3pm", value="Afternoon"
label="3pm - 6pm", value="Evening"

So, the combo box will display the "9am - 12pm", etc. but the value returned will be "Morning".
Maybe I've been spending too much time on my web assignments that I'm going about this in a stupid way but any help would be appreciated.

A: Create a class to encapsulate the entity that you want to be displayed in the combo box:
import java.time.LocalTime ;

// maybe an enum would be good here too
public class TimeOfDay {

    private final LocalTime startTime ;
    private final LocalTime endTime ;

    private final String shortDescription ;

    public TimeOfDay(LocalTime startTime, LocalTime endTime, String description) {
        this.startTime = startTime ;
        this.endTime = endTime ;
        this.shortDescription = description ;
    }

    public LocalTime getStartTime() {
        return startTime ;
    }

    public LocalTime getEndTime() {
        return endTime ;
    }

    public String getShortDescription() {
        return shortDescription ;
    }
}

Now you can make a ComboBox that displays these:
ComboBox<TimeOfDay> timeOfDayCombo = new ComboBox<>();

timeOfDayCombo.getItems().addAll(
    new TimeOfDay(LocalTime.of(9,0), LocalTime.of(12,0), "Morning"),
    new TimeOfDay(LocalTime.of(12,0), LocalTime.of(15,0), "Afternoon"),
    new TimeOfDay(LocalTime.of(15,0), LocalTime.of(18,0), "Evening"));

You can customize the display by defining a list cell:
import java.time.LocalTime ;
import java.time.format.DateTimeFormatter ;

public class TimeOfDayListCell extends ListCell<TimeOfDay> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ha");

    @Override
    protected void updateItem(TimeOfDay timeOfDay, boolean empty) {
        super.updateItem(timeOfDay, empty) ;
        if (empty) {
            setText(null);
        } else {
            setText(String.format("%s - %s",
                formatter.format(timeOfDay.getStartTime()),
                formatter.format(timeOfDay.getEndTime())));
        }
    }
}

and then
timeOfDayCombo.setCellFactory(lv -> new TimeOfDayListCell());
timeOfDayCombo.setButtonCell(new TimeOfDayListCell());

Now calling timeOfDayCombo.getValue() will return the TimeOfDay instance, from which you can call any method you need (such as getShortDescription()).

A: What you can do is use a custome class that will hold those value. Use that class to create an ObservableList to create this Combobox.
public class MyHolder{
    private int id;
    private String label;

    public MyHolder(int id, String label){
        //...
    }

    //GETTER (AND SETTER IF NEEDED)

}

Then, using a StringConverter using this same class as type, you define the method toString to return the String you want.
public class MyConverterHolder extends StringConverter<MyHolder>{

    public String toString(MyHolder holder){
        return holder.getName();
    }
    //...
}

You set the converter to the combobox, and you are set.
Then to get the selectedValue, get the selectionModel, and get the item with getModelItem. Here you will get an instance of the specified type, just get the value you want.
This is a solution from documentation only, I didn't write an example to test it but this seems to be correct from what I have read. If this is not clear or not working, I will write an example (I could use a working example to get this started ;) ).

A: The combo box uses toString() so you just need to output there what you want to have displayed:
class TimeSpan
{
    String label,value;

    public TimeSpan(String label, String value)
    {
        this.label = label;
        this.value = value;
    }

    @Override public String toString() {return label;}
}

If for some reason you cannot do that, e.g. it's not your own class or you need toString() to work differently for some other case, you can encapsulate it as follows, assuming the class above as your base class:
class TimeSpanFormatter
{
    TimeSpan timeSpan;

    public TimeSpanFormatter(TimeSpan timeSpan)
    {
        this.timeSpan = timeSpan;
    }

    @Override public String toString() {return "Whatever you want to output with "+timeSpan.label;}
}

P.S.: This is the same as AxelH's approach, but I think you don't need the StringConverter.


text:
Q: Why student registration id showing instead of student name in odoo when i enter student's information then student id showing than student name.
here is url showin within form view.
Students/student.registration,2

A: It seems you don't have used/declared name field in student.registration object/class.
If you don't want to use/declare name field then you can use _rec_name for proper value display.
For example.
_rec_name = 'field_name'

It will show value of given field.
Or you can override the name_get method