text:
Q: Is it safe to assign a _bstr_t com property a LPCTSTR? I come across some code where a LPCTSTR is assigend to a _bstr_t. As a BSTR does provide length information according to MSDN and a common TCHAR pointer does not I am unsure if the following code is safe. I did not find a clue that there is an overloaded operator that makes this possible safely, however this seems to work without any obvious errors, but it might be undefined behaviour.
Example:
// pComObject->Property is of type _bstr_t
pComObject->Property = (LPCTSTR) string;

A: Yes, _bstr_t has an operator= which accepts a NULL-terminated string (both wide and multibyte), so this is safe


text:
Q: c# string .Startwith() any string from List I have a list of strings in example:
['xxx', 'xxxyy', 'ccccy']

and a normal string i.e. String example1 = "xxxyyy"
And I want to check if any of the strings in my list matches start of my example1
I dont need to know which strings match but only if example1 starts with any of the strings in the list.

A: You can use LINQ for that like this:
if (yourArray.Any(a => example1.StartsWith(a))

A: you can also use the below simple method using foreach loop.
you should also handle the null cases here.
private static bool StartsWith(string example1, string[] yourArray)
{
    if(example1 == null || yourArray == null)
    {
        return false;
    }
    foreach (string str in yourArray)
    {
        if (example1.StartsWith(str))
        {
            return true;
        }
    }

    return false;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maximize browser window automatically I'm developing a web application in PHP. I need to maximize the browser window automatically when my web page is opened in the browser. Is it possible? Is there any code for this? Will it support all kind of browsers? Can anyone help me? Thanks in advance for your help! :)

A: It isn't possible to maximize current window, but you could use the full screen mode of html5, supported from html5 capable browsers:
Using fullscreen mode


text:
Q: App Engine NDB query with multiple inequalities? The only two answers on here involve essentially restructuring the database to accommodate this limitation, but I am unsure how to do that in my case.
I have a list of thousands of contacts, each with many many properties. I'm making a page that has an ability to filter on multiple properties at once.
For example: Age < 15, Date Added > 15 days ago, Location == Santa Cruz, etc. Potentially a ton of inequality filters required. How does one achieve this in GAE?

A: According to the docs (for python),

Limitations: The Datastore enforces some restrictions on queries.
  Violating these will cause it to raise exceptions. For example,
  combining too many filters, using inequalities for multiple
  properties, or combining an inequality with a sort order on a
  different property are all currently disallowed. Also filters
  referencing multiple properties sometimes require secondary indexes to
  be configured.

If you check back in a few months, this may change. GAE keeps changing pretty quickly.
For now, though, you'll have to make multiple queries and combine them in your code.


text:
Q: Ubuntu 13.10 Cannot Detect Galaxy S4 Ubuntu won't recognize my S4 and on the phone it doesn't realize it's connected either, it just shows that it's charging.
I've read posts such as Ubuntu can't see my Android phone! but that shouldn't be a problem as 13.10 supports MTP.
Any ideas as to what's going on?
It came up with "Couldn't find matching udev device" as an error one time, but I can't get it to show up again.
Also, I tried installing mtp-tools and restarting but that didn't work either.
Edit:
If you're going to downvote this could you at least comment why?

A: In your mobile device settings, check if it is set to "connect as media device". If it is set to "connect in camera mode", it will not be detected by Ubuntu.


text:
Q: Angular - ngFor performance issues I have a video application written in Angular 4. In this app, user can add a video and subtitles, and edit the videos captions on a list. the captions in list are always synced with the video current play time. When video current time change, the list viewport is changed in order to display the current caption.
The number of captions always stay the same, user can not add or remove items only edit the caption text.
When having many captions (>500) the app is working very very slowly.
I thought about creating and destroying items in the ngFor according to the list viewport, but it seems to be to much work.
Is there a better solution (Not using pagging)
[![

import { Caption } from './caption';

export class Translation {
    public sourceCaption: Caption;
    public targetCaption: Caption;

    constructor(sourceCaption: Caption, targetCaption: Caption) {
        this.sourceCaption = sourceCaption;
        this.targetCaption = targetCaption;
    }

    get startTime() {
        return this.sourceCaption && this.sourceCaption.startTime;
    }

    get endTime() {
        return this.sourceCaption && this.sourceCaption.endTime;
    }
}

export class Caption{
    public startTime: number;
    public endTime: number;
    public text: Array<string>;
    public id: String;
    public isFlag: Boolean;
    public isItalic: Boolean;
    public languageId: String;
    public clientId: String;

    constructor(clientId: String, languageId: String, id?: String, startTime?: number, endTime?: number, text?: Array<string>, isFlag?:Boolean, isBold?:Boolean, isItalic?: Boolean ) {
        this.id = id;
        this.clientId = id || clientId;
        this.startTime = startTime;
        this.endTime = endTime;
        this.text = text || new Array<string>();
        this.isFlag = isFlag;
        this.languageId = languageId;
    }
}

  <tt-translation-list-header></tt-translation-list-header>

        <tt-translations-list-item [index]="i"
                                   [translation]="translation">
        </tt-translations-list-item>

          <tt-translations-list-item-header [caption]="translation.sourceCaption"
                                            [index]="index">
          </tt-translations-list-item-header>

              {{line}}

          <tt-target-caption-editor [editCaption]="translation.targetCaption">
          </tt-target-caption-editor>

]2

A: I would recommend you to render the list in parts or only the visible captions. If this is not solution for you try to set change detection to
ChangeDetectionStrategy.OnPush and set the click event on the parent element of the list, to avoid having thousand event clicks (for each row).
If your translations have ID's track by it trackBy: trackByFn
trackByFn(index, item) {
  return item.id
}

When you set changedetection OnPush you have to have always new instance of the array you provide to *ngFor, for ex:
let captions = [{id: 1, name: '1 caption'}];
// instead of
captions.push({id: 2, name: 'new caption'});
// you have to do
captions = caption.concat({id: 1, name: 'new caption'});

or if you have object, avoid mutating it, because OnPush works by comparing references of the inputs of the component.
While you did not provide a reference to a new object/array but instead mutated an existing one, the OnPush change detector did not get triggered.


text:
Q: GraalVM Quarkus Locale in native mode I have an unexpected behavior with available locales when native build. I have only one locale available in native mode.
My application is very simple :
@ApplicationPath("/api")
public class ApplicationPathConfiguration extends Application {
}

@Path("/locales")
public class LocaleController {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Locale[] get() {
        return Locale.getAvailableLocales();
    }

}

After checkout if I launch the application in dev mode :
mvn quarkus:dev

You can call the endpoint : http://localhost:8080/api/locales
curl http://localhost:8080/api/locales

This endpoint return a lot of locales :
["","nn","ar_JO","bg","kea","nds","zu","am_ET","fr_DZ","ti_ET","bo_CN","hsb","qu_EC","ta_SG","lv","en_NU","zh_SG_#Hans","en_MS","en_GG","en_JM","vo","kkj","sr_ME","sv_SE","es_BO","dz_BT","mer","sah","en_ZM","fr_ML","br","ha_NG","ar_SA","fa_AF","dsb_DE","sk","os_GE","ml","en_MT","en_LR","ar_TD","en_GH","en_IL","sv","cs","el","tzm_MA","af","sw_UG","ses_ML","smn","tk_TM","sr_ME_#Cyrl","ar_EG","dsb","lkt_US","vai_LR_#Latn","ji_001","yo_NG","se_NO","khq","sw_CD","vo_001","en_PW","pl_PL","fil_PH","it_VA","sr_CS","ne_IN","es_PH","es_ES","es_CO","bg_BG","ji","ar_EH","bs_BA_#Latn","en_VC","nds_DE","nb_SJ","es_US","agq","hsb_DE","en_US_POSIX","en_150","ar_SD","en_KN","ha_NE","pt_MO","ebu","ro_RO","zh__#Hans","lb_LU","sr_ME_#Latn","es_GT","so_KE","dje_NE","bas_CM","fr_PM","ar_KM","fr_MG","no_NO_NY","es_CL","mn","agq_CM","kam_KE","teo","tr_TR","eu","fa_IR","en_MO","wo","shi__#Tfng","en_BZ","sq_AL","ar_MR","es_DO","ru","twq_NE","az","nmg_CM","fa","kl_GL","en_NR","nd","kk","az__#Cyrl","en_MP","en_GD","tk","hy","shi__#Latn","en_BW","en_AU","en_CY","kab_DZ","kde_TZ","ta_MY","ti_ER","nus_SS","en_RW","nd_ZW","sv_FI","ksb","luo","lb","ne","en_IE","zh_SG","ln_CD","en_KI","nnh_CM","om_ET","no","ja_JP","my","ka","ar_IL","mgh","or_IN","fr_MF","shi","kl","en_SZ","rwk_TZ","zh","es_PE","mgh_MZ","saq","az__#Latn","ta","en_GB","lag","zh_HK_#Hant","ar_SY","ksf_CM","bo","kk_KZ","es_PA","tt_RU","om_KE","ar_PS","en_AS","fr_VU","zh_TW","bez","kln","fr_MC","kw","pt_MZ","fr_NE","vai__#Latn","ksb_TZ","ksh","ur_IN","ln","en_JE","gsw_CH","ln_CF","en_CX","luy_KE","pt","en_AT","gl","kkj_CM","sr__#Cyrl","yue_CN_#Hans","es_GQ","kn_IN","ar_YE","to","en_SX","ga","qu","ru_KZ","en_TZ","et","en_PR","mua","ko_KP","in","ps","sn","nl_SR","rof","en_BS","km","zgh","fr_NC","be","gv","es","dua","gd_GB","jgo","nl_BQ","fr_CM","gsw","uz_UZ_#Cyrl","pa_IN_#Guru","en_KE","guz","mfe","asa_TZ","teo_UG","ja","fr_SN","or","brx","fr_MA","pt_LU","fr_BL","en_NL","mgo_CM","ln_CG","te","sl","ko_KR","el_CY","mr_IN","ha","es_MX","lrc_IR","gsw_FR","es_HN","hu_HU","ff_SN","sbp","sq_MK","sr_BA_#Cyrl","fi","uz","bs__#Cyrl","et_EE","sr__#Latn","en_SS","sw","bo_IN","fy_NL","ar_OM","tr_CY","nmg","rm","en_MG","fr_BI","uz_UZ_#Latn","bn","dua_CM","de_IT","lrc_IQ","vai__#Vaii","kn","fr_TN","sr_RS","de_CH","bn_BD","nnh","fr_PF","en_ZA","gu","pt_GQ","vun_TZ","jmc_TZ","en_TV","lo","fr_FR","en_PN","en_MH","fr_BJ","zh__#Hant","cu_RU","zh_HK_#Hans","nl_NL","sah_RU","en_GY","ps_AF","bs__#Latn","ky","mas","dyo_SN","os","bs_BA_#Cyrl","nl_CW","ar_DZ","sk_SK","pt_CH","fr_GQ","ff_CM","am","en_NG","fr_CI","ki_KE","en_PK","zh_CN","en_LC","rw","brx_IN","wo_SN","iw","gv_IM","mk_MK","en_TT","dav","sl_SI","fr_HT","te_IN","nl_SX","lrc","ses","ce","fr_CG","fr_BE","jgo_CM","mt_MT","es_VE","mg","mr","mer_KE","ko","nds_NL","en_BM","nb_NO","ak","seh","kde","dz","kea_CV","mgo","vi_VN","en_VU","en_US","to_TO","mfe_MU","seh_MZ","fr_BF","pa__#Guru","it_SM","fr_YT","gu_IN","ii_CN","pa_PK_#Arab","ast","fr_RE","fi_FI","yue__#Hans","ca_FR","sr_BA_#Latn","bn_IN","fr_GP","pa","zgh_MA","uk_UA","fr_DJ","rn","tg","rwk","hu","fr_CH","en_NF","twq","ha_GH","sr_XK_#Cyrl","bm","ar_SS","en_GU","nl_AW","de_BE","en_AI","en_CM","xog_UG","cs_CZ","tr","ca_ES","cgg","rm_CH","nyn_UG","ru_MD","ms_MY","ta_LK","ksf","en_TO","cy","en_PG","fr_CF","pt_TL","sq","fr","tg_TJ","en_ER","qu_PE","sr_BA","es_PY","de","es_EC","kok_IN","lg_UG","zu_ZA","fr_TG","sr_XK_#Latn","en_PH","ig_NG","fr_GN","prg_001","cgg_UG","zh_MO_#Hans","ksh_DE","lg","ru_RU","se_FI","ff","en_DM","en_CK","sd","ar_MA","ga_IE","en_BI","en_AG","fr_TD","en_WS","fr_LU","ebu_KE","bem_ZM","xog","ewo_CM","fr_CD","so","rn_BI","en_NA","ar_ER","kab","ms","nus","sn_ZW","prg","iw_IL","ug","es_EA","th_TH_TH_#u-nu-thai","hi","fr_SC","ca_IT","lag_TZ","en_SL","teo_KE","no_NO","ca_AD","zh_MO_#Hant","en_SH","vai","qu_BO","haw_US","vi","fr_CA","de_LU","sq_XK","dyo","en_KY","mt","it_CH","de_DE","si_LK","luo_KE","en_DK","yav","so_DJ","lt_LT","it_IT","eo","kam","ar_SO","en_ZW","ro","eo_001","ee","en_UM","nn_NO","fr_MU","pl","se_SE","en_TK","en_SI","mua_CM","ur","uz__#Arab","vai_LR_#Vaii","saq_KE","se","pt_GW","lo_LA","chr","ar_LB","af_ZA","ms_SG","ee_TG","ln_AO","be_BY","ff_GN","yue__#Hant","in_ID","es_BZ","ar_AE","hr_HR","luy","as","rof_TZ","it","pt_CV","ks_IN","uk","my_MM","ur_PK","mn_MN","da_DK","en_FM","es_PR","wae_CH","mzn","en_BE","ii","tt","fr_WF","ru_BY","mzn_IR","naq","fo_DK","en_SG","ee_GH","ar_BH","kln_KE","tzm","fur","om","hi_IN","en_CH","asa","yo_BJ","fo_FO","ast_ES","fr_KM","bez_TZ","fr_MQ","en_SD","es_AR","en_MY","ja_JP_JP_#u-ca-japanese","es_SV","pt_BR","ml_IN","sbp_TZ","fil","en_FK","uz__#Cyrl","is_IS","yue_HK_#Hant","hy_AM","en_GM","en_DG","fo","ne_NP","hr","pt_ST","ak_GH","lt","uz_AF_#Arab","fur_IT","ta_IN","ccp","en_SE","fr_GF","lkt","zh_CN_#Hans","is","es_419","si","pt_AO","en_001","en","guz_KE","gsw_LI","ccp_BD","es_IC","ca","ru_KG","fr_MR","ar_TN","ks","zh_TW_#Hant","bm_ML","kw_GB","ug_CN","as_IN","es_BR","zh_HK","khq_ML","sw_KE","en_SB","th_TH","rw_RW","chr_US","shi_MA_#Tfng","ar_IQ","nyn","yue","jmc","en_MW","naq_NA","mk","en_IO","ar_QA","en_DE","pa__#Arab","en_CC","bs","ro_MD","en_FI","pt_PT","fy","az_AZ_#Cyrl","th","dav_KE","ckb_IQ","shi_MA_#Latn","es_CU","ar","en_SC","en_VI","haw","eu_ES","en_UG","en_NZ","dje","es_UY","bas","mas_KE","ru_UA","sg_CF","el_GR","yav_CM","uz__#Latn","sg","da_GL","en_FJ","de_LI","en_BB","km_KH","smn_FI","hr_BA","de_AT","ckb_IR","nl","lu_CD","ca_ES_VALENCIA","ar_001","so_SO","lv_LV","ckb","es_CR","fr_GA","ar_KW","sr","ar_LY","sr_RS_#Cyrl","bem","en_MU","da","wae","gl_ES","en_IM","az_AZ_#Latn","en_LS","ig","en_HK","en_GI","ce_RU","en_CA","gd","ka_GE","fr_SY","sw_TZ","fr_RW","so_ET","nl_BE","ar_DJ","mg_MG","cy_GB","en_VG","cu","os_RU","sr_RS_#Latn","en_TC","ky_KG","sv_AX","af_NA","vun","en_IN","lu","ki","yo","es_NI","nb","ff_MR","sd_PK","mas_TZ","ti","kok","ewo","ms_BN","ccp_IN","br_FR"]

If I do the same in native mode :
mvn clean package -Pnative && ./target/QuarkusLocale-1.0-SNAPSHOT-runner

I obtain only one locale :
["fr_US"]

How can I obtain all available locale ?
Moreover, because of this behavior I have another problem. As you can see if I tried to develop a service who want use locale. Locale is not use and I can't apply currency format. To demonstrate that, I develop CurrencyController.
@Path("/currency")
public class CurrencyController {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String get(String localeString) {
        String[] localeArray = localeString.split("-");
        Locale locale = new Locale(localeArray[0], localeArray[1]);

        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
        numberFormat.setCurrency(Currency.getInstance("USD"));
        return numberFormat.format(1337);
    }

}

You can call it with curl :
curl -X POST http://localhost:8080/api/currency -H "Content-Type: application/json" -d "en-GB"
> US$1,337.00

curl -X POST http://localhost:8080/api/currency -H "Content-Type: application/json" -d "en-US
> $1,337.00

If I do the same in native mode :
curl -X POST http://localhost:8080/api/currency -H "Content-Type: application/json" -d "en-GB"
> US$1,337.00

curl -X POST http://localhost:8080/api/currency -H "Content-Type: application/json" -d "en-US
> US$1,337.00

*

*Running Quarkus native-image plugin on GraalVM Version 19.3.1 CE

*Quarkus 1.4.1.Final

A: This is a very well-known issue on GraalVM. Currently, the only way to bypass it is to create Feature that will scan all locales at run time:

*

*Add maven dependency

        <dependency>
            <groupId>org.graalvm.nativeimage</groupId>
            <artifactId>svm</artifactId>
            <version>19.3.1</version>
        </dependency>

*Create Feature class

package org.example;

import com.oracle.svm.core.annotate.AutomaticFeature;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.impl.RuntimeClassInitializationSupport;

import java.util.Locale;

@AutomaticFeature
public class NativeLanguageFeature implements Feature {

    @Override
    public void beforeAnalysis(BeforeAnalysisAccess access) {
        ImageSingletons.lookup(RuntimeClassInitializationSupport.class).initializeAtBuildTime(SupportedLocales.class, "__");

        final Locale[] availableLocales = Locale.getAvailableLocales();
        final SupportedLocales supportedLocales = new SupportedLocales();
        supportedLocales.locales = availableLocales;
        ImageSingletons.add(SupportedLocales.class, supportedLocales);
    }

    public static class SupportedLocales {
        public Locale[] locales;
    }
}

*In a place where you want to access locales, check if SupportedLocales present in ImageSingletons
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Locale[] get() {
        if(ImageSingletons.contains(NativeLanguageFeature.SupportedLocales.class)){
            final NativeLanguageFeature.SupportedLocales lookup = ImageSingletons.lookup(NativeLanguageFeature.SupportedLocales.class);
            return lookup.locales;
        }
        return Locale.getAvailableLocales();
    }

You probably will need to do same thing with money as well.

A: This happens to keep the native executable small as possible, so only the default locale is added to the bundle. The GraalVM allows you to add more custom locales at build time with -H:IncludeLocales=fr,en,....
More information in https://www.graalvm.org/22.1/reference-manual/native-image/Resources/#locales


text:
Q: Loop over array I need a piece of powershell-code to search and replace a certain string inside a text-file. In my example, I want to replace 23-06-2016' with '24-06-2016'. The script below does this job:
$original_file  = 'file.old'
$destination_file   = 'file.new'

(Get-Content $original_file) | Foreach-Object {
$_ -replace '23-06-2016', '24-06-2016' `
} | Out-File -encoding default $destination_file

As the search / replace string change I want to loop over an array of dates which might look like this:
$dates = @("23-06-2016","24-06-2016","27-06-2016")

I tried use the
$original_file  = 'file.old'
$destination_file   = 'file.new'

foreach ($date in $dates) {
  (Get-Content $original_file) | Foreach-Object {
  $_ -replace 'date', 'date++' `
  } | Out-File -encoding default $destination_file
}

In a first step, the date '23-06-2016' should be replaced by '24-06-2016' and in a second step, the date '24-06-2016' should be replaced by '27-06-2016'.
As my script is not working I am seeking for some advice.

A: You are using $date as your instance variable in your foreach loop but then referencing it as 'date', which is just a string. Even if you used '$date' it would not work because single-quoted strings do not expand variables.
Further, $date is not a number, so date++ would not do anything even it were referenced as a variable $date++. Further still, $var++ returns the original value before incrementing, so you would be referencing the same date (as opposed to the prefix version ++$var).
In a foreach loop, it's not very practical to refer to other elements, in most cases.
Instead, you could use a for loop:
for ($i = 0; $i -lt $dates.Count ; $i++) {
    $find = $dates[$i]
    $rep = $dates[$i+1]
}

This isn't necessarily the most clear way to do it.
You might be better off with a [hashtable] that uses the date to find as a key, and the replacement date as the value. Sure, you'd be duplicating some dates as value and key, but I think I'd rather have the clarity:
$dates = @{
    "23-06-2016" = "24-06-2016"
    "24-06-2016" = "27-06-2016"
}

foreach ($pair in $dates.GetEnumerator()) {
    (Get-Content $original_file) | Foreach-Object {
      $_ -replace $pair.Key, $pair.Value
    } | Out-File -encoding default $destination_file
}


text:
Q: Could two different bases of a Hilbert space have different cardinality? Here is a quote from http://en.m.wikipedia.org/wiki/Hilbert_space#Hilbert_dimension (accessed: Nov. 22, 2013) :

As a consequence of Zorn's lemma, every Hilbert space admits an orthonormal basis; furthermore, any two orthonormal bases of the same space have the same cardinality, called the Hilbert dimension of the space.

But it seems to me that for a lot of quantum systems this is not so. For example, the one dimensional harmonic oscillator has a countable basis of energy eigenstates but an uncountable basis of position eigenstates (whose wave functions are delta functions).
So where am I wrong? I assume the answer has to do with the fact that delta functions are not actually part of the Hilbert space. Is that it?

A: As you and Christoph already pointed out, the difference comes from the fact that these contiuous "bases" do not belong to the respective Hilbert space themselves.
This is why they are not actually bases at all in the general sense.
Rather, they are useful mathematical tools to expand any states actually belonging to the Hilbert space. As they obey certain orthonormality and completeness conditions they are also referred to as "continuous bases" (rough summary of section 2.1.3 of "Quantum Mechanics" by Claude Cohen-Tannoudji).


text:
Q: Save the pointer value in parse.com with iOS Swift I want to add an id to a pointer field in Parse.  I have 2 classes categories and Ads.  In the categories class, the objectId is a String that I am using to get all the fields of the Ads class. In the Ads class, the cat field is a pointer to categories. Now I add the cat id with another column that is a String. The String field is added but the pointer column 'cat' is not added.
Here is the code:
let ex = "s8HiwfvKtQ"
let posts = PFObject(className: "Ads")
posts.setObject(ex, forKey: "cat")

or alternatively
posts["cat"] = ex
posts.saveInBackground()

I tried the above code and found other solutions but still cannot save the cat field.
Below is a screenshot of the categories and Ads classes:

Error in console is:

invalid type for key cat, expected *categories, but got string (Code: 111, Version: 1.10.0)

A: It is throwing error because cat is a category object and you are setting object as String you must set an object for cat row.
you must do something like:
 let ex = PFObject(className: "categories")
        ex.objectId = "s8HiwfvKtQ"

        let posts = PFObject(className: "Ads")
        posts.setObject(ex, forKey: "cat")

        posts.saveInBackgroundWithBlock { (success, error) -> Void in
            if let error = error{
                print(error.localizedDescription)
            }else{
                print(success)
            }
        }


text:
Q: How to force Focus on Child Forms? I need to Focus on a Form.
I tried in Form2:
//...

var form3 = new Form3(this);

if (System.Windows.Forms.Application.OpenForms[form3.Name] == null)
{
    form3.Show();
}

else
{
    System.Windows.Forms.Application.OpenForms[form3.Name].Focus();
}

and then in Form3:
public partial class Form3 : Form
{
    public Form2 _emailForm;

    public Form3 (Form2 emailForm)
    {
        _emailForm = emailForm;
        InitializeComponent();
    }

    public void foo()
    {
        _emailForm.ForceFocus();
        this.Close();
    }
}

But the Form is never Focused.
Can someone point out what I'm doing wrong?
Thanks in advance.

A: You can simplify it like this:
public Form1(Form parent)
{
    InitializeComponent();
    _parent = parent;
}

private void button1_Click(object sender, EventArgs e)
{
    if (_parent != null)
        _parent.Focus();
}

I hope it answers your question. Otherwise please leave a comment.
EDIT
Both Show() and BringToFront() are using SafeNativeMethods.ShowWindow(...) internally. So you won't notice any difference. However, I think it is more common to use Show() or Activate() on Form objects, and BringToFront() on Control objects, that are part of other Control objects.

A: If you absolutely want the user to take action in Form2 prior to being able to utilize Form1 again use .ShowDialog() instead of .Show()


text:
Q: Custom Template with header and a line over the entire page I am trying to replicate a template on MS word using LaTeX. The template is as shown in the  picture below and must be applied to the entire document.

So far I succeeded to either have the text in the header using fancyhdr (but I failed to apply it to all pages, it is missing from the list of figures page and pages that include the chapter name) or to have the blue line on the left side (same problem as above) using put \rule. For some reason, I am not able to have them both at the same time and for all pages in the document.
I am including my preamble, hoping you can advise me on the way to tackle this issue.
% Preamble
\documentclass[12pt]{report}
\makeatletter
\def\bstctlcite#1{\@bsphack
\@for\@citeb:=#1\do{%
\edef\@citeb{\expandafter\@firstofone\@citeb}%
\if@filesw\immediate\write\@auxout{\string\citat
ion{\@citeb}}\fi}%
\@esphack}
\makeatother
% Packages
% ---
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{afterpage}

\usepackage{color}
\usepackage{setspace}
\usepackage{footmisc}
\usepackage{color}
\usepackage{soul}
\usepackage{ulem}
\newcommand\semiHuge{\@setfontsize\semiHuge{23}{28}}
\def\blfootnote{\gdef\@thefnmark{}\@footnotetext}
\newcommand{\red}[1]{\textcolor{red}{#1}}
\newcommand{\blue}[1]{\textcolor{blue}{#1}}
\newcommand{\green}[1]{\textcolor{green}{#1}}
\usepackage[top=2.54cm, includehead,headheight=45pt,bottom=2.54cm,left=2.54cm,right=2.54cm]{geometry}
\definecolor{lightblue}{RGB}{157,225,230}
\definecolor{purple}{RGB}{188,165,207}
\definecolor{darkblue}{RGB}{146,154,200}
\newcommand{\lightblue}[1]{\textcolor{lightblue}{#1}}
\newcommand{\purple}[1]{\textcolor{purple}{#1}}
\newcommand{\darkblue}[1]{\textcolor{darkblue}{#1}}
\usepackage{amsmath} % Advanced math typesetting
\usepackage{hyperref} % Add a link to your document
\usepackage{graphicx} % Add pictures to your document
\usepackage{listings} % Source code formatting and highlighting
\usepackage{setspace}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage[draft=true]{scrlayer}

\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}%I dont want blck line in header

\lhead{\textbf{\lightblue{\Large{Final Report}}\\
\purple{ECE 491: ECE Capstone Design Project -1\\
Fall 2017}}
}
\fancyhead[R]{\includegraphics[scale=0.5]{CoE.jpg}}
%\DeclareNewPageStyleByLayers{titlestyle}{test}
%
%
%\DeclareNewLayer[
%  background,
%  innermargin,
%  width=1cm,
%  hoffset=1cm,
%  contents={\color{lightblue}\rule{\layerwidth}{\layerheight},\put(-30,650){\color{darkblue}\rule{.25in}{2in}} }
%]{test}
\doublespacing
%\pagestyle{titlestyle}
\usepackage{mathptmx}
\title{Internship report}
\author{Rawan}
\date{\today}

\usepackage{blindtext}

\begin{document}

\newpage
\listoffigures
\listoftables
\tableofcontents

\newpage
\chapter{\large \textbf{Introduction}}
\blinddocument
\end{document}

A: Some pages in a LaTeX document have different pagestyles compared to the "normal" one. For instance \chapter typically uses \thispagetsyle{plain}.
You could try using the memoir class (a superset of book, report and article classes) which provides commands for setting the pagestyle for chapters, list of figures, etc. Along the lines of:
\documentclass{memoir}
 % your preamble
\aliaspagestyle{chapter}{your page style}
\aliaspagestyle{listoffigures}{your page style}

Untested. But read chapter Seven Pagination and headers in the documentation (< texdoc memoir) for more information.


text:
Q: How to limit the search index fields in Magento? We are using elastic search 6.x and facing search index limit exceeded error. As per this doc

https://support.magento.com/hc/en-us/articles/360003290654-Exception-on-category-page-with-Elasticsearch-5-0-Limit-of-total-fields-1000-in-index-has-been-exceeded
  How can we limit the search index fields in Magento? Any body knows where that setting or config resides in Magento


text:
Q: How do I write a bash script to restart a process if it exits gracefully? So I read this How do I write a bash script to restart a process if it dies? and quickly discovered that this was not the dilemma I'm facing.
I copied the below into /etc/init/ and it appears to be working.
description "Forever my process"

start on started mountall
stop on shutdown

respawn
respawn limit 5 5

script
    export HOME="/root"

    exec my_process >> /var/log/my-process.log 2>&1
end script

A: A simple way:
while sleep 1; do
    echo "success"
done

Seems to work fine for me.
Replace sleep 1 with the command to start your process.

edit: this is an answer for the question in the title, I'm not sure what /etc/init or the code you gave has to do with the question

A: Given that this works, I'm posting this as an answer. If there is a better way to do it, please add.
description "Forever my process"

start on started mountall
stop on shutdown

respawn
# respawn limit 5 5 - use this if you want to limit it for any reason

script
    export HOME="/root"

    exec my_process >> /var/log/my-process.log 2>&1
end script


text:
Q: How to implement thousand separator in string Data Frame without modifications in one row with percentage values in Python Pandas? I have Pandas Data Frame in Python like below, be aware that every value is STRING!:
IDX | COL1 | COL2
------------------
ABC | 130  | 0
DEF | 5409 | 346
GHI | 34.9 | 25.3

And i try to implement here thousand separator in above Data Frame, so I need something like below:
IDX | COL1 | COL2
------------------
ABC | 130   | 0
DEF | 5 409 | 346
GHI | 34.9  | 25.3

BE AWARE:

*

*each value is string

*IDX column is index

*index GHI has only percent values like: 34.9 and 25.3 and this rows should stay WITHOUT any modifications

How can I do that in Python Pandas ?

A: You can apply this function onto .apply()
def thousand_sep(text):
    try:
        text = int(text)
        return "{:,}".format(text)
    except:
        return str(text)

print(thousand_sep("1918.18"))

For practical use-case:
import numpy as np
import pandas as pd

def thousand_sep(text):
    try:
        text = int(text)
        return "{:,}".format(text)
    except:
        return str(text)

df = pd.DataFrame(data={"COL1":{"ABC":"130", "DEF":"5409", "GHI":"34.9"}, "COL2":{"ABC":"0", "DEF":"346", "GHI":"25.3"}})
df["COL1"], df["COL2"] = np.vectorize(thousand_sep) ([df['COL1'], df['COL2']])
print(df)

Unfortunately I couldn't find a work-around to get a " " instead of a "," after the 3 digits.


text:
Q: How to get a float from a character I have a char like
'0'
From which I need to get the float value
0.0
However, when I try casting the char to a float using (float)'0' I get 48.0 instead of 0.0. The same thing happens when I attempt to use the float.valueOf('0') method.
Any help would be appreciated.

A: By casting char to float you are getting char ascii value. Float parseFloat and valueOf methods can be used to value casting. You can read this page for detailed info from here: https://way2java.com/casting-operations/java-char-to-float If you convert char to string and try below you can get the desired result:
String a = "0";
float f = Float.valueOf(a);
System.out.println(f);

A: You need to subtract the ASCII (unicode) value for '0' (which is why you get 48.0)...
public class CTF {

    public static void main(String[] args) {
        char c = '0';
        float f = (float) (c - '0');
        System.out.println(f);
    }
}

It's a bit odd though because if you input a non-number such as 'G', you get 23.0. ' ' yields -16.0

A: Float.parseFloat(String.valueOf('0'));

0.0


text:
Q: How to make the message/label to be closed I need your help or some pointers on my challenge.
In my web application, I am displaying a warning message and a dashboard to the user.
The message is a label that tells some information about the dashboard. I am playing the dashboard in browser frame.
Please refer to the code below,
Label warningMessage = new Label("Warning : Dashboard is only accessible under local network/VPN.");
BrowserFrame boxInfo = new BrowserFrame(null, new ExternalResource(address));
boxInfo.setSizeFull();
VerticalLayout layout = new VerticalLayout();
layout.addComponent(warningMessage);
layout.addComponent(boxInfo);
layout.setExpandRatio(warningMessage, 0);
layout.setExpandRatio(boxInfo, 1);
layout.setSizeFull();
body.addComponent(layout);
body.setSizeFull();

My requirement as follows,
The label or any other component that display the message, should have a privilege to be closed as soon as the user clicks "X" button on the label.
It should be like
Warning : Dashboard is only accessible under local network/VPN.                            X
When the user reads the message and clicks on the "X" button/whatever it is. The message should disappear and browser frame  needs to be re-sized to occupy the space of the label/component.
Please advice how to do this.

A: I would most likely create a new server-side component for it.
pseudocode below.
class ClosableLabel extends HorizontalLayout {
  public CloseableLabel(String label, Button.ClickListener listener){
    addComponent(new Label(label));
    addComponent(new Button("x", listener);
  }

  // Probably needs some setters and such
}

In the view, you can then use these:
CloseableLabel label = new CloseableLabel("Warning : Dashboard is only accessible under local network/VPN.", new ClickListener {
  @Override
  public onClick(event){ //or what ever the implementable method of ClickListener is called.
    layout.removeComponent(label);
  }
});
layout.addComponent(label);

Then you can add more features to this component, like borders to the label, better icon than the letter x, no borders to the button, transitions etc. etc.
All the code was written directly into StackOverflow and needs to be error checked and properly implemented.


text:
Q: Better time to compile/install/test cycle my project is growing large, and I am facing the following problem: the compile/transform-to-dalvik/install cycle takes too long.
It takes around 2 minutes since I press F11 (or ^F11) until the dialog to choose the device is shown, and around another minute from there until the application is shown on the phone.
3 minutes may not seem like a waste of time, but it breaks the concentration (actually, I am writing this post during those 3 minutes).
Do you have any trick to avoid this? Any way to avoid the full dalvik conversion when only a couple of classes have been modified? Any way to live-copy the classes to the phone without the need of the .class-dalvik-.apk-copy-install cycle?
Any other hint?


text:
Q: How do you implement a max-heap? So I've read up on heaps, and I understand the basic concept,
but not how to actually implement it.
Basically, my issue is

*

*How you know where to put a new node?

*How you know which node to replace the root with when you delete?


text:
Q: How can I edit my savegames? In previous SCS games, savegames were in text format, so you could easily edit them. The .sii files used for savegames in Euro Truck Simulator 2 seem to be in some binary format instead.
Is there a way I can edit my savegames?

A: ETS2 is a pain in the ass when it comes to editing savegames. I have found a nifty tool on the truckersmp forum. Maybe give that a try?
There is a full explaination on how to edit the save game.
Best of luck.


text:
Q: How to use OData in Asp.net Core Web API without Entity Model? I am using OData in Asp.net Core web API. I am new to OData.
I used the Odata like this:
Controller
 [EnableQuery]
 public async Task<ActionResult> ListAsync([FromODataUri]ODataQueryOptions<Orders> opts)
 {
   .........
 }`

Model
 public List<Orders> GetList(ODataQueryOptions<Orders> opts)
 {
     if (order.Count == 0)
        BindDataSource();
     var results = order.AsQueryable();
     var count = results.Count();
     if (opts.OrderBy != null)
        results = opts.OrderBy.ApplyTo(results);
     if (opts.Filter != null)
     {
        if (opts.Filter.RawValue.Contains("substring"))
        {
            string key = opts.Filter.RawValue.Split(new string[] { "'" }, StringSplitOptions.None)[1];
            results = results.Where(fil => fil.CustomerID.Contains(key) || fil.EmployeeID.ToString().Contains(key) || fil.Freight.ToString().Contains(key) || fil.OrderID.ToString().Contains(key) || fil.ShipCity.Contains(key) || fil.OrderDate.ToString().Contains(key));
        }
        else
            results = opts.Filter.ApplyTo(results, new ODataQuerySettings()).Cast<Orders>();
        }
     }
     if (opts.InlineCount != null)
        count = results.Count();
     if (opts.Skip != null)
        results = opts.Skip.ApplyTo(results, new ODataQuerySettings());
     if (opts.Top != null)
        results = opts.Top.ApplyTo(results, new ODataQuerySettings());
 }

Note
I no need to create EDM for using OData.
https://damienbod.com/2018/10/12/odata-with-asp-net-core/
Here, it is integrated with entity framework. But I no need to integrate. I need to use it's attribute only.
How to use it?
When I am running the API, I am getting an error like
InvalidOperationException: No service for type 'Microsoft.AspNet.OData.ODataOptions' has been registered.

Note
I need to use OData in web API without EDM.


text:
Q: How to merge two FMResultSet's based on a common column? I have two separate SQLite db files and am using FMDB to access them (cocoa wrapper for sqlite).
I retrieve two results - one from each DB, which is in two FMResultSet.
How do I use FMDB to merge and sort the two FMResultSets based on a single common column of the two resulting sets?

A: FMDB will not handle this for you since it is just a sqlite-Wrapper, and not manipulating, merging or sorting any data. A possibility would be to create a temporary database where you insert your FMResultSets.


text:
Q: Group list of numpy arrays based on shape. Pandas? I have some instances of a class containing numpy arrays.
import numpy as np
import os.path as osp
class Obj():
  def_init__(self, file):
     self.file = file
     self.data = np.fromfile(file)
     self.basename = osp.basename(file)

I have a list of such objects, which I want to group by shape. I can do that using sort:
obj_list = [obj1, obj2, ..., objn]
obj_list.sort(key=lambda obj: obj.data.shape)

Now I have a second list, say obj_list_2:
objects in obj_list_2 are initialized from different files but the resulting arrays have the same shape as in the first one (but not in the same order) and also the basenames are the same.
To clarify these are files loaded from different folders. In every folder I have the same files to which I applied different preprocessing)
If I sort them using the method shown above I can end up having
I want the two lists sorted based on shape and also aligned according to their basename
I though about doing first a sort based on the shape followed by one based on basename (of a function of it). Something like
obj_list.sort(key=lambda obj: obj.data.shape)
obj_list.sort(key=lambda obj: obj.basename)

However the second sort might screw the first one. They should be done together, somehow.
My final goal is to extract from the two lists the objects having the same shape and having the same basename
I tried with pandas but I'm not that familiar with it.
First I align them based on the basename, then I create a list of lists and pass it to pandas.
import pandas as pd
obj_list_of_list = [obj_list1, obj_list2]
obj_df = pd.DataFrame.from_records(obj_list_of_list)

What is missing is to group them by shape and extract the different groups.

A: You can create a dictionary mapping (file, shape) to a list of objects using collections.defaultdict:
from collections import defaultdict

d = defaultdict(list)

obj_list = [obj1, obj2, ..., objn]

for obj in obj_list:
    d[(obj.filename, obj.data.shape)].append(obj)

Similarly, you can sort by shape only if you wish:
d_shape = defaultdict(list)

for obj in obj_list:
    d_shape[obj.data.shape].append(obj)

You can then access unique shapes via d_shape.keys(), and access a list of objects given a shape via d_shape[some_shape]. The benefit of such a solution is your complexity is O(n), while sorting will have higher complexity, e.g. O(n log n).


text:
Q: I wanted to allow only 1 comma between 2 letters in PHP validation Hello I have a scenario that, in textbox I can enter string like
"1,2,3" this would be allowed.

but if someone enters,
"1,2,,3" this would not be allowed.

allowed multiple commas but not like above.
Thanks in advance

A: Try this reg-ex:
/^\d(?:,\d)*$/

Explanation:
/            # delimiter
  ^          # match the beginning of the string
  \d         # match a digit
    (?:      # open a non-capturing group
      ,      # match a comma
      \d     # match a digit
    )        # close the group
    *        # match the previous group zero or more times
  $          # match the end of the string
/            # delimiter

If you allow multi-digit numbers, then change \d to \d+.

A: Try this,
if(in_array("", explode(',',$str)))
{
    // validation fail
}

A: You can simply do a regex test to check. If the only thing you want to prevent is duplicate commas:
if (preg_match('/,,/', $myString)) {
    // not allowed... do something about it
}

If you want to limit it to only a pattern of numbers, separated by commas, swap the regex pattern for '/^([0-9]+,?)+$/', which only 1 or more numbers, optionally followed by a decimal, with that pattern repeated any number of times (but must have at least one number). Also, flip the conditional around, so:
if (!preg_match('/^([0-9]+,?)+$/', $myString)) {
    // not allowed... do something about it
}

If you want something a little simpler, doing this will also solve it (and be a little more efficient, if all you want is to test for multiple commas together):
if (strpos($myString, ',,') !== false) {
    // not allowed... do something about it
}

A: Try This:
if (strpos($input_string,',,') == true) {
    echo 'Invalid string';
}

A: You can detect this using (preg_match will work too of course):
if(strpos($your_string, ',,') !== false) {
   echo "Invalid"
}

Do you also need to detect leading or trailing commas?
Also keep in mind if validation is not really necessary you can simply "fix" the input by using explode and filtering out empty string elements, and then implode array:
$your_string = implode(',', array_filter(explode(',', $your_string), function ($i) {
    return $i !== '';
}));

A: use the strpos() function for your above requirement
 if (strpos($youstring,',,') == false) {
        echo 'String not found';
    }
    else
    {
        echo 'String is found';
    }

A: You can use stristr function to fix this
if(stristr ($Array,',,'))
echo 'Flase';
else
// do something


text:
Q: React get selected value from child component combobox Calling the child component, comboBox.
I am new in React and trying to save data from a child component but I am not receiving this value at the Parent component. I tryed some approaches with function at both components, but I just saw some examples using classes with 'this.[FUNCTION]' and I am not using function in this following code.
export default function PostApartment() {
  const [apartment_id, setApartmentId] = useState('');
  const [apartment_floor, setApartmentFloor] = useState('');
  const [apartment_size, setApartmentSize] = useState('');
  const [apartment_data, setApartmentData] = useState('');
  const [tower_data, setTowerData] = useState('');
  const classes = useStyles();

  const urlSearchApartment = 'http://localhost:' + config.port + '/apartment';

  const handleClick = (e) => setTowerData(e.target.value);
  console.log('tower_data - definition: ', tower_data);

  useEffect(() => {
    axios
      .get(`${urlSearchApartment}/`, {
        port: config.port,
      })
      .then((res) => {
        setApartmentData(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, [urlSearchApartment]);

  useEffect(() => {
    axios
      .get(urlSearchTower, {
        port: config.port,
      })
      .then((res) => {
        setTowerData(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }, []);

  return (

        <Typography className={classes.marginAlignment} variant='h4'>
          Cadastrar a localização e tamanho dos apartamentos
        </Typography>
        <Typography
          className={classes.marginAlignment}
          color='textSecondary'
          variant='body2'
        >
          O objetivo organizar a destribuição dos apartamentos e o tamanho, para
          poder organizar as informações do condomínio.
        </Typography>
        <Divider variant='middle' />

        <form>
          <FormControl>
            <Grid
              container
              spacing={0}
              direction='row'
              alignItems='flex-end'
              className={classes.marginAlignment}
            >

              {apartment_data ? (
                <ComboBox
                  field='tower_id'
                  data={tower_data}
                  description='Número do bloco'
                  onChange={handleClick}
                />
              ) : (
                ''
              )}
              <TextField
                required
                className={classes.marginRight}
                id='aparmentId'
                name='aparmentId'
                label='Número do apartamento'
                type='text'
                onChange={(e) => setApartmentId(e.target.value)}
                helperText='Identificador do apartamento'
              />
              <TextField
                className={(classes.marginRight, classes.marginAlignment)}
                id='apartmentFloor'
                name='apartmentFloor'
                label='Andar do apartamento'
                type='text'
                onChange={(e) => setApartmentFloor(e.target.value)}
                helperText='Exemplo:Informar o andar do apartamento'
              />

                {apartment_data ? (
                  <ComboBox
                    field='apartment_size'
                    data={apartment_data}
                    description='Tamanho do apartamento'
                    onClick={(e) => setApartmentSize(e.target.value)}
                  />
                ) : (
                  ''
                )}

                {apartment_data ? (
                  <ComboBox
                    field='apartment_parking_id'
                    data={apartment_data}
                    description='Número da vaga que o apartamento utiliza'
                  />
                ) : (
                  ''
                )}

            </Grid>
            <Grid container spacing={0} direction='row'>
              <Router forceRefresh={true}>
                <Switch>
                  <Route>
                    <Link to='/apartment'>
                      <Grid
                        item
                        xs={12}
                        sm={6}
                        className={classes.marginAlignment}
                      >
                        <Button
                          type='submit'
                          variant='contained'
                          color='primary'
                          size='large'
                          onClick={() => {
                            axios
                              .post(
                                `http://${config.host}:${config.port}/apartment`,
                                {
                                  apartment_id: apartment_id,
                                  apartment_block_id: tower_data,
                                  apartment_block_name:
                                    apartment_data.apartment_block_name,
                                  apartment_floor: apartment_floor,
                                  apartment_size: apartment_size,
                                  apartment_parking_id:
                                    apartment_data.apartment_parking_id,
                                },
                              )
                              .then(function (response) {
                                console.log(response);
                              })
                              .catch(function (error) {
                                console.log(error);
                              });
                          }}
                        >
                          Cadastrar
                        </Button>
                      </Grid>
                    </Link>

                    <Grid
                      item
                      xs={12}
                      sm={6}
                      className={classes.marginAlignment}
                    >
                      <Button
                        variant='contained'
                        color='secondary'
                        size='large'
                      >
                        Sair
                      </Button>
                    </Grid>
                  </Route>
                </Switch>
              </Router>
            </Grid>
          </FormControl>
        </form>

  );
}

The child component structure.
import React, { useState } from 'react';
import FormHelperText from '@material-ui/core/FormHelperText';
import { makeStyles } from '@material-ui/core/styles';

export default function ComboBox(props) {
  const classes = useStyles();

  function renderOption() {
    return props.data
      ? props.data.map((dataDescription, key) => {
          return <option key={key}>{dataDescription[props.field]}</option>;
        })
      : '';
  }
  const [selectedValue, setSelectedValue] = useState('');
  const handleClick = (e) => setSelectedValue(e.target.value);
  console.log('selectedValue: ', selectedValue);

  return (

        <select className={classes.input}>
          <option value=''></option>
          {renderOption()}
        </select>

      <FormHelperText>{props.description}</FormHelperText>

  );
}

I can find the selected value, but I would like to manipulate this value at the Parent component, to send all the payload to the API.
Can someone help on it and suggest more architectural approach for this code?

A: **
Parent component
**
I am passing the onChange event to the child component.
<ComboBox
 field='apartment_size'
 data={apartment_data}
 description='Tamanho do apartamento'
 onChange={(value) => setApartmentSize(value)}
/>

**
Child component (ComboBox)
**
I have included the props.onChange at the component

 props.onChange(event.target.value)}>

The Parent component receive the event and set it to a state.


text:
Q: Sitecore, How do you add a link or image map to the home slides? my company has this project, the digital media specialist gave me a design which has 4 other pictures on the main slide. I have use the home slider group and create new item for it.
In the home slider template, I can enter some text and it will float over the slide (in short description), but I would like to know how to either make a image maps for these 4 pictures or give a link when they click on the slide?
I am enable to either disable the floating text box and give different css style to it.

A: Sitecore doesn't have a 'slider' control, so this is probably something the original developers designed and developed.
Unfortunately for you, it doesn't sound like the implementation meets your new business requirements.  I believe you'd have to update your code in order to accomplish what you're trying to do via the Content or Page Editor.


text:
Q: split the arrays and get the column value from in rails view? I have the following array list in my view. How can I use the array each loop and get the values from it?
  [#<Order::List code: 1511, Reference: "FRIA004", valuation: nil, full_Address: "1, abc road, xyz", reason_available: "Y", list: "1 : Meter cupboard generic throughout - Very low">,
     #<Order::List code: 1512, Reference: "FRIA005", valuation: nil, full_Address: "2, abc road, xyz", reason_available: "Y", list: "2 : Meter cupboard generic throughout - Very high">,
     #<Order::List code: 1513, Reference: "FRIA006", valuation: nil, full_Address: "3, abc road, xyz", reason_available: "Y", list: "15 : Meter cupboard generic throughout - Low">,
     #<Order::List code: 1514, Reference: "FRIA007", valuation: nil, full_Address: "6, abc road, xyz", reason_available: "Y", list: "16 : Meter cupboard generic throughout - High">]

Expected output:
full_address
reason_available
list

A: Lets your array
@orders = [#<Order::List code: 1511, Reference: "FRIA004", valuation: nil, full_Address: "1, abc road, xyz", reason_available: "Y", list: "1 : Meter cupboard generic throughout - Very low">,
     #<Order::List code: 1512, Reference: "FRIA005", valuation: nil, full_Address: "2, abc road, xyz", reason_available: "Y", list: "2 : Meter cupboard generic throughout - Very high">,
     #<Order::List code: 1513, Reference: "FRIA006", valuation: nil, full_Address: "3, abc road, xyz", reason_available: "Y", list: "15 : Meter cupboard generic throughout - Low">,
     #<Order::List code: 1514, Reference: "FRIA007", valuation: nil, full_Address: "6, abc road, xyz", reason_available: "Y", list: "16 : Meter cupboard generic throughout - High">]

in view

     <% @orders.each do |order| %>

<%= order.full_Address %>

<%= order.reason_available %>

    <% end %>


text:
Q: Install android platform on cordova I started using PhoneGap and I got the following error when installing the android platform:
C: \ PhoneGap \ hello> cordova platform add android
[Error: An error occured falling on android establishment of sub-project. The specified access path was not found.]
somebody can give me help?? I have an windows 8 OS.

A: Please verify that you have java in your Environment Variable PATH. This causes this issue.


text:
Q: Is there are any implementations of stopwatch in TypeScript? I would like to run performance measurement for some critical functions on the website written on TypeScript.  I'm wondering if there is any implementation of stopwatch similar to .NET System.Diagnostics.Stopwatch class in TypeScript?

A: I have a simple implementation here:
/**
 * Simple timer
 */
export function timer() {
    let timeStart = new Date().getTime();
    return {
        /** <integer>s e.g 2s etc. */
        get seconds() {
            const seconds = Math.ceil((new Date().getTime() - timeStart) / 1000) + 's';
            return seconds;
        },
        /** Milliseconds e.g. 2000ms etc. */
        get ms() {
            const ms = (new Date().getTime() - timeStart) + 'ms';
            return ms;
        }
    }
}

Usage
const howLong = timer();
// do some stuff
console.log(howLong.ms);

There are lots of other implementations out there as well as the built in console.time function you can look at.

A: Building off of basarat's answer above, this is already built in to console.
console.time('myTask');
// code to time here
console.timeLog('myTask');
console.timeEnd('myTask');

A: This stopwatch is written in typescript and comes with type definitions.
https://github.com/vcfvct/stopwatch-node

A: Since the OP asked specifically for something similar to .NET's Stopwatch, the @tsdotnet/stopwatch package might be a good option.
First, install package in your npm project: npm i @tsdotnet/stopwatch
Code example:
import Stopwatch from "@tsdotnet/stopwatch"

(async () => {
const stopwatch = Stopwatch.startNew();

    // Simulates a delay of 1000 milliseconds.
    await new Promise(r => setTimeout(r, 1000));

    console.log(stopwatch.elapsedMilliseconds);
})();

Please, notice that your tsconfig.json needs to be targeting at least es2015 due to the use of promises in this example. This is not a requirement because of @tsdotnet/stopwatch.


text:
Q: With an address, how to get the store opening hours at that address in Google Maps? I can't get Google Maps Autocomplete to return the correct place_id for an address I am trying. For example, when I select "298 W McKinley Ave, Sunnyvale, CA 94086, United States" in Autocomplete service, it returns place_id: ChIJtc3P4122j4ARl7eqhmjB3ow, but no store hours in the results.
var place = new google.maps.places.Autocomplete(element[0], {});
google.maps.event.addListener(place, 'place_changed', function() {
   console.log("place: " + JSON.stringify(place.getPlace()));
});

But if I query PlacesService with place_id: ChIJqUSz4l22j4ARRjulQFPISrw, it returns the same address, with store hours this time.
 var request = {
   placeId: 'ChIJqUSz4l22j4ARRjulQFPISrw'
};

var service = new google.maps.places.PlacesService(map);

service.getDetails(request, function(place, status) {
  console.log("place details: " + JSON.stringify(place));
});

Please see http://plnkr.co/edit/vEMO0ls4aIHLgAnGJg3g?p=preview.
Is there a way to get Autocomplete to return the place_id that corresponds to the store at that address? Or with an address, is there any way to get the place_id of the store at that address?


text:
Q: How to do conditional formatting in Google Sheets based off of Date? I am looking for a way to color rows based on date. My hope is that every other day will alternate colors.
For example, I would like all of the rows with the same date, January 1st, 2023, to be one color. Then all of the rows with the next day, January 2nd, 2023, to be another color. Then each day would alternate back and forth.

There is plenty of info on conditional formatting. Just couldn't find alternating colors that switch back and forth based on date. Any help would be much appreciated. Thank you!
To be more clear I am hoping that the entire row will alternate colors based on the date. Here is a better example:

A: Apply the desired conditional formatting to range A2:A with custom formula
=if(isblank(A2),,arrayformula(mod(countif(A$2:A2<>A$1:A1,"=true"),2)))=1

Regarding your edit, you can indeed apply the same format in column A to other columns by including those columns in the range of the conditional formatting rule. For example, replace A2:A with A2:B

It is easier to see why this works with some helper columns.
The above is equivalent to the followings.
In B2, put
=arrayformula(if(isblank(A2:A),,A:A<>A2:A))

In C2, put
=ArrayFormula(IF(isblank(B2:B),,mod(countIFs(B$2:B,"=true",row(B$2:B),"<="&ROW(B$2:B)),2)))

Apply the desired conditional formatting to range A2:A and use custom formula =C2=1.
And you will have the desired effect.

The helper column B simply checks if a date is different from the preceding row. If it is, we will mark it as TRUE.
Helper column C is a running sum of the number of TRUE values in column B. A running sum of TRUE values mark the number of distinct dates. With this particular running sum formula, a second helper column is needed because the syntax checker in Google Sheet considers A:A<A2:A of different length. And that's also why helper columns are needed with this particular formula.
We also wrap the running sum formula with mod(_,2) to divide the distinct dates into 2 groups. Now in column C, you will have label 1 and 0 for the alternating groups of dates in column A. Hence the custom formula =C2=1 for conditional formatting.
But to take a step back, custom formula in conditional formatting has implicit iterations built-in and produces a different formula for every cell in the range implicitly. That makes running sum a single formula on your end. That's how you can go from the helper columns to the simplified answer at the beginning.


text:
Q: JQuery Using Closest("element.class") I am trying to find the closest tr that also matches a specific class name. The selector returns no matches.  What am I not understanding?
For example:

  Category 1

    Item 1

    This is a description of category item 1

    <input type="text" name="c1_i1_input" id="c1_i1_input" class="category-item-input" />

    Item 2

    This is a description of category item 2

    <input type="text" name="c1_i2_input" id="c1_i2_input" class="category-item-input" />

A: Closest finds the closest ancestor element, not the nearest in the DOM.  In your case the tr containing the input does not have the class and so the selector fails.  You probably want to find the closest tr, then find the preceding previous sibling of that tr with the class.
$(this).closest('tr').prevAll('tr.category-item:last');


text:
Q: Probability involing percentages (Bernoulli?) Assume that about 56% of population belong to group type of O.
A) What is the probability that it will need to take a blood test from exactly three individuals in order to find a person with O-type blood?
B) What is the probability that it will need to take more than 4 blood tests?
My attempt of A):
n  = 3
k = ?
n-k = 3-?
p = 56% = 14/25
q = 1-p = 11/25
C(n,k)p^k * q^(n-k)
I am not sure how to use given information to solve this problem. Can you give me any hint please?

A: We want the probability that we try once, fail, try again, fail, try again, got it. So the probability is $(0.44)(0.44)(0.56)$.  .
For B), we want the probability that we fail $4$ times in a row. For that's exactly the situation in which we need more than $4$ trials.
Remark: It is best to get a handle on the problem, then use (if necessary) the appropriate formula.


text:
Q: Update fragment ui from broadcast receiver in MvvM architecture and Kotlin Being new to kotlin and mvvm architecture I wasted the past two days searching for an answer for this problem without any success. So I am searching for a clean solution to change the fragment ui (in my case it is just a textview) when the device is connected/disconnected in the internet. I am using the mvvm architecture and the android architecture component(viewmodels, livedata, data bindings ...). I have a base activity with a bottom navigation and multiple fragments.
I am trying to get the connectivity event from a custom broadcast receiver and I want somehow to pass that event in the viewmodel or my fragment.
My first thought was to use an interface. This interface is triggered by the onreceive of the broadcastreceiver and it is implemented in my fragment or viewmodel, so when the internet event happens, the textview is updated in my fragment. But I am not sure about how to use the interface in the broadcast receiver, or I don't know even if this is possible or a good practice.
what I did till now is create the broadcast receiver
class ConnectionStateObserver: BroadcastReceiver() {
    override fun onReceive(p0: Context?, p1: Intent?) {
       //somehow use the interface in here
    }
}

register/unregister it in my base activity
    override fun onResume() {
        super.onResume()
        val broadcastIntent = IntentFilter()
        broadcastIntent.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        registerReceiver(ConnectionStateObserver(), broadcastIntent)
    }
    override fun onPause() {
        super.onPause()
        unregisterReceiver(ConnectionStateObserver())
    }

(I know that ConnectivityManager.CONNECTIVITY_ACTION is deprecated but I couldn't find a better solution).
create an interface
interface ConnectionStatusChange{
    fun onChange()
}

and implement the interface in my Fragment
class myFragment : Fragment(), ConnectionStatusChange {
override fun onChange() {
        // do the ui changes here
    }
}

I would like to know if this approach is a good practice and how can I make it work. In the case that it is not possible to be done like that then please give me some suggestions (code always appreciated! =)). Also it would be good to have a modern, rather than a 5 years old solution. Thank you in advance.

A: Eventually I found a clean and modern solution like I wanted. The trick is to wrap the BroadcastReceiver in a LiveData. By using this pattern you can observe the connection LiveDada directly from your fragment and update the ui. Of Course it is also possible (like sergiy tikhonov mentioned) to have a companion object in the base activity with a LiveData that is getting updated from the BroadcastReceiver and you can observe it from the fragment, but I didn't like this approach.
So it works like this:
Create an enum with the states of the network.
enum class NetworkAvailability {
    UNKNOWN,
    CONNECTED,
    DISCONNECTED
}

Create the class that extends the LiveData. I am using the singleton pattern because I don't want multiple instances. I create a BroadcastReceiver instance and I register/unregister it in onActive and onInactive methods of the LiveData.
class ConnectionStateLiveData(val context: Context) : LiveData<NetworkAvailability>() {

    companion object {
        private lateinit var instance: ConnectionStateLiveData

        fun get(context: Context): ConnectionStateLiveData {
            instance = if (::instance.isInitialized){
                instance
            }else{
                ConnectionStateLiveData(context)
            }
            return instance
        }
    }

    private val connectivityBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            val connectivityManager =
                context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val netInfo = connectivityManager.activeNetworkInfo

            value = if (netInfo != null && netInfo.isConnected) {
                NetworkAvailability.CONNECTED
            } else {
                NetworkAvailability.DISCONNECTED
            }
        }
    }

    override fun onActive() {
        super.onActive()
        value = NetworkAvailability.UNKNOWN
        val broadcastIntent = IntentFilter()
        broadcastIntent.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
        context.registerReceiver(connectivityBroadcastReceiver, broadcastIntent)
    }

    override fun onInactive() {
        super.onInactive()
        context.unregisterReceiver(connectivityBroadcastReceiver)
    }
}

And finally I observe the LiveData in my fragment.
ConnectionStateLiveData.get(context).observe(viewLifecycleOwner, Observer {
                if (it == NetworkAvailability.CONNECTED) {
                    binding.noInternetTextView.visibility = View.GONE
                }
            })

A: *

*base/helper class

public class ReceiverLiveData<T> extends LiveData<T> {

    private final Context context;
    private final IntentFilter filter;
    private final BiFunction<Context, Intent, T> mapFunc;

    public ReceiverLiveData(Context context, IntentFilter filter, BiFunction<Context, Intent, T> mapFunc) {
        this.context = context;
        this.filter = filter;
        this.mapFunc = mapFunc;
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        context.unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    protected void onActive() {
        super.onActive();
        //initialize LiveData value
        mBroadcastReceiver.onReceive(context, null);
        context.registerReceiver(mBroadcastReceiver, filter);
    }

    final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            setValue(mapFunc.apply(context, intent));
        }
    };
}

*ViewModel class

    public static class ViewModel extends AndroidViewModel {
        public ViewModel(@NonNull Application application) {
            super(application);
        }

        public final LiveData<NetworkInfo> activeNetworkInfoLiveData = new ReceiverLiveData<>(getApplication(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION), (c, i) -> ((ConnectivityManager) c.getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo());

    }

*in databinding layout file

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="viewModel"
            type="com.XXXX.settingitemtest.MainActivity.ViewModel" />

    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text='@{viewModel.activeNetworkInfoLiveData.connected ? "Connected" : "Disconnected"}'/>

    </LinearLayout>
</layout>


text:
Q: Reg. Expression checks first letter of a string I would like to check if the first character of a string is a letter or not. My regular expression is:
 '/^([a-zA-Z.*])$/'

This is not working. What's wrong with it?

A: Try the following:
'/^[a-zA-Z].*$/'

which checks if the first letter is in the alphabet and allows any character after that.

A: Your expression does not need .* nor should it have the $
'/^([a-zA-Z])/'

In fact, if you don't need to know what this letter is, you could go even simpler:
'/^[a-zA-Z]/'

// These expressions are true
/^[a-zA-Z]/.test("Sample text")

var re = new RegExp('^[a-zA-Z]');
re.test('Sample text');

A: I was able to single out the first letter with this /^[a-zA-Z].*$/ from one of the above answers, but I didn't need the .\*$ so I had /^[A-J]/g (working on my own assignment hence a-j).


text:
Q: How to pass/make an object/variable accessible inside a callback function which is called by a third party library? How to make globalObject accessible by callbackFunction?
I am using a third party library library.h which has a method libraryFunction. The output of libraryFunction is a libraryFunctionOutput which is passed into the callback function callbackFunction.
How to pass another object (e.g. globalObject) for use inside the callback function callbackFunction?
Unfortunately the third party library is compiled so I cannot make any changes to it.
#include <stdio.h>
#include "library.h"

int callbackFunction(int libraryFunctionOutput):
    printf("%s, %d", libraryFunctionOutput, globalObject);
    return 1;

int main(int argc, char* argv[])
{
   int globalObject = 0;
   libraryFunction(callbackFunction);
}

In the documentation, the function is shown as:
int __stdcall libraryFunction(const char*    filename,
                              unsigned int   flags,
                              int            userID,
                              MathrelCallback callbackFunction);

The MathrelCallback struct is defined as the following:
struct MathrelCallback {MathrelHeader header;
                        MathrelInfo   data;
                        unsigned int Type;
};

A: If the library really takes a function pointer (not a generalized Callable like std::function) and does not offer the ability to pass a context or user pointer to your callback, you have to make your global object global (with all its drawbacks):
#include <stdio.h>
#include "library.h"

static int globalObject = 0;

int callbackFunction(int libraryFunctionOutput)
{
    printf("%s, %d", libraryFunctionOutput, globalObject);
    return 1;
}

int main(int argc, char* argv[])
{
   libraryFunction(callbackFunction);
}


text:
Q: Calculating line integral $\int_{\gamma}K(x) dx$ $G=\{(x,y,z)^t \in \mathbb{R}^3: y>0,z>0\}$
$K\Big((x,y,z)^t\Big)= \Big(\ln(zy),\frac{x}{y},\beta \frac{x}{z}\Big)$
I want to calculate the line integral $$\int_{\gamma}K(x) dx$$ for $\beta=1$ and $\beta=2$ for $\gamma$ going from $(0,1,1)^t$ directly to $(x_0,y_0,z_0)^t$ in $G$.
For $\beta=1$ it's pretty easy because I can use the indefinite integral $F:=x \ln(zy)$ so $\int_{\gamma}K(x) dx = F\Big((x_0,y_0,z_0)^t\Big)-F\Big((0,1,1)^t\Big)=x_0\ln(z_0y_0)$.
Now, for $\beta=2$ there is no such $F$. But apparently one can caluclate the integral using:
$\mathrm {integral(\beta=1)}+\mathrm{what's\ missing}$
Can someone explain to me how this is done? So how do I calculate the line integral for $\beta=2$?
Thanks!

A: I will write all vectors as row vectors. Let
$$
K_1(x)=\Bigl(\ln(z\,y),\frac{x}{y},\frac{x}{z}\Bigr),\quad K_2(x)=\Bigl(0,0,(\beta-1)\frac{x}{z}\Bigr).
$$
Then
$$
\int_\gamma K(x)\,dx=\int_\gamma K_1(x)\,dx+\int_\gamma K_2(x)\,dx.
$$
The first one you know how to do. The second one can be computed explicitly using the definition of line integral


text:
Q: view sets throwing pagenotfound! found Django DRF Getting page not found error, trying DRF, I am trying these viewsets but so far error as mentioned thanks in advance!
urlpatterns = [
    path('',include(router.urls)),
    path('organisation_list/',OrganisationList.as_view()),
]

Routes
router = DefaultRouter()
router.register(r'list_organisation',OrganisationViewSet)

class OrganisationViewSet(ViewSet):

    permission_classes = []
    authentication_classes = []

    queryset = Organisation.objects.all()

    @action(detail=False, methods=['get'])
    def list_organisations(self,request,*args,**kwargs):
        print('working')
        data = self.queryset
        serializer = OrganisationSerializer(data,many=True)
        return Response(serializer.data,status=200)

error
 "GET /list_organisation/ HTTP/1.1" 404 3548

A: Since the view list_organisations was defined as a custom action, the actual url for it is:
list_organisation/list_organisations

If you want list_organisation/, just change the view to list:
class OrganisationViewSet(ViewSet):
    ...
    def list(self, request, *args, **kwargs):
        print('working')
        data = self.queryset
        serializer = OrganisationSerializer(data,many=True)
        return Response(serializer.data,status=200)


text:
Q: Splitting field of $\sqrt{\vphantom{\sum}1+{\sqrt2}}$ and Galois group Let $\alpha= \sqrt{\vphantom{\sum}1+{\sqrt2}}$.
(a) Let $p(x)$ be the minimal polynomial of $\alpha$. Find $p(x)$. Let K be the splitting field of $p(x)$
(b)Let $E= \mathbb{Q}(i, \sqrt2)$ Show that $E \subseteq K$
(c) Show that $K=E\sqrt{\vphantom{\sum}1+{\sqrt2}}$
(d) Show that there exists $j:E \longrightarrow E$ such that $j(i)=-i$ and $j(\sqrt2)=-(\sqrt2)$
(e) Show that there exists $f:K \longrightarrow K$ which extends $j$ such that $f(\sqrt{\vphantom{\sum}1+{\sqrt2}})=\sqrt{\vphantom{\sum}1-{\sqrt2}}$
(f)Show that $f$ has order 4
(g) Let $g \in$ Gal$(K/ \mathbb{Q})$ be a complex conjugation. Then show that $fg=gf^3$
(h) Conclude that Gal $(K/ \mathbb{Q})$ is isomorphic to $D_8$
Attempt
Finding the minimal polynomial is the only easy part here $(x^2 -1)^2 -2= x^4 -2x^2 -1$
Also I calculated the splitting field which I got to be the Galois closure as well which is done by computing
$x=-i\sqrt{\vphantom{\sum}-1+{\sqrt2}}$
$x=i\sqrt{\vphantom{\sum}-1+{\sqrt2}}$
$x=-\sqrt{\vphantom{\sum}1+{\sqrt2}}$
$x=\sqrt{\vphantom{\sum}1+{\sqrt2}}$
So we just get $\mathbb{Q}(i,\sqrt{\vphantom{\sum}1+{\sqrt2}})$
(h) I have no idea how to proceed but I have found the following facts in the dummit and foote
1) The Galois group of the splitting field of an irreducible polynomial f acts transitively on the roots of f
2)The order of the Galois group of the splitting field of an irreducible polynomial f is divisible by degree of f
Not sure how I'm supposed to use these hints
(b) Look at this it's obvious to see that the 'elements' that K and E have in common is $i$ but what is the mechanism for showing such? I'm not sure how to proceed here.
(c) For this part is it okay to just take
 $\mathbb{Q}(i,\sqrt{\vphantom{\sum}1+{\sqrt2}})$ = $\mathbb{Q}(i,\sqrt2)$  x $\sqrt{\vphantom{\sum}1+{\sqrt2}})$ and proceed by normal multiplication?
(f) It's not hard to see from the splitting field $x^4 -2x^2 -1$ that it is irreducible over $\mathbb{Q}$ and the degree of the extension is 4.
for (d) and (e) i'm drawing a blank but i'm thinking they are related and somehow the minimal polynomial of $\sqrt{\vphantom{\sum}1+{\sqrt2}})$ and $\sqrt{\vphantom{\sum}1-{\sqrt2}})$ are some how related by the function $j$ but I just can't quite see it.
Please note I don't have much experience in this field and I'm currently using the dummit and foote.
Can anyone assist me.

A: (b) take products and sums of the generators in $K$ to get elements in $E$. E.g $\sqrt{1 + \sqrt{2}}$ is contained in $K$, so $1 + \sqrt{2}$ is. Similarly $1 - \sqrt{2}$ is. Subtracting these two elements $1$ and $\sqrt{2}$ are both contained in $K$.
(c)  When you say $E \sqrt{1 + \sqrt{2}}$ you must mean $L = E ( \sqrt{ 1 + \sqrt{2}})$. Since $E \subset K$, we can use degrees here to show they are the same (if a finite field extension is contained in another finite field extension of the same degree then they are the same. $L/E$ has degree $2$ and $E/\mathbb{Q}$ has degree $4$, as $E / \mathbb{Q}(\sqrt{2})$ has degree $2$ and $\mathbb{Q}(\sqrt{2}) / \mathbb{Q}$ has degree $2$. Now show that $K$ has degree $8$ using the tower $K / \mathbb{Q}(\sqrt{1 + \sqrt{2}})/\mathbb{Q}(\sqrt{2}) / \mathbb{Q}$.
(d) For a simple extension $L(a)/L$ of fields, with $a$ having minimal polynomial $f(x) \in L[x]$, there is always an automorphism permuting any two roots of $f$ contained in $L[x]$. To get one of the desired maps in the problem, take the map $\mathbb{Q}(\sqrt{2}) \rightarrow \mathbb{Q}(\sqrt{2})$ sending the root $\sqrt{2}$ of the minimal polynomial $x^2 - 2$ to the other root $-\sqrt{2}$ of the minimal polynoimal. This gives an automorphism of $\mathbb{Q}(\sqrt{2})$. This gives a map $\mathbb{Q}(\sqrt{2}) \rightarrow \mathbb{Q}(\sqrt{2}, i)$, which extends to a map $\mathbb{Q}(\sqrt{2}, i)$ sending $i$ to $i$. The reason this extension exists is that $\mathbb{Q}(\sqrt{2}, i) / \mathbb{Q}(\sqrt{2})$ is a simple extension generated by $i$, with minimal polynomial $x^2 + 1$, and $x^2 + 1$ has a root in the target of the embedding $\mathbb{Q}(\sqrt{2}) \rightarrow \mathbb{Q}(\sqrt{2}, i)$.
So the two general facts we used were

*

*Let $L(a)/L$ be a finite simple extension of fields. For any root $b$ of the minimal polynomial $f$ in $L(a) / L$, there is an $L$-automorphism of $L(a)$ sending $a$ to $b$.

*Let $L(a)$ be a finite simple extension of fields. If $M/L$ contains a root $b$ of the minimal polynoimal $f(x)$ of $a$ in $L[x]$, then there is an embedding $L(a) \rightarrow M$ sending $a$ to $b$.
(e) this uses the same methods discussed in the last one. Here $K/E$ is a simple extension with $a = \sqrt{1 + \sqrt{2}}$ its generator. To proceed, calculate the minimal polynomial $f(x)$ of $a$ over $E$. There is an $E$-automorphism of $K$ sending $a$ to the other root of $f(x)$ in $K$.
(f) you got it!
(g) $fg$ and $gf^3$ are determined by what they do to the roots of certain polynomials. This is nice for us, since we have identified finitely many of these, and automorphisms send roots to other roots. So it is simply a matter of evaluating what they do to the roots. E.g. $f g ( \sqrt{1 + \sqrt{2} } ) = f ( \sqrt{1 + \sqrt{2}} ) = \sqrt{1 - \sqrt{2}}$. Do all the calculations of this kind, observe that they are the same for $fg$ and $gf^3$, and you'll be done.
When we found roots of the minimal polynomials and observed how each automorphism permutes them, we have really reduced an "intractible" question of automorphisms of fields to a tractible question of a finite group acting on the roots; automorphisms are determined by how they act on the roots of certain polynomials, and they permute those roots. In this way, instead of automorphisms acting on a field we have automorphisms acting on a finite set. The second should seem a lot easier to answer, since it is about something finite- in the worst case, we have a brute force approach.
(h) This is potentially the most tricky part, but it's also where all this computation has been leading us. $D_8$ is given by generators and relations as $\langle x, y  | x^4, y^2, xy = yx^3 \rangle$. To give an isomorphism, let's start with a map from the free group $\langle x, y \rangle$ to the galois group in question sending $x$ to $f$ and $y$ to $g$. We must show a few things to establish an isomorphism:

*

*$x^4$ is sent to $\text{Id}$, and so are $y^2$ and $x^{-3}y^{-1}xy$. You showed the last one already, but the first two are not so different!

*All automorphisms in the galois group are some combination of $f$ and $g$.

*The order of the galois group is $8$.
I have to go for now, but I hope this is enough.


text:
Q: Testing controllers = integration test? once I asked a similar question before. We have a forum system:
class ForumThread
{
    public function delete ($threadId)
    {
        Container::getPost()->deletePostsByThreadId ($threadId);
        Container::getSql()->sql ('DELETE FROM threads WHERE ID = '.$threadId);
    }
}

class Post
{
    public function deletePostsByThreadId ($threadId)
    {
        Container::getSql()->sql ('DELETE FROM posts WHERE THREAD_ID = '.$threadId);
    }
}

as you can see, it gets the post and thread objects from a container, it can be replaced, mocked, etc. When unit-testing, I felt something missing: so, its ok to test if a forum thread is actually deleted - so post too. This is what unittesting for - but do they work together well? If they works OK standalone, its not guaranted that they work together well. If two lego elements are well made, they might not fit to each other.
Here enter the integration test:
class Controller
{
    function controllerDelete()
    {
        Container::getForumThread()->delete ($_POST['ID']);
    }
}

I guess here I could check both SQL tables. Is my theory OK? Because if controller testing was unittest-like, it wouldnt really make sense, since controllers are typically the shortest classes (once I made a test ForumThread::delete, the test controller::controllerDelete would be the same

A: As you already know Unit testing is mostly concentrated on smallest testable part of an application. So if they pass – your unit level is OK. Integration testing is yet another thing – modules combined and tested as a group. So as bottom line to:

Is my theory OK?

Yes. What you need to cover in controller testing on this level is functional, performance, and reliability you've already placed as per application design and requirements.


text:
Q: Graphic app in C++ and code in C **Qt Programming** i have an application to realise with sockets in c, and i'm confortable with C++ and Qt, is it possible to do both C and C++ on Qt.
there is a sample from the code is on C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 9600

int main(int argc, char *argv[]){
    int sock_cnx; /* Socket pour ouverture de connexion */

    struct sockaddr_in serveraddr;
    struct sockaddr_in clientaddr;

    int newfd;
    char buf[1024];
    int nbytes;
    int addrlen;
    int i, j;

    /* Ensemble des descripteurs qu'on souhaite surveiller en lecture */
    fd_set surveil_fds;

    /* Ensemble des descripteurs qu'on va utiliser dans SELECT */
    fd_set read_fds;

    /* Memorise le plus grand descripteur : a utiliser dans SELECT*/
    int fdmax;

    addrlen = sizeof(clientaddr);

    /* Ouverture de la socket du serveur */
    if ((sock_cnx = socket(AF_INET,SOCK_DGRAM,0)) == -1){
        perror("Erreur socket");
        exit(1);
    }

    bzero(&serveraddr, sizeof(serveraddr));

    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(PORT);
    serveraddr.sin_addr.s_addr = htonl (INADDR_ANY);

    bzero(&(serveraddr.sin_zero), 8);

    /* Bind */
    if (bind(sock_cnx, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1) {
        perror("Erreur Bind");
        exit(1);
    }
    ........
    return 0;
}

i already created my interface for the app on Qt.

A: Within you Qt/C++ application, you can include you C-file as follows:
extern "C" {
#include "myCHeaderFile.h
} /* extern "C" */

You can than simply access the C-functions within your C++/Qt file.


text:
Q: iOS7: How to wait for requestInterstitialAdPresentation to finish I have implemented a method on my view controller (via a protocol) which my game engine calls to present Interstitial advertisements.
I want to prevent the control loop from returning to the caller while a full screen advertisement is in play, and not affect subsequent animations of SKScene objects happening while the ad cleans up and delays processing.
I have achieved this with the following code, which checks if an advert will be presented, and blocks the current thread until the advert is no longer being shown, and the view isn't unloading for that ad. (Without the dismiss check, my transitions appeared to be effected too early).
I know that the iAD model is simpler in iOS7, no need to implement delegates etc. But what is the right way of waiting for interstitial ads to complete in iOS7. (Note, I'm using SpriteKit, not storyboarding). Do I have to revert to using iOS6 or less style delegates?
-(void)presentFullScreenAd
{
    if( [self requestInterstitialAdPresentation] )
    {
        while( self.isPresentingFullScreenAd  || self.isBeingDismissed )
        {
            // wait till we have finished before continuing
            [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.5]];
        }
    }
}

A: The code above does not work on iOS8 (tested on iPhone 4s in simulator), it will loop infinitely. So I've had to change it.
This isn't perfect, there is still a bit of jerkiness between transitions but is less hacky.
First, in the view controller, create a helper method to pause and un-pause the current SKView
-(void)pauseCurrentSKView:(bool)paused
{
    if( [self.view isKindOfClass:[SKView class] ] )
    {
        SKView* pView = (SKView*)self.view;
        pView.paused = paused;
    }
}

then make your full screen ad method pause the view immediately but un-pause if adverts didn't show. You'll un-pause later.
-(void)presentFullScreenAd
{
    // pause ASAP - requestInterstitialAdPresentation may take some time
    // so you need to pause before your transitions kick in.
    [self pauseCurrentSKView:YES];

    if( [self requestInterstitialAdPresentation]==NO )
    {
        [self pauseCurrentSKView:NO];
    }
}

Then handle when your view comes back into play - and resume animations.
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if( self.isPresentingFullScreenAd )
    {
        // we are about to stop presenting full screen ads
        [self pauseCurrentSKView:NO];
    }
    else
    {
        // we are presenting the normal view or the full screen ad
    }
}

The key thing is to make sure after you call the presentFullScreenAd method, that you put your code in follow on block actions against nodes in the view, so that you don't have to worry about 'when the ads are gone, do this bit of code'.
If anyone has any refinements - please ad.
I've purposefully not included extra code where I only launch fullscreen adverts every three minutes - easy to do.


text:
Q: Transpose pivot table I have this pivot table df_pivot:
                          sum
                       points
team        position
Liverpool    fwd       66.1
             gkp       8.6
             mid       33.9
             def       45.2

How do I transpose the table in order to get:
team       fwd   gkp  mid   def
Liverpool  66.1  8.6  33.9  45.2


text:
Q: WPF in a browser and printing Can WPF be hosted in a web browser?  If so how?  (I think it can as I have seen some examples of it.)
While hosted in the web browser what printing support does it have?
What are the drawbacks to using WPF in a browser?
My company is looking for a rich web app platform.  They will not choose Silverlight because it ignores any printing needs (at least as far as I understand).  Right now a solution from Adobe is in the lead because it supports printing.
Most (if not all) of the apps written for browsers will be used internally by my company (ie we control the computers and browsers).  (We want to use browsers for easy of deployment.)

A: Have you checked out XBAP (Xaml Browser APplications)?
The major drawbacks I am aware of concern security.  When some coworkers of mine were developing an XBAP product, they often ran into problems with security, as the XBAP model is pretty strict.
I can't answer about printing, but I'd tend to think that might be a problem with the security considerations.
Hope I was able to help.

A: If the apps are solely internal and you control the target platform; and the reason for choosing to host your apps in the browser is 'ease of deployment', I would seriously consider writing Full Trust applications in WPF, and deploying them with ClickOnce... Your users would simply have a shortcut on their desktops that would check a server to see if their version of the app is current, and download the newest version if not.
You get all the benefits of the full WPF platform (greater feature-set than Silverlight), and do not need to conform to the Partial-Trust restrictions of XBAP (although you will need to configure the ClickOnce server to allow for Trusted Application Deployment)

A: No.  That's what Silverlight is for right now and yes there are printing limitations.  However, printing anything using a web app is not straight forward.

A: I would suggest Silverlight/Flex solution for web based app and for printing need the best way to do is use iTextSharp library and generate PDF for your reports or printing need, which can be fetched from a URL. PDF is a very standard and adobe reader will always print it right, printing will not be a problem, we went through lot of options and it requires reinventing wheel where else generating PDF through iTextSharp is very easy as creating normal html in javascript way.


text:
Q: Is this correct design approach for splitting logic between activity and other class I have an android/programming design question. For some reason I feel my design is awkward but if it is correct (no issues) then  I would like a confirmation so I know I am on the right path.
Often I come across where I have Activity (lets say it has map). I don't want to put everything in this class ( ie map  work). I usually create the activity class and another class (say map worker). I pass the activity as a reference to the map worker class, so that map worker class can method in there. Something like that
public class MainActivity extends Activity{

    public void onCreate(){

        MapWorker myWorker = new MapWorker(this);
    }

    public renderUpdate  (Marker m){

        mapView.addMarker(m)
    }
}

The map worker class is as follows
public class MapWorker {

    MainActivity act;

    public void MapWorker(MainActivity act){

        this.act = act;
    }

    public doWork(){

        //do lots of work
        .
        .
        .
        act.renderUpdate(marker)
    }
}

These classes have two way linking as you see. Is this ok or should I do it differently?and Why?
Thank you so much


text:
Q: Visual studio : unsupported URL protocol Good Morning,
I'm having an issue with my git repository in visual studio (2013), when I try to publish a branch. it says "unsupported URL protocol", the url being :

I can publish the branch correctly in my computer, however it doesn't work on my intern's computer, despite using the exact same git config file in the project :

the remote repository config is like this :

Researches I made told me that it might be a TLS 1.2 problem, but even enabling it in VS command prompt doesn't fix the issue, forcing to SSH, HTTPS or HTTP protocol won't fix it either, according full access on the repository doesn't help too.
What could I do to fix that ?
EDIT : when I try to pull directly from a third party git client, it says that my repository isn't a git repository (despite being one), and that it might have to be becasue of right access (it's not, I added my intern to domain admins so he can access everything)

A: Okay, it was a permission problem finally, but either GIT and visual studio was clear about that when trying to PULL, in Visual Studio, it was an unsupported URL error, with GIT client too and suggested that it was a permission problem (but without saying that it's one directly, which is odd).


text:
Q: How to get all user details in rest api wordpress I am trying to get all the user details from wordpress 4.7 through the rest api - wp-json/wp/v2/users.
Currently I am seeing a lot of fields for the user object (close to 100 fields, amr user plugin installed) in the wordpress site, but the api is returning very few fields.
How can I get all the fields of user object in the rest api, should I install any other plugin for the same?

A: You are only receiving the user fields which are stored in the wp_users table, but not the fields which are stored in the wp_usermeta table.
In order to get all information about a user, you have to get the user meta fields of this user from the REST API.
How to get user meta fields from the REST API:
Look into register_rest_field() to register meta with the rest api.
add_action( 'rest_api_init', 'adding_user_meta_rest' );

function adding_user_meta_rest() {
   register_rest_field( 'user',
                        'collapsed_widgets',
                         array(
                           'get_callback'      => 'user_meta_callback',
                           'update_callback'   => null,
                           'schema'            => null,
                            )
                      );
}

And then put your get_user_meta bit in the callback.
function user_meta_callback( $user, $field_name, $request) {
       return get_user_meta( $user[ 'id' ], $field_name, true );
   }
The WP_REST_Meta_Fields class may provide more useful insight as well.
The later part of this answer I have found in this answer on WordPress Stackexchange: https://wordpress.stackexchange.com/questions/270154/getting-user-meta-data-from-wp-rest-api


text:
Q: How to add node_modules folder in a global npm package? I have created an npm package which has a lot of dependencies, but when I test my app with npm install -g ./ the app gets added in the global npm directory but without the node-modules folder. Thus when the app is run through the terminal, although the app is recognized, it doesn't work because none of the dependency is installed.
How can I make sure to make app installs node-modules when its published in the npm registry
If I install the node-modules independently on the project folder by doing npm install, the app works. I don't want the user to install the packages independently. What I am expecting is the full installation of the app and the required dependencies only with npm install -g my_package
I have also used yarn as the package manager, and the dependencies are listed under "dependencies" in package.json file. The "bin" field in the package.json file points to our app, which can also be run as node bin/index.js. This app is also recognized by the terminal, the only problem is the dependencies

A: I think you can use this command npm install --save then it might work.


text:
Q: Can't fetch the data in MVC by ajax I want to fetch data from a database in ASP.NET MVC with Ajax.
This is my controller:
public JsonResult EditCustomer(int Id)
{
        Customer customer = new Customer();

        if (Request.IsAjaxRequest())
        {
            using (SEntities dc = new SEntities())
            {
                customer = dc.Customers.Where(a => a.ID == Id).SingleOrDefault();
                customer.Events = null;
            }
        }

        return Json(customer, JsonRequestBehavior.AllowGet);
}

and this is the Ajax in the view
var EditCustomer = function (Id) {
    $.ajax({
        type: "POST",
        dataType: "json",
        url: '/BasicInfo/EditCustomer',
        data: { 'Id': Id },
        success: function (data) {
            $('#txtFirstName').val(data.FirstName);
            $('#txtLastName').val(data.LastName);
            $('#txtPhone').val(data.Phone);
            $('#txtID').val(data.ID);
            $('#hdUserID').val(data.UserId);
            $('#txtNote').val(data.ClientNote);
            $("#myModalEdit").modal("show");

        },
        error: function () {
            alert('Failed EditCustomer');
        }
    })
}

Although the variable customer from controller is correctly populated but in the view I just get the error "Failed EditCustomer".
What could cause this problem?

A: I solved it just  by adding
 dc.Configuration.LazyLoadingEnabled = false;

before fetching data in controller. and it worked.


text:
Q: Log4j Version 1 Custom Throwable (stacktrace) Renderer for removing new line characters We are trying to customize Log4j version 1 appenders which generate the output in Json format that there are no new line characters including Stacktrace, i.e., we read these logs in Splunk and need all the data in one line so that Splunk can parse the Json properly. If we end up generating multiline Json, Splunk fails to understand the Json correctly, Splunk dashboards won't work correctly.
Added a ThrowableRender to strip the new line characters inside the stacktrace
class Log4JThrowableRenderer extends ThrowableRender {
 override def doRender(throwable: Throwable) : Array[String] = {

   // Kept it simple for now, could have optimized the replace statements
   val defaultRepresentation: Array[String] = new DefaultThrowableRenderer().doRender(throwable)
   val newRepresentation: String = defaultRepresentation.map( l => {
      l.replace('\n','|').replace('\r', '|')
   }).mkString("|)

   Array(newRepresentation)
}

Updated the log4j appenders
log4j.throwableRenderer=com.foo.Log4JThrowableRenderer
log4j.appender.fooAppender.layout.ConversionPattern={"timestamp":"%d{yyyy-MM-dd}", "stackTrace":"%throwable" } // simplified

And we are able to remove the new line characters from Stacktrace in Json output, except that the ending "}" bracket ends up in new line as in
    {"timestamp": "2020-01-01", "stackTrace": "..| ... |... |...|
"}

Not sure how to get all in one line, any ideas?


text:
Q: Azure AD B2C Graph API: Create User + Login At Same Time We are building an android/ios app that will authenticate with B2C.  We will be creating our users programmatically with something like below:

*

*API: invite user

*USER: enters invite into app

*API: confirms invitation info

*USER: enters account info (i.e. password)

*API + B2C/Graph: creates new user

*USER: asked to login with new account (to get tokens) - will launch B2C hosted login

Question: Is there any way we could skip this last login step by using Graph to both create the user and get initial Access + Refresh tokens for the newly created user?  See possible highlighted below.
My sense is that this is possible, but we'd need to mark our B2C application as Allow public client flows and then use the ROPC flow to get tokens programmatically on behalf of the user.  This would likely lower the security posture of this B2C app somewhat.  Are there other options?