text:
Q: react native mapbox dynamically added PointAnnotations are misplaced
I currently developing a react native app ( version 0.55.2) and mapbox/react-native (version 6.1.2-beta2)
I have a situation where some annotations are shown initially on map render, then further annotations are loaded when the user's zooms.
The first annotations are displayed at the right place.

However, when new annotations are added, there are all stuck at the top left corner.

Following their documentation, https://github.com/mapbox/react-native-mapbox-gl/blob/master/docs/MapView.md, I tried to call the function when the map is loaded or rendered. I even tried a setTimeout. The annotations always appears at the topleft map.

Any ideas how should I approach this?
THanks!

class map extends React.Component {
  constructor(props) {
    super(props);
    this.getMapVisibleBounds = getMapVisibleBounds.bind(this);
    this.state = {
      ...INIT_MAP_STATE
    };
  }
  //compo lifecyle
  componentDidUpdate(prevProps, prevState) {

    if (this.state.userPosition.longitude !== prevState.userPosition.longitude) {
      this.setBounds();//first annotations. works fine
    }
    if (this.state.zoomLevel !== prevState.zoomLevel) {
     this.setBounds(); //update annotations. doesn't work
    }

  }

render()=>{
const { quest, checkpoint } = this.props;
    const { selectedIndex } = this.state;
    return (
      <View style={styles.container}>
        <Mapbox.MapView
          styleURL={MAP_STYLE}
          zoomLevel={this.state.zoomLevel}
          centerCoordinate={[this.state.userPosition.longitude,
this.state.userPosition.latitude]}
          style={styles.mapWrap}
        >
          {this.renderMap(checkpoint, "checkpoint")}
        </Mapbox.MapView>

      </View>
    );
}
setBounds = () => {
this.getMapVisibleBounds(this.map)
  .catch(err => {
    console.error(err);
  })
  .then(bounds => {
    this._setMapBounds(bounds);// set state bounds
    return this.props.onLoadQuest(bounds); //api call
  });
 }
}

// annotations rendering
class checkPoint extends Component {
  constructor(props) {
    super(props);
  }

  renderAnnotations = (data, id) => {
    const uniqKey = `checkpoint_${id}`;
    return (
      <Mapbox.PointAnnotation key={uniqKey} id={uniqKey} coordinate={[data[0], data[1]]}>
        <TouchableWithoutFeedback onPress={idx => this.onSelect(id)}>
          <Image source={checkPointImg} style={styles.selfAvatar} resizeMode="contain" />
        </TouchableWithoutFeedback>
      </Mapbox.PointAnnotation>
    );
  };

  render() {
    if (!this.props.checkpoint || isEmpty(this.props.checkpoint)) {
      return null;
    }
    const { hits } = this.props.checkpoint;
    if (!Array.isArray(hits)) {
      return [];
    }

    return hits.map((c, idx) =>
      this.renderAnnotations(c._source.location.coordinates, c._source.id)
    );
  }
}

A: "PointAnnotation" is legacy, try passing your points to  as an object. You're map render will be so much faster once you make the swap. Something like this.
<MapboxGL.MapView
    centerCoordinate={[ userLocation.longitude, userLocation.latitude ]}
    pitchEnabled={false}
    rotateEnabled={false}
    style={{ flex: 1 }}
    showUserLocation={true}
    styleURL={'your_style_url'}
    userTrackingMode={MapboxGL.UserTrackingModes.MGLUserTrackingModeFollow}
    zoomLevel={10}
>

    <MapboxGL.ShapeSource
        key='icon'
        id='icon'
        onPress={this._onMarkerPress}
        shape={{type: "FeatureCollection", features: featuresObject }}
        type='geojson'
        images={images}
    >
        <MapboxGL.SymbolLayer
            id='icon'
            style={layerStyles.icon}
        />
    </MapboxGL.ShapeSource>
</MapboxGL.MapView>

Where "featuresObject" looks something like this...
        let featuresObject = []

        annotation.forEach((annot, index) => {
            let lat = annot.latitude
            let lng = annot.longitude

            featuresObject[index] = {
                type: "Feature",
                geometry: {
                    type: "Point",
                    coordinates: [lng, lat]
                },
                properties: {
                    exampleProperty: propertyValue,
                }
            }
        })

Example for polygon layer
Example with custom icon

A: You can add markers dynamically by using this code:
Create marker component:
const Marker = ({ coordinate, image, id }) => {
    return (
      <MapboxGL.MarkerView coordinate={coordinate} id={id}>
      // Add any image or icon or view for marker
        <Image
            source={{ uri: image }}
            style={{width: '100%', height: '100%'}}
            resizeMode="contain"
          />
      </MapboxGL.MarkerView>
    );
 };

Consume it inside MapBoxGL:
<MapboxGL.MapView
      style={{
        // it will help you keep markers inside mapview
        overflow: 'hidden'
      }}>
{markers &&
      markers?.length > 0 &&
         markers.map((marker, index) => (
            <Marker
              coordinate={[marker.longitude, marker.latitude]}
              // id must be a string
              id={`index + 1`}
              image={getIconUrl(index)}
            />
         ))
}
</MapboxGL.MapView>

A: const layerStyles = Mapbox.StyleSheet.create({
  icon: {
    iconImage: "{icon}",
    iconAllowOverlap: true,
    iconSize: 0.5,
    iconIgnorePlacement: true
  }
});
const mapboxIcon = props => {
  return (
    <Mapbox.ShapeSource
      shape={makeMapBoxGeoJson(props.datum, props.mapKey, props.name)}
      key={`${props.name}_key_${props.mapKey}`}
      id={`${props.name}_${props.mapKey}`}
      images={getIcon(props.name)}
      onPress={idx => (props.isActive ? props.onSelectId(props.mapKey) : null)}
    >
      <Mapbox.SymbolLayer
        id={`${props.mapKey}_pointlayer`}
        style={[layerStyles.icon, { iconSize: props.iconSize ? props.iconSize : 0.5 }]}
      />
    </Mapbox.ShapeSource>
  );
};


text:
Q: Dynamically change bean using applicationProperties in SpringBoot Is it possible to use application properties to set the definition of a bean in Spring boot?
For example:
@Bean
public SomeClassImpl getImpl(){
       return SomeClassImplFactory.getDefaultClassImpl();
 }

would be the default definition. But would there be a way i could specify in a properties file something like
getImpl=some.package.NewClassImpl
Overriding the previous one?
Thanks

A: You may consider to use this approach:
@Autowired
private Environment environment;

@Bean
public SomeClassImpl getImpl(){
    if(environment.getProperty("getImpl").equals("xxx")) {
        return new NewClassImpl();
    }
    return SomeClassImplFactory.getDefaultClassImpl();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I put the result of the data in variable to the other variable? <?php
$a = "time(0)";
$b = eval($a);

Like this, I want to put the result of the data....
I can put the string with eval code.. But how can I do this?

A: 1) your string must contain completed php code, ie has ; at the end
2) code in the string doesn't produce any output and it results in NULL value of $b
So, to make it working, write:
$a = "time(0)";
$b = eval("echo ".$a.";");
echo $b; // 1433582861

A: I think this will help you,
$a = "time(0)";
$b = call_user_func($a);
$c = new DateTime($b);
var_dump($c);


text:
Q: Bootstrap radio buttons in Yesod: how to get value? I try to get value of radio button from Bootstrap value in Yesod. So this is my inline-radio:
<form .form-horizontal
    ...
    <label .radio-inline>
        <input type=radio
               name=gender
               checked>_{MsgMale}
    <label .radio-inline>
        <input type=radio
               name=gender>_{MsgFemale}

But I don't understand how can I get value of gender. I try it:
data NewPatient = NewPatient { lastName
                             , firstName :: Text
                             , gender    :: Bool
                             } deriving Show

...

newPatient <- runInputPost $
              NewPatient <$> ireq textField "patientLastName"
                         <*> ireq textField "patientFirstName"
                         <*> ireq boolField "patientGender"

but gender is always True.
I've tried to use value attribute for input, but in this case I got an error Invalid boolean.
I've read this in docs:
If this field is required, the first radio button is labeled "Yes" and the second "No".

But I don't understand it. What is it mean "labeled" in this case?
Please help me.

A: I found solution:
<form .form-horizontal
    ...
    <label .radio-inline>
        <input type=radio
               name=gender
               value=on                 <<< exactly `on`
               checked>_{MsgMale}
    <label .radio-inline>
        <input type=radio
               value=no                 <<< exactly `no`
               name=gender>_{MsgFemale}

In this case I have True if user checked on first button (Male), and False if he checked second button (Female).


text:
Q: Подсчитать сумму заказа исходя из цены и количества в каждом поле Уважаемые знатоки, помогите пожалуйста разобраться. Бьюсь уже пол дня, не могу добиться чтобы при увеличении количества в поле input автоматически количество перемножалось на цену и выводило результат.

window.onload = function () {
  var myDiv = document.getElementById('myDiv');
  var inp;
  myDiv.onclick = function (e) {
    e = e || event
    var target = e.target || e.srcElement;
    if (target.value == '+') {
      inp = target.previousSibling.previousSibling;
      if (parseInt(inp.value) < 5) {
        inp.value = parseInt(inp.value) + 1;
      }
    } else if (target.value == '-') {
      inp = target.nextSibling.nextSibling;
      if (parseInt(inp.value) > 1) {
        inp.value = parseInt(inp.value) - 1;
      }
    }
 var znachenie = document.getElementById('inp').value;
 var prise = document.getElementById('price').textContent;
 var totalPriceProduct = prise * znachenie;
 document.getElementById('total_price').innerHTML = totalPriceProduct;
 document.getElementById('total_price_post').value = totalPriceProduct;
  }
}

500 грн.
<input type="button" value="-">
<input type="text" id="inp" size="1" value="1">
<input type="button" value="+">
500
<input id="total_price_post" type="text" value="500">

500 грн.
<input type="button" value="-">
<input type="text" id="inp" size="1" value="1">
<input type="button" value="+">
500
<input type="text" value="500">

500 грн.
<input type="button" value="-">
<input type="text" id="inp" size="1" value="1">
<input type="button" value="+">
500
<input type="text" value="500">

A: Можно сделать подсчёт, основываясь на вёрстке, но это сильно неправильно - чуть изменить и всё полетит.
Лучше сделать базу в JS, а при вводе передавать только маркер ID товара:

// База знаний; тут уже можно гораздо больше ставить, нежели просто цена
let db = [
  {
    cost: 500
  },
  {
    cost: 111
  },
  {
    cost: 894
  }
];

// Простенький делегатор
document.querySelector('table').addEventListener('input', function(e){
  let el = document.activeElement;
  if(el.nodeName === 'INPUT' && el.classList.contains('amountInput')) recalculate.call(el);
});

function recalculate() {
  let id = +this.dataset.purchase;
  if(!db[id]) return;

  let parent = this.closest('.item'); // Общий предок
  let cost = db[id].cost; // Получаем цену по ID

  parent.querySelector('.calcResult').innerHTML = +this.value * cost; // Перемножаем и вставляем в последнюю ячейку
}
input[type="number"] {
   width: 50px;
}

    Стоимость
    Количество
    Итого

    500 гавриков
    <input type='number' value='0' data-purchase='0' class='amountInput' />
    0

    111 гавриков
    <input type='number' value='0' data-purchase='1' class='amountInput' />
    0

    894 гавриков
    <input type='number' value='0' data-purchase='2' class='amountInput' />
    0


text:
Q: Authenticate GCP Service Account via environment /variable Authentication for a GCP Service Account usually requires a .json file containing the credentials.
The command is: gcloud auth activate-service-account --key-file "path to .json file"
If the above command is run as a subprocess in Python3 how could one pass the --key-file by storing the contents of the .json in memory. The requirement is to not have/create the file on local storage.


text:
Q: Is it possible to make an APK file with sharedPreferences data from install App in device? This is first time I put an input in my app, The input saved in shared Preferences.
I want to share my app with other persons including shared preferences data.
How can I build an APK file with shared preferences saved data from the installed app from device?
Please help me out


text:
Q: Filter rows where all matching rows are True I have a table formatted as follows:

BOM
Imported

COM123
True

COM123
True

COM123
False

COM999
True

COM999
True

COM999
True

I'd like to filter the table to show only rows where all matching BOM rows are True in the Imported column. I.e., in this case, COM999 rows should show, and COM123 rows are filtered out because one entry is False.
FYI this is to produce a list of Production BOMs where all the components already exist in Business Central. The Imported column is the result from a merge of the query with an extract from BC, and sets the value to true where the BOM components exist.
Can anyone please give me a steer?
I've been farting around with this half the day, but I can't find the equivalent to a EXISTS query in SQL...

A: Algorithm should be clear in the code comments

*

*Group by BOM

*Test each BOM subgroup for ALLTRUE

*Filter the Grouped table

*Re-expand the original

let

//change next line to reflect actual data source
    Source = Excel.CurrentWorkbook(){[Name="Table21"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"BOM", type text}, {"Imported", type logical}}),

//Group rows by BOM
//Then determine where all "Imported" = True
    #"Grouped Rows" = Table.Group(#"Changed Type", {"BOM"}, {
        {"all true", each List.AllTrue([Imported]), type logical},
        {"all", each _, type table [BOM=nullable text, Imported=nullable logical]}}),

//Remove the false rows
//then delete the "all true" column
    #"Filtered Rows" = Table.SelectRows(#"Grouped Rows", each ([all true] = true)),
    #"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"all true"}),

//re-expand
    #"Expanded all" = Table.ExpandTableColumn(#"Removed Columns", "all", {"Imported"}, {"Imported"})
in
    #"Expanded all"


text:
Q: Perform POST request in Swift I am trying to do something like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

request.HTTPMethod = @"POST";

NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

This is what I have so far:
var url = NSURL(string: "some url")
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"

var dataString = "some data"
var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData

request.HTTPBody = requestBodyData

var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)

println("sending request...")

connection.start()

However, the var requestBodyData: line throws the first stone with "Cannot convert the expression's type NSData to type NSData"
Anyone care to weigh in?

A: stringByAddingPercentEscapesUsingEncoding returns a string instead of an NSData object. According to this answer, you need to use this to convert to an NSData instance:
let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding)

A: Using Alamofire to send HTTP POST request
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.google.com")!)
request.HTTPMethod = "POST"

let body = "email=\(email)&access_token=\(token)"
request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)

Alamofire.request(request).responseJSON { response in

        NSLog("response.request: \(response.request)")  // original URL request
        NSLog("esponse.response: \(response.response)") // URL response

        switch response.result {
        case .Success:
            NSLog("Validation Successful")
        case .Failure(let error):
            // Logout
            NSLog("\(error), \(String(data: response.data!, encoding: NSUTF8StringEncoding))")
            return
        }

        // Save sip account information to NSUserdefaults
        if let json = response.result.value as? [String: AnyObject]{
            // Do your stuff
        }
}


text:
Q: Re-usable dropdown list when clicking various elements, what's the technique? Say I have various parts of a page, that when clicked, should display a dropdown list below the link I just clicked on.
Since this drop down is the exact same, I noticed that some sites do this, where they have a single drop down list defined in the DOM, and when clicked, it somehow gets displayed below where they clicked.
What's the technique to do this?
Would it be to have a empty div below all the parts of my site where I want to inject the drop down, then when clicked, copy the div that contains the drop down list elements to the element that was just clicked? Or is there a smarter way?

A: I would also like to see these sites...
However if you'd like to accomplish what you've described I would advise against a bunch of empty divs. Maybe something along these lines: jsFiddle
A select box which is initially hidden, that you show on click. Of course you still have a get rid of it if they decide not to use it, but at least it's not in the flow, and isn't repeating itself.
$('a').click(function(){
    var offset = $(this).offset();
    offset.top += 20;
    $('#ghost').show().offset(offset);
});


text:
Q: Pm2 error while deploying Strapi App on DigitalOcean I've been following the official docs for deploying a Strapi app onto Digital ocean, but I'm having trouble setting up pm2.
It starts the app for a second, and then shows
status: errored

there's no script.js to run the app, but when I cd to /home/myusername/appname/backend and run npm start, it works just fine, which leads me to believe that I have the ENV variables set correctly
Here's the config file
module.exports = {
  apps: [
    {
      name: 'strapi',
      cwd: '/home/your-name/project/backend',
      script: 'npm',
      args: 'start',
      env: {
        NODE_ENV: 'production',
        DATABASE_HOST: 'localhost', // database endpoint
        DATABASE_PORT: '5432',
        DATABASE_NAME: 'strapi', // DB name
        DATABASE_USERNAME: 'your-name', // your username for psql
        DATABASE_PASSWORD: 'password', // your password for psql
      },
    },
  ],
};

Then I run pm2 logs, I see
2020-07-13T01:58:49: PM2 log: App [strapi:0] online
PM2        | 2020-07-13T01:58:49: PM2 error: Error: spawn node ENOENT
PM2        |     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
PM2        |     at onErrorNT (internal/child_process.js:415:16)
PM2        |     at process._tickCallback (internal/process/next_tick.js:63:19)

Thanks

A: *

*First replace:

    NODE_ENV: 'production',
    DATABASE_HOST: '127.0.0.1', // database endpoint
    DATABASE_PORT: '5432',
    DATABASE_NAME: 'THE DB NAME EX.SAMMY'
    DATABASE_USERNAME: 'THE DB USERNAME EX.SAMMY'
    DATABASE_PASSWORD: 'THE DB PASSWORD'

*pm2 del 0 (check strapi app with pm2 start)

*pm2 start ecosystem.config.js

A: for me it was because cwd was already relative and didn't like how my path was structured. I tried ~/my-app as well as /home/me/my-app and both were wrong. It eventually just wanted my-app.


text:
Q: DotNetZip - How to cancel a "zipping" operation that is in progress? How to cancel a "zipping" operation that is in progress in DotNetZip?
I'm using the following code to zip a folder:
using Ionic.Zip;
...
using (zip = new ZipFile())
{
    zip.AddDirectory(@"C:\SomeFolder");
    zip.Save(@"C:\SomeFolder.zip");
}

Now I need to add a "Cancel" button that allows the user to cancel the process, if he wants to.
I think that there's a proper way of doing this, but I cannot find it anywhere.
Thank you.

A: Seems to be working now:
using Ionic.Zip;

bool wasCanceled = false;
ZipFile zip;

using (zip = new ZipFile())
{
    zip.SaveProgress += zipProgress;
    zip.AddDirectory(@"C:\SomeFolder");
    zip.Save(@"C:\SomeFolder.zip");
}

private void zipProgress(object sender, SaveProgressEventArgs e)
{
    if(wasCanceled) { e.Cancel = true; }
}

private void btnCancel_Click(object sender, EventArgs e)
{
    wasCanceled = true;
}

Very helpful documentation here: https://documentation.help/DotNetZip/


text:
Q: Want a redirection for a specific URl. so logged out users cannot be access the page directly. i amm working in codeigniter For Example i have this "http://localhost/traffictack/woorank/" URL and i want that it can be only access by the logged in user. if any other user directly access to this url it redirected to home page:
  if ( ! $this->session->userdata('logged_in'))
   {
    redirect('login');
   }

A: if (empty($this->session->userdata('logged_in')))
{
    redirect('login'); # use not logged in
}
else{
    redirect('home'); # logged user
}

Or else
In Controller
function __construct() {
    parent::__construct();
    $this->is_logged_in();

}

function is_logged_in() {
    $is_logged_in = $this->session->userdata('logged_in');
    if ((!isset($is_logged_in))) {
        redirect('login');
    }
}


text:
Q: How to configure scaladoc in eclipse juno? I'm new to scala. I've installed the nightly build since I use eclipse juno. The problem I'm facing is I do not see scaladoc when the cursor is on a class/trait and I press F2(like in java).

A: That is because it is not implemented yet. See ticket #1000954 and #1000210 for more information and future work on this.

A: As a poor man's alternative, the JavaDoc view works for Java elements. You can enable it from Window/Show View and it will show you the docs related to the element under the cursor as long as it comes from Java (even in Scala code).

A: For the completeness of SO : Scaladoc is now integrated since release 4.0.0 RC1 of the Scala-IDE plugin.


text:
Q: Android как сделать GET запрос Мне при нажатии на кнопку в MainActivity надо запросить данные
Есть специальный адрес по которому они лежать в json представлении
Мне кажется или в java все как то сложно?)
Права для интернета я указал.
Все, с кодом проблемы)
URL url = new URL("http://hashcode.ru").openStream()

Тут подчеркивает красным строчку с адресом.... (((

A:  public static String doGet(String url)
            throws Exception {

        URL obj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        connection.setRequestMethod("GET");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0" );
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        connection.setRequestProperty("Content-Type", "application/json");

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = bufferedReader.readLine()) != null) {
            response.append(inputLine);
        }
        bufferedReader.close();

//      print result
        Log.d(TAG,"Response string: " + response.toString());

        return response.toString();
    }

Использовать можно так:
    new AsyncTask<Void, String, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            String s = "";
            try {
                s = doGet(myURL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return s;
        }

        @Override
        protected void onPostExecute(final String result) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvRez.setText(result);
                }
            });
        }
    }.execute();

A: Делал с помощью потока:
public class JsonTask extends AsyncTask<String,String,String>
{
    private final String URL = "google.com";
    private ArrayList<NameValuePair> postParams = new ArrayList<>();
    private JSONObject jsonObject = new JSONObject();

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params)
    {
            postParams.add(new BasicNameValuePair("ParamKey", "ParamValue"));
            jsonObject = JSONParser.makeHttpRequest(URL, "GET", postParams);
            return jsonObject.toString();
    }
}

и Вот сам парсер для разбора JSON:
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

        public static JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
            try {
                if (method == "POST") {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                } else if (method == "GET") {
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }
            } catch (UnsupportedEncodingException e)
            {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e)
            {
                System.out.println("Internet Error.")
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                System.out.println("Buffer Error : Error converting result " + e.toString());
            }
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                System.out.println("JSON Parser: + Error parsing data " + e.toString());
            }
            return jObj;
        }
    }


text:
Q: How to import specific packages from common/shared folder? I am relatively new to python and am trying to find a good way to share common code amongst multiple projects.
Say I have folder structure below and both Proj1/Proj2 have their own environments (left out for simplification):
/Development
    /Common
        __init__.py
        setup.py
        /CommonA
            __init__.py
            commonA.py
        /CommonB
            __init__.py
            commonB.py
    /Proj1
        main1.py
    /Proj2
        main2.py

and setup.py:
from setuptools import setup, find_packages

setup(name='Common',
      version='0.1',
      description='Common Code',
      author='Me',
      license='MIT',
      packages=find_packages(),
      zip_safe=False)

If I am working in Proj1, I can "pip install .\Common" which pulls in both CommonA and CommonB.
That's great if Proj1 needs both modules, but what if Proj1 only needs CommonA? Is there a way to only install CommonA without changing setup.py each time I pip install?


text:
Q: Rig in which + distributes over * Let $A$ be a commutative rig (ring without additive inverses). Suppose that addition in $A$ distributes over multiplication in $A$, so that $A$ is a rig in $2$ ways, depending on which operation we think of as the multiplication.

Question: Are all such rigs distributive lattices?

This question is interesting to me because it contends to show a special property of distributive lattices: that they are precisely the sets with $2$ commutative monoidal operations which distribute over each other.
Note that it suffices to show that $\forall a \in A : a^2 = a$ and $\forall a \in A : a +a =a$.
Edit: One answer has shown that without a unit for $+$ and $\cdot$, my note above does not hold, and the answer is also false. I should have stated which meaning of "lattice" I am using, namely that a lattice is a poset with finite meets and joins, including the empty meet and empty join.

A: Distributivity of addition over multiplication says $$a+bc=(a+b)(a+c)$$ for any $a,b,c$.  Setting $b=c=0$ gives $a=a^2$.  Setting $b=0$ and $c=1$ gives $a=a(a+1)=a^2+a=a+a$.
(Alternatively, assuming that by "addition distributing over multiplication" you include the case of nullary multiplication where it says $a+1=1$, then you can deduce $a=a+a$ by just dualizing the argument for $a=a^2$.  Actually, though, that nullary case does not have to be assumed, since it follows automatically.  Indeed, setting $a=1$ and $c=0$ in $a+bc=(a+b)(a+c)$ gives $1=(1+b)1=1+b$ for arbitrary $b$.)


text:
Q: Validate one field when another model changes There are a number of questions that already exist that discuss being able to validate one field based on the value of another model changing. Many of these questions seem out of date as the changes that have happened in Angular post-date these questions.
I have one directive that allows a user to choose a "color". There are other directives that allows a user to choose "sizes" (width and height). Some colors are only available in certain sizes.
My "color" directive has an additional directive assigned that manages validation. If the width and height are over a certain amount, I add my error message and everything is great.
However, this same validation will not trigger when the "sizes" change. I have tried to use on-change="form.myfield.$validate() on the size fields and this provides the desired functionality, but then because the field becomes invalid, the "color" model is now undefined.
Is there a simple way to trigger validation on a field when the value of another model is changed?
Here is a Plunkr.
http://plnkr.co/edit/DQhRFcIKkLlf0NfnuDJa?p=preview

EDIT
The more I think about this, the more I believe I realize that validation on this type of application is going to be incredibly difficult due to the complex interactions that take place between various multi-element directives. I think it might be simpler to just set the acceptable values for various inputs based on certain model values, thus preventing any invalid values from being chosen in the first place.

A: You can do it by adding a watch on width and height properties and setting the validity of the color input conditionally.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.colors = [
    {
      description: 'Red',
      sku: '5555',
      oversize: true
    },
    {
      description: 'Blue',
      sku: '6666',
      oversize: false
    }
  ]

});

app.directive('oversize', function(){
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      function validator (modelVal, viewVal) {
        var w = scope.width;
        var h = scope.height;
        var isValid = false;
        if (w > 4 && h > 4) {
          if (modelVal.oversize === true) {
            isValid = true;
          }
        } else {
          isValid = true;
        }
        return isValid;

      }
      ctrl.$validators.oversize = validator;
      scope.$watch('width', function () {
        ctrl.$setValidity("oversize", validator(scope.color));
      })
      scope.$watch('height', function () {
        ctrl.$setValidity("oversize", validator(scope.color));
      })
    }
  }
})
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" href="style.css" />

    <form action="" name="form">

Red is available in oversize, blue is not.

If both width and height are > 4, blue cannot be used

That is not available in this size

      Color
      <select oversize name="color" ng-model="$parent.color" ng-options="c.description for c in colors track by c.sku"></select>

      Width
      <select name="width" ng-model="width" ng-options="v for v in [1,2,3,4,5]"></select>

      Height
      <select name="height" ng-model="height" ng-options="v for v in [1,2,3,4,5]" id=""></select>
    </form>

Oversize for {{color.description}} is {{color.oversize}}


text:
Q: Why fastNlMeansDenoisingColored() of openCV is giving error? I'm a rookie in openCV concept so please do excuse me if my question is foolish.Actually I'm trying to apply the Photo.fastNlMeansDenoisingColored() method but I don't understand why it's giving such error.
Code:
Mat tmp = new Mat (bitmap.getWidth(), bitmap.getHeight(), CvType.CV_8UC1);

            Utils.bitmapToMat(bitmap, tmp);

            Photo.fastNlMeansDenoisingColored(tmp,tmp, 10, 10, 7, 21);

            Utils.matToBitmap(tmp,bitmap);

Error:
CvException [org.opencv.core.CvException: cv::Exception: /hdd2/buildbot/slaves/slave_ardbeg1/50-SDK/opencv/modules/photo/src/denoising.cpp:91: error: (-5) Type of input image should be CV_8UC3! in function void cv::fastNlMeansDenoisingColored(cv::InputArray, cv::OutputArray, float, float, int, int)
]
    at org.opencv.photo.Photo.fastNlMeansDenoisingColored_0(Native Method)
    at org.opencv.photo.Photo.fastNlMeansDenoisingColored(Photo.java:118)
    at opengl.community.myopencvexample.MainActivity$3.onClick(MainActivity.java:83)
    at android.view.View.performClick(View.java:4478)
    at android.view.View$PerformClick.run(View.java:18698)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)

A: Download the native libs and put them in your main/jniLibs directory.

A: I've solved my issue by updating the openCV lib from 2.x to 3.0


text:
Q: why pam_sm_authenticate is called twice when ssh login? i am tring to make PAM module that authenticate user and password and also get a trap when logout has occurred but i don't understand why pam_sm_authenticate  is called twice?
i have build my own pam_hook.so , compiled it with:
 gcc -fPIC -Wall -shared -lpam -o pam_hook.so pam_hook.c

i have implemnted this function's :
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_chauthtok(pam_handle_t    *pamh,const int flags,int argc,const char **argv);
PAM_EXTERN int pam_sm_acct_mgmt(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv);
PAM_EXTERN int pam_sm_close_session(pam_handle_t *pamh, int flags, int argc, const char **argv);

i have printed to file each enter to this function's.
the order of the call to the function's on login of sshd user :
function :  pam_sm_authenticate
function :  pam_sm_setcred
function :  pam_sm_open_session
function :  pam_sm_setcred
function :  pam_sm_authenticate

and on sshd logout:
function :  pam_sm_close_session
function :  pam_sm_setcred

i can't understand why pam_sm_authenticate  it is called twice ,
my /etc/pamd.d/sshd:
# cat /etc/pam.d/sshd
 session     optional       /path_to/pam_hook.so
 auth        requisite       /path_to/pam_hook.so

A: Just faced this problem and it took me time to find a reason.
In my case I use custom conversation in pam_sm_authenticate() to ask user for a second password.
My module called twice, but at first time my conversation was not prompted to user, althought suceeded by return value. And response was empty, so my module failed authentication.
Going through openssh code I found that if PasswordAuthentication set to yes, sshd will use "blind" method for your conversation. Your prompts will be ignored and the response will be the password provided by user before. My password was empty so my module got empty response.
Hate this undocumented magic..


text:
Q: MVC: 404 not found in ajax I am showing a number of flights in a view. I have created a button for every flight. On clicking this button I am getting the details of a single flight shown in the view.
here is my view code:
foreach (var item in Model)
                    {

@item.FromCity

@item.ToCity

@item.DepartureDate.ToShortDateString()

@item.DepartureTime.ToShortTimeString()

@item.ArrivalTime.ToShortTimeString()

                            <select id="CFare_@item.Fare" class="form-control me-2">

                                @foreach (var re in ddlcabin)
                                {
                                    <option value="@re.Fare">@re.CabinName (@re.Fare)</option>
                                }
                            </select>
                            <button class="form-control btn btn-primary" onclick="Save(@item.FlightID,@item.Fare)">select </button>

                    }

Now I want to get these values using and pass them to an action method without using a form in the view.
here is my js code:
    function Save(id, fare) {
            var fct = $("#FCity_" + id).text();
            var tct = $("#TCity_" + id).text();
            var ddt = $("#DDate_" + id).text();
            var dt = $("#DTime_" + id).text();
            var at = $("#ATime_" + id).text();
            var cf = $("#CFare_" + fare).val();

            $.ajax({
                method: 'GET',
                url: 'Flights/ReserveFlight',
                data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
                success: function (data) {
                    console.log("data is inserted")
                },
                error: function (err) {
                    console.log(err)
                }
            });
}

when I click the save button it shows an error in the browser console and doesn't hit the debugger applied to the action method
here is my action method:
public ActionResult ReserveFlight(string FromCity, string ToCity, DateTime DepDate, DateTime DepTime, DateTime ArrTime, int CabinFare)
        {
            return View();
        }

here is the error:

GET
http://localhost:64480/Flights/Flights/ReserveFlight?FromCity=Islamabd%20&ToCity=Karachi&DepDate=5%2F20%2F2022&DepTime=8%3A30%20AM&ArrTime=12%3A00%20AM&CabinFare=4500 404 (Not Found)

A: Modify the URL in ajax as:
$.ajax({
    method: 'GET',
    url: '/Flights/ReserveFlight',
    data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
    success: function (data) {
        console.log("data is inserted")
    },
    error: function (err) {
        console.log(err)
    }
});

Or work with UrlHelper.
$.ajax({
    method: 'GET',
    url: '@Url.Action("Flights", "ReserveFlight")',
    data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
    success: function (data) {
        console.log("data is inserted")
    },
    error: function (err) {
        console.log(err)
    }
});

Reference: Action(String, String) | UriHelper.Action() Method


text:
Q: How can I Omit a specific subtype/property? How can I omit a grandchild property?
Here is a contrived example.
interface ILikes {
   article: string,
   page: string,
   userId: number | string,
}

interface IUserData {
   userName: string,
   isAdmin: boolean,
   ...data,
   interests: {
     likes: ILikes,
     saved: {
       ...data
     }
   }
}

const userObj: Omit<IUserData, "interests"> = {
   ...data
}

I need to omit likes which is a grandchild property. I can't make likes optional because I use it in other instances.

A: export type DeepKey<
    T,
    K extends keyof T = keyof T
> =
    K extends string ?
    T[K] extends Record<string, unknown>
    ? K | `${K}.${DeepKey<T[K]>}`
    : K
    : never

type DeepOmit<
    T,
    P extends DeepKey<T>,
> =
    P extends `${infer M}.${infer Rest}`
    ? { [O in M]: DeepOmit<T[O & keyof T], Rest extends DeepKey<T[O & keyof T]> ? Rest : never> } extends infer Y
    ? { [K in Exclude<keyof T, M>]: T[K] } extends infer Z ?
    {} extends Y ? Z : {} extends Z ? Y : Y & Z
    : never : never
    : { [K in Exclude<keyof T, P>]: T[K] }

type ABC = {
    a:
    {
        b:
        {
            c: 1,
            d: { e: boolean }
        }, f: 2
    }
}

type A = DeepOmit<ABC, 'a'>
//   ^?

type B = DeepOmit<ABC, 'a.b'>
//   ^?

type C = DeepOmit<ABC, 'a.b.c'>
//   ^?

playground

A: You can define an interface for your interests property and Omit likes from that interface. That way it is more readable than creating a special Omit utility type.


text:
Q: Save .csv file in the same directory as .py file I am tring to save my .csv file which is a result of some queries in the same location as the .py file.
import os
with open(os.path.dirname(os.path.abspath(__file__))+'MyCSVFile.csv','wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(myList)

I always seem to get my csv file one directory before. When I print os.path.dirname(os.path.abspath(__file__)) it gives me the proper path but the output MyCSVFile is saved one above. What is the problem here?

A: You have to use os.path.join to save the csv file in the same directory
import os

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'MyCSVFile.csv')

with open(csvfilename, 'wb') as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(myList)

This should work as excepted

A: Remove the call to os.path.dirname since you are already calling os.path.abspath. Calling dirname returns the directory component thus you are getting the directory up in the hierarchy. BTW: use os.path.join to join parts of a directory.


text:
Q: How to disable CSRF Token in Laravel and why we have to disable it? I want to see how I can disable CSRF token in Laravel and where I have to disable it. Is this good to disable it or not?

A: You can Disable CSRF on few routes by editing.
App\Http\Middleware\VerifyCsrfToken

and add your own routes name in protected
$except = [] array.

It does not seems to be good practice as by doing this we are removing security feature of Laravel.

A: The CSRF token protects your application and it's users against cross-site request forgery. For more information on that, have a read here:
https://en.wikipedia.org/wiki/Cross-site_request_forgery
The token is validated via Middleware in Laravel. If you take a look at the file app/Http/Middleware/VerifyCsrfToken.php, you will see it gives you the option to add URLs that should be exempt from CSRF verification.
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}

If you want to disable it entirely, you can find it in the Middleware group named web in app/Http/Kernel.php. Those are the middlewares that fire by default over HTTP requests.
I wouldn't recommend disabling it where possible though.

A: In laravel 9.
Open file \App\Http\Middleware\VerifyCsrfToken.php
Disable for all routes
protected $except = [
    '*',
];

Disable for some routes
 protected $except = [
    'mobile/*',
    'news/articles',
];

I searched for a long time how to disable CSRF completely, there are many identical examples but they do not help

A: Many people explain how to do it, but they do not explain what the url should look like.
edit app/Http/Middleware/VerifyCsrfToken.php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
     *
     * @var bool
     */
    protected $addHttpCookie = true;

    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        '/user/my_function'
    ];
}

In the $except array(); we add a url with just a simple string.  This points to a controller usually depending on how your route is setup.
For example I have a UserController.php file in my Controller folder.  I have a route like. In the web.php routes file.
Route::post('/user', 'UserController@my_function')->name('my_function');

Also alternatively, if you came to this question simply because you don't know how to use the CSRF and you don't actually need to disable it, or make the URL except.  You can use this method.
Add these lines to your app.blade.php if it is used for ajax related calls.
<script>
$(function() {
    $.ajaxSetup({
        headers: {
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
        }
    });
});
</script>

A: Hi just go to app/Http/Kernel.php file simply commented out line no 31
// \App\Http\Middleware\VerifyCsrfToken::class,

A: You can disable it in app/http/Kernel.php in the web middleware group.

Is this good to disable it or not?
No it's not. Read the Wikipedia page about CSRF to understand what CSRF is, the CSRF-Token prevents CSRF.

A: If you want to block csrf token verification easily head over to app/Middleware/VerifyCsrfToken.php to disable it for all routes
protected $except = ['*'];
or specify routes like this
 protected $except = ['/api/route/one', 'api/route/two'];

A:
(Temporary fix. Not Recommended)

Just Open kernel.php (app/http)
and disable
App\Http\Middleware\VerifyCsrfToken::class,


text:
Q: Link Tracking with DTM and Custom Variables I need to capture the link that was clicked as well as the page that the link was clicked on using Adobe DTM, and then pass it into an evar and sprop. I don't need pageviews, so the s.tl() is used.
I'm using an event based rule with "click" as my event type, with my element tag/selector as "a" for the anchor tag.
Below is the page code that I'm using in DTM - but my problem is, I'm getting an "Unexpected token ILLEGAL (line: 1, col:3)" and I can't seem to figure out why.
Ultimately - is this the right approach to take, or is there a more simplified approach or better solution?
// Custom Link Tracking
$("a").click(function(event) {
console.log($(this).text();
s.eVarXX = $(this).text();

A: By using an event-based rule that already listens for the anchor click you don't need another jQuery function.
You can simply grab both the href and link text within the Adobe Analytics section of your rule:
s.prop1 = $(this).text() // link text
s.eVar1 = $(this).attr("href") // Link URL

Hope this Helps


text:
Q: Ruby random number generator I'm attempting to make a random number guessing game in Ruby. I'm rather new so perhaps the answer is obvious but why won't this work?
number = rand(5)
choice = 9999
while number != choice do
    puts "Guess the number #{number}"
    choice = gets.chomp
end
puts "You guessed Correctly! #{number} was the correct number."

As you can see I limited it to numbers between 0 and 4. Then the while loop runs while the guess made by the user is different from the random number generated. However, even when the user enters the correct number, the while loop continues looping. As you can see I've even printed the generated number so I know which to guess.
Any idea what's going wrong here?

A: number is a number, choice is a string. You need to parse the string for this to work:
choice = gets.chomp.to_i

A: You probably should be using something else to be comparing the number returned from the rand() function and the string returned from gets.
Perhaps the spaceship operator (<=>) would work, combined with turning the number into a string using to_s, in which case the while loop header would look like
while !(number.to_s <=> choice) do

or something like that.
You don't have to use the spaceship operator, though.


text:
Q: Flash Message in YII Framework After I send the request, I will announce the result to the user via SET FLASH. What is the way to show a message when the user sends a request?
For example when sending a message form : Display -> form is being send and then a flash message is displayed

A: Check the wiki on the Yii framework website:
http://www.yiiframework.com/wiki/21/how-to-work-with-flash-messages/
In your controller you can put:
Yii::app()->user->setFlash('success', "Form posted!");

In your view you can echo the flash message by:
<?php echo Yii::app()->user->getFlash('success'); ?>

Optionally you can check if a flash message exists by using the hasFlash method, so the code in your view would look like this:
<?php if(Yii::app()->user->hasFlash('success')):?>

      <?php echo Yii::app()->user->getFlash('success'); ?>

<?php endif; ?>

A: Add setFlash in your controller. Something like this:
if($comment->save())
{
    Yii::app()->user->setFlash('commentSubmitted','Thank you for your comment.');
    $this->refresh();
}

And in your views, display flash message something like this:
<?php if(Yii::app()->user->hasFlash('commentSubmitted')): ?>

        <?php echo Yii::app()->user->getFlash('commentSubmitted'); ?>

<?php endif; ?>

A: In your controller you can put:
if(conditions)
   Yii::app()->user->setFlash('success', "Success text");
else
   Yii::app()->user->setFlash('error', "Error text");

In your view you can echo the flash message by:
<?php
if(Yii::app()->user->hasFlash('success'))
    Yii::app()->user->setFlash('success', 'Well done! '.Yii::app()->user->getFlash('success').'.');
else
    Yii::app()->user->setFlash('error', 'Error! '.Yii::app()->user->getFlash('error').'.');

$this->widget('bootstrap.widgets.TbAlert', array(
    'block'=>true, // display a larger alert block?
    'fade'=>true, // use transitions?
    'closeText'=>'×', // close link text - if set to false, no close link is displayed
    'alerts'=>array( // configurations per alert type
        'success'=>array('block'=>true, 'fade'=>true, 'closeText'=>'×'), // success, info, warning, error or danger
    ),
)); ?>


text:
Q: Can Google Tag Manager add head pixels? While TM is loaded in a webpage's body, can it still be used to add pixels to a webpage's head?
Note that sometimes it's just a recommendation (e.g. Facebook Remarketing pixel), but other times it's mandatory (e.g. Facebook Conversion pixel).

A: Yes, it can.
Google Tag Manager code is below the body tag, but that doesn't mean the custom HTML tags are loaded there too. Actually it loads them in the head by default.


text:
Q: How to add accessibility to Unity3d for iOS Is there any way to communicate with iOS's VoiceOver accessibility native support via Unity3d?  We have an application that needs to be accessible, and we are not sure how to go about it.
Creating our own custom VoiceOver is not possible since we need language support, so we need to go native. Our gut tells us to communicate with iOS via a plugin, however it seems that iOS hardware is not able to capture unity taps, but also it seems to override some of our gestures.
Any suggestion would be appreciated.

A: There is some note here

In general, you do not create accessibility elements for items in your application because standard UIKit controls and views are accessible by default. However, if you have a view that contains nonview items, such as icons or text images, that need to be accessible to users with disabilities, you create accessibility elements to represent them. In this case, the containing view should implement the UIAccessibilityContainer informal protocol and use this method to create an accessibility element to represent each item that should be exposed to an assistive application.

and here

The UIAccessibilityContainer informal protocol provides a way for UIView subclasses to make selected components accessible as separate elements. For example, a view might contain icons or drawn text that, to end users, appear and function as separate items. But because these components are not implemented as instances of UIView, they are not automatically accessible to users with disabilities. Therefore, such a container view should implement the UIAccessibilityContainer methods to supply accessibility information about these components to assistive applications such as VoiceOver.

I'm not familiar with Unity itself, but that's seems to be possible to hack containing view to support accessibility - you can build set of UIAccessibilityElemets that represents currently visible items on screen.

A: Unfortunately, Unity and VoiceOver cannot natively work together, since Unity takes care of all rendering - including the UI. That is why VoiceOver or any other screen reader cannot access the UI and make it accessible.
Really your only option is, as you already mentioned, taking the long way around and implement the same functionality inside of Unity.
You can either implement this yourself, or use a plugin that does it for you.
There's a plugin available that recreates screen reader functionality for Unity UI. It works like VoiceOver and TalkBack, and uses the native VoiceOver speech for text-to-speech output.
https://assetstore.unity.com/packages/tools/gui/ui-accessibility-plugin-uap-87935

A: Unity3d does not support the .ipa files that are used by VoiceOver to provide hooks that allow the feature to function. Therefore, the feature cannot be used directly to make an application more accessible.
Therefore, a method of developing a system based on VoiceOver within Unity must be used, which could make use of some current VoiceOver conventions - i.e. recreating VoiceOver's methods of handling pages and applications within Unity.
Other than that I'm unsure what you could do without taking the "long way round" of creating your own language support with similar accessibility functions to VoiceOver.


text:
Q: Vue i18n - can not dynamically change locale I have a small vue app where I want to implement the vue-i18n plug to make my app multilingual. I have installed the vue-i18n plugin from the vue cli. I have two locales and everything works as expected - whenever I manually change the locale from the.env file to the desired language, the language in the app also changes.However, whenever I try to change it with a button on the frontend I fail to do so.
This is what I have in my i18n.js file:
import { createI18n } from 'vue-i18n'

function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i);
  const messages = {};
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i);
    if (matched && matched.length > 1) {
      const locale = matched[1];
      messages[locale] = locales(key);
    }
  })
  return messages;
}

export default createI18n({
  legacy: false,
  locale: process.env.VUE_APP_I18N_LOCALE || 'en',
  fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
  messages: loadLocaleMessages()
})

This is in .env file:
VUE_APP_I18N_LOCALE=en
VUE_APP_I18N_FALLBACK_LOCALE=en

This is code from a tutorial I saw and they access the locale by this.$i18n.locale, however, this does not work for me, this is how I try to implement it:
<template>

Hello World

{{ t("hello") }}

{{ t("message") }}

    <button @click="SetLocale('en')">EN</button>
    <button @click="SetLocale('nl')">NL</button>

</template>

<i18n>
{
  "en": {
    "hello": "Hello i18n in English! (from component)",
  },
  "nl": {
    "hello": "Hello i18n in Dutch! (from component)",
  }
}
</i18n>

The error that I get when I click the button is:

[Vue warn]: Unhandled error during execution of native event handler
Uncaught TypeError: Cannot set properties of undefined (setting
'locale')

I have tried some other solutions like i18n.locale and this.$root.$i18n.locale but they dont seem to work either.
In addition when I try to access the {{ t("message") }} from which message comes from a JSON file from locales folder I get those warnings:

[intlify] Not found 'message' key in 'nl' locale messages.
[intlify] Fall back to translate 'message' key with 'en' locale
[intlify] Not found 'message' key in 'en' locale messages.
[intlify] Fall back to translate 'message' key with 'nl' locale

My question is, where am I doing something wrong and is there a way to get rid of the warnings that I have when I try to access the JSON files from the locales folder?


text:
Q: BaseTest class doesn't initialize the Webdriver instance I have gone through similar type Q&As, but couldn't figure out the issue in my code.
This is my BaseTest class
`
package com.supportiveTests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.cucumber.java.After;
import io.cucumber.java.Before;

public class BaseTests {
    public static WebDriver driver;

    @Before
    public void setUpDriver() {
        System.setProperty("webdriver.chrome.driver", "src/main/resources/Drivers/chromedriver.exe");
        driver = new ChromeDriver();
    }

    @After
    public void quitDriver() {
        this.driver.quit();
        System.out.println("done AfterTest");
    }
}

`
This is my stepDefinition class (LoginPageSteps)
`
package com.stepDefinitions;

import com.pageObjects.LoginPage;
import com.supportiveTests.BaseTests;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.testng.annotations.Test;

@Test
public class LoginPageSteps extends BaseTests {
    LoginPage obj_login;

    @Given("User is on Google Home page")
    public void user_is_on_google_home_page() {
        BaseTests.driver.navigate().to("https://www.google.com/");
    }

    @Given("User is navigated to SwagLabs Login page")
    public void user_is_navigated_to_swag_labs_login_page() {
        BaseTests.driver.navigate().to("https://www.saucedemo.com/");
    }

    @When("^User enters valid (.*) and (.*)$")
    public void user_enters_valid_standard_user_and_secret_sauce(String username, String password) {
        obj_login = new LoginPage(driver);
        obj_login.enterUserName(username);
        obj_login.enterPassword(password);
    }

    @When("clicks on LOGIN button")
    public void clicks_on_login_button() {
        obj_login.clickOnLogin();
    }

    @Then("User is navigated to SwagLAbs Home page")
    public void user_is_navigated_to_swag_l_abs_home_page() throws InterruptedException {
        BaseTests.driver.getCurrentUrl().contains("https://www.saucedemo.com/inventory.html");
        Thread.sleep(2000);
        BaseTests.driver.quit();
    }
}

`
This is my TestRunner class
`
package com.supportiveTests;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/Features",
        glue = {"com/stepDefinitions"},
        monochrome = true,
        plugin = {
                "pretty", "html:target/HTMLReports/report.html",
                "json:target/JSONReports/report.json",
                "junit:target/JUnitReports/report.xml"
        }
)
public class TestRunner {
}

`
This is my pageObject class (LoginPage)
`
package com.pageObjects;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {
    WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    By txt_username = By.xpath("//input[@id='user-name']");
    By txt_password = By.xpath("//input[@id='password']");
    By btn_login = By.xpath("//input[@id='login-button']");

    public void enterUserName(String username){
        driver.findElement(txt_username).sendKeys(username);
    }

    public void enterPassword(String password){
        driver.findElement(txt_password).sendKeys(password);
    }

    public void clickOnLogin(){
        driver.findElement(btn_login).click();
    }

}

When the above TestRunner class is executed, I get this error
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.navigate()" because "com.supportiveTests.BaseTests.driver" is null

    at com.stepDefinitions.LoginPageSteps.user_is_on_google_home_page(LoginPageSteps.java:16)

I went through the similar Q&As, where the solutions for driver initialization were provided, but couldn't figure out the issue. I am at basic level of Selenium testing framework, so appreciate any guidance on fixing this.


text:
Q: Set ImageURL without knowing the file extension c# I have a folder where images are uploaded and named 'Photo1', 'Photo2', etc depending on how many photos are uploaded. In another panel on the same aspx page I want to display the uploaded photos. I will know the filenames but the extension could be .png, .jpg, or .jpeg.
How can I set the ImageUrl path when I know only the filename and not the extension?
Here is an example of how I've attempted it so far--
ASPX Page Code:

<asp:Image ID="Image1" runat="server" />

Code Behind:
Image1.ImageUrl = Server.MapPath("~/RepairPhotos/" + order_id + "." + unit_id + ".RepairPhoto1.*");

This method says I've used an invalid character. Although, I've tested it by going into the folder and finding the extension then entering the line as:
Image1.ImageUrl = Server.MapPath("~/RepairPhotos/" + order_id + "." + unit_id + ".RepairPhoto1.jpg");

and that didn't work either, so there may be more wrong here than just the unknown character in the extensions place.

A:

string jpg = "~/RepairPhotos/" + order_id + "." + unit_id + ".RepairPhoto1.jpg"
string png = "~/RepairPhotos/" + order_id + "." + unit_id + ".RepairPhoto1.png"
if (File.Exists(Server.MapPath(jpg)))
{

}
else if(File.Exists(Server.MapPath(png)))
{

}

A: If you don't have the file's extension, you may need to read the first few bytes of that file to determine if an image is in what format.
This snippet may help: https://gist.github.com/ChuckSavage/dc079e21563ba1402cf6c907d81ac1ca


text:
Q: Modal Window Second time open Javascript stop i'm using kendo Ui and jbox, i can open many times kendo ui window it's working perfect. i was integrared jbox modal window on Kendo ui Window. if i open jbox modal window on kendo ui window it's too working perfect. if i don't close kendo ui window i can open many times jbox modal window it's working good. if i reopen kendo window i can open jbox modal but in jbox javascript content doesn't work properly. i thinks it's about Jquery but i can't solve .
Jquery 1.9.1 Version
here is my code,
my index;
var ICCANPopUp;
$(document).on("click", ".k-overlay", function () {
    ICCANPopUp.close();
});

$("#LoadFormDiv").kendoWindow({
    width: "750px",
    height: "90%",
    draggable: false,
    resizable: false,
    modal: true,
    title: "",
    visible: false,
    open: function(e) {
        this.wrapper.css({ top: 25 });
        $("html, body").css("overflow", "hidden");
    },
    close: function (e) {
        $("html, body").css("overflow", "");
    }

});
$('#LoadFormDiv').closest(".k-window").css({
    position: 'fixed',
    margin: 'auto',
    top: '20%'
});

var ICCANPOPUPLOCATIONBEFOREOPEN;
function ICCANPopUpShow() {
    ICCANPopUp = $("#LoadFormDiv").data("kendoWindow");
    ICCANPopUp.content('
Yükleniyor...

');
    ICCANPopUp.title("");
    ICCANPopUp.refresh({
        url: "/IccanApi/GetProductByID",
        data: { ID: 3012 }
    });

    ICCANPOPUPLOCATIONBEFOREOPEN = $(window).scrollTop();
    window.scrollTo(0,0);
    ICCANPopUp.center().open();
}

$("#LoadFormDiv").data("kendoWindow")
.bind("close", function (e) {
    $("html, body").animate({ scrollTop: ICCANPOPUPLOCATIONBEFOREOPEN });

});

kendo ui window script's
$('#FavouriteWrp').jBox('Modal', {
  width: 602,
  height: 495,
  closeButton: true,
  ajax: {
    url: '/Account/Login',
    data: '',
    reload: true
   },
   onClose: function () { ResetAllLoginStuff(); }
});

Jbox Modal Window Conent Script,(if i close and reopen kendo window and after if i open jbox modal window this codes not working)
$("form").submit(function (e) {
        $(".ICCAN-Register-processing").css({ "display": "block" });
        var emailForRegister = $("#UserName").val();
        var passwordForRegister = $("#Password").val();
        var passwordValidateForRegister = $("#PasswordValidate").val();
        var smsForRegister = $('#Sms').prop('checked');
        var mailingForRegister = $('#Mailing').prop('checked');
        var agreementForRegister = $('#agreement').prop('checked');

        $.ajax({
            url: '/Account/Register',
            data: JSON.stringify({
                UserName: emailForRegister,
                Password: passwordForRegister,
                PasswordValidate: passwordValidateForRegister,
                Sms: smsForRegister,
                Mailing: mailingForRegister,
                agreement: agreementForRegister
            }),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                if (response.isSuccess) {

                    alert("Kayıt Başarılı");
                    $(".ICCAN-Register-processing").css({ "display": "none" });
                    window.location.replace("/");

                }
                if (!response.isSuccess) {
                    $(".ICCAN-Register-processing").css({ "display": "none" });
                    $("#UserName").css({ "border": "1px solid red" });
                    $("#ResultText").show();
                }
            }
        });
        e.preventDefault();
        e.unbind();
    });
    $("#ResultText").hide();

can somebody help me, thanks a lot

A: When i refreshed page i saw conflict jquery versiob, so i use newest version of jquery and problem is gone.


text:
Q: Remove empty sets from a dict inside a list (python 2.7) So I have some dicts which looks something like this
clue={"number":set([i,j]), "var2":x[i]<0.03 or x[j]<0.03, "var3":x[i]>0.97 or x[j]>0.97, "var4":v4}

etc.
clue={"number":set([k,l]), "var2":x[i]<0.03 or x[j]<0.03, "var3":x[i]>0.97 or x[j]>0.97, "var4":v4}

etc.
I created a list of these dictionaries list(clue) because I needed to sort them and join some of the values together, so for example:
clue={"number":set([i,j,k,l]), "var2":True, "var3":False, "var4":v4}

etc.
clue={"number":{}, "var2":True, "var3":False, "var4":v4}

etc.
Now because I have a list(clue) the following operation becomes difficult: I want to delete all dict entries from my list(clue) which have the set {} for number. i.e. The dicts with "number:{}" are worthless (regardless of the other key, values) and are just cluttering up everything else and I want rid of them.
I would like to make it clear that I want to get rid of the whole dict entry with number:{} rather than just the key from that specific dict.
Using Python 2.7
Thanks

A:
I want to delete all dict entries from my list(clue) which have the
  set {} for number. i.e. The dicts with "number:{}" are worthless
  (regardless of the other key, values) and are just cluttering up
  everything else and I want rid of them.

filtered_clue = filter(lambda x: len(x['number']), clue)


text:
Q: add functional icon in google map link that i want to email I have spent hours searching for the answer, forgive me if it was right in front of me.
I want to send an email with a google map link
http://maps.google.com/maps?q=address
(I got this from an answer in stackoverflow.)
In his iphone, the reader taps the link in the email, the map opens,
The reader taps Directions, then Route,
And the route, time and distance appear in the map from the reader's current location to the map address above.
Now – I want to include an icon visible on a corner of the map view that reads "I'll be there."     When the reader taps that icon in the map, the end result is the reader responds in the email to the sender "I'll be there."
How hard is this to program?
The intermediary physical steps are  - Tap main iphone button to main screen.   Tap email.   Tap respond arrow.   Tap Reply.   Type "I'll be there."   Tap Send.

A: You will want to look at embedding a map into your own web page using the Google Maps v3 API. The link in your question is a web page rendered by Google. You will want to control the rendering to add your button. I don't know of any other way.
Bob
[Update] Here is a jsFiddle using the API to render a map. http://jsfiddle.net/JsAJA/3/


text:
Q: == check on two fields elasticsearch I have scenario like where need to check two fields equality.
Assume i have an index my_index with mapping
    "field_one": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          },
          "regexkeyword": {
            "type": "keyword",
            "normalizer": "lowercase_normalizer"
          }
        },
        "analyzer": "simple"
      },
     "field_two": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          },
          "regexkeyword": {
            "type": "keyword",
            "normalizer": "lowercase_normalizer"
          }
        },
        "analyzer": "simple"
      }

Here i need to write a query to get the data by matching field_one and field_two
Here is what i tried
 {
 "script_fields": {
     "adas": {
        "script": {
           "inline": "'field_one.keyword' == 'field_two.keyword'",
           "lang": "painless"
         }
     }
 }

Note : Elastic version : 5.5.3

A: I think the syntax is, but I have no instance in ES .X to test it
{
 "script_fields": {
     "adas": {
        "script": {
           "inline": "doc['field_one.keyword'].value == doc['field_two.keyword'].value",
           "lang": "painless"
         }
     }
 }


text:
Q: Convert sqlclient.h to swift I'm trying to access a SQL Server with swift SQLClient.h Already using classes I access the classes, but I can not translate the objective-c code to swift. The original code is this:
SQLClient* client = [SQLClient sharedInstance];
client.delegate = self;
[client connect:@"server:port" username:@"user" password:@"pass" database:@"db" completion:^(BOOL success) {
    if (success)
    {
      [client execute:@"SELECT * FROM Users" completion:^(NSArray* results) {
        for (NSArray* table in results)
          for (NSDictionary* row in table)
            for (NSString* column in row)
              NSLog(@"%@=%@", column, row[column]);
        [client disconnect];
      }];
    }
}];

Could anyone make a swift? .I Am unable. I get errors with the completion
I got this:
var client = SQLClient()
client.delegate = self
client.connect("172.29.XX.XX:1433", username: "XX", password: "XXXX", database: "XXX", completion: {(success:Bool) -> Void in

    if success
        {
            client.execute("SELECT * FROM Users" , completion: {(results:NSArray) ->  Void in

                for (table:NSArray in results)
                for (row:NSDictionary in table)
                for (column:NSString in row)
                    NSLog(@"%@=%@", column, row[column])

            client.disconnect

            } )
        }

})

Thank you very much

A: A couple of observations:

*

*In your Objective-C code sample, you're using the singleton, so I assume you should do that in the Swift code, too:
let client = SQLClient.sharedInstance()

You can also use let instead of var. Always favor immutability over mutability. Only make it mutable where you need it to be mutable.

*Your for loops:

*

*require braces

*don't need the parentheses around the expression of the for loop, though

*the for loop of a dictionary in Swift returns a tuple including both the key and the value (in Objective-C it was just the key)

*When you call disconnect, that's a function, so I'd include the ().

*You can use NSLog if you want, but in Swift we often use println. But instead of printf-style formatters, we'd generally use string interpolation (e.g. "value = \(variable)" where the value of variable will be inserted in that string.

*As a minor observation, I'd be inclined to adopt the trailing closure syntax (which gets rid of those completion parameters, converted to just a closure after the function) and use implied types to clean up the code sample.
Pulling that all together, that yields something like:
let client = SQLClient.sharedInstance()

client.delegate = self
client.connect("172.29.XX.XX:1433", username: "XX", password: "XXXX", database: "XXX") {
    success in

    if success {
        client.execute("SELECT * FROM Users") {
            results in

            for table in results as NSArray {
                for row in table as NSArray {
                    for column in row as NSDictionary {
                        println("\(column.key) = \(column.value)")
                    }
                }
            }

            client.disconnect()
        }
    }
}

Or, possibly something like:
let client = SQLClient.sharedInstance()

client.delegate = self
client.connect("172.29.XX.XX:1433", username: "XX", password: "XXXX", database: "XXX") {
    success in

    if success {
        client.execute("SELECT * FROM Users") {
            results in

            for table in results as [[[String:AnyObject]]] {
                for row in table {
                    for (columnName, value) in row {
                        println("\(columnName) = \(value)")
                    }
                }
            }

            client.disconnect()
        }
    }
}

A: class ViewController:  UIViewController,SQLClientDelegate

func error(error: String, code: Int32, severity: Int32) {
    println(error)
}

A: sharedInstance() is a anyObject, you have to set client as a SQLclient in order to be able to set de delegate to self:
let client = SQLClient.sharedInstance() as! SQLClient


text:
Q: C - Investigating stack and heap contents program How would I go about writing a C program that lists ALL the contents of stack and heap including its own variables and mallocations ?
The purpose of it is for me to be able to see what's going on in the memory as I write and test code.

A: The c standard doesn't explicitly mention a stack or a heap. That, along with the fact that variable and function names are compiled out, means that your task is impossible.
You could build your own compiler which would effectively be a debugging tool. But that would be ridiculous as such a thing would take a long time to build and you'd have to adapt it constantly as the standard evolves. Or you could use the output of a compiler that generates debugging symbols.
Better still, learn to use a good debugger.


text:
Q: how to insert a new li after three each li in jquery I want to insert a li tag in after each third li tag using jquery how can we handle this. Consider the following example i have nine li items

1 element

2 element

3 element

4 element

5 element

6 element

7 element

8 element

9 element

1 element

2 element

3 element

item inserted

4 element

5 element

6 element

item inserted

7 element

8 element

9 element

item inserted

A: You can use :nth-child to target every 3,6,9...n element. and insert new content after matched elements:

$('
item inserted
').insertAfter($('li:nth-child(3n+3)'));

1 element

2 element

3 element

4 element

5 element

6 element

7 element

8 element

9 element

A: Try this: add li before li for which index divided by 3, see below code

$(function(){
  $('ul li').each(function(i){
     if(i!=0 && i%3==0)
        $(this).before('
Insert here
');
  });
});

1 element

2 element

3 element

4 element

5 element

6 element

7 element

8 element

9 element

A: try this
$("ul li:nth-child(3n)").append("
item inserted
")

A: You can check the code below.
<!Doctype html>

1 element

2 element

3 element

4 element

5 element

6 element

7 element

8 element

A: Try this!
$(document).ready(function() {
    $(function(){
        $('ul li').each(function(i){
            var j = i +1;
            if(j!=0 && j%3==0) {
                $(this).after('
Insert here
');
            }
        });
    });
});


text:
Q: Scala Programming for Android I have followed the tutorial at Scala and Android with Scala 2.7.3 final. The resulting Android App works but even the most basic application takes several minutes (!) to compile and needs 900 kb compressed, which is a show stopper for mobile applications. Additionally, the IDE runs out of memory every now and then. I assume dex is not made for big libraries like the scala-library.

*

*So my question is: Has anyone actually done this and is there any cure for this?

A: Developing Android apps for Scala is continuously evolving. The current best way to do it appears to SBT in conjunction with the android-sdk-plugin, which is maintained* and works well for me in my Scala/Android project. A somewhat recent example that demonstrates the use of this plugin with the already mentioned Scaloid can also be found.
Please note that this question is a typical example of a question with outdated answers on Stack Overflow. This answer will likely become outdated at some point as well.
* The other SBT based projects mentioned in this answer thread don't appear to have code being written for them in the last six months at the time of writing. They may have compatibility issues with newer versions of Scala and SBT.

A: If you use maven, use android-scala-test as a startup template. It works great for me out-of-the-box.
Scaloid is an Android API wrapper written in Scala that help you to write your Android program in Scala-style.

A: You can now use the Android plugin for Gradle to create Android applications in Scala.  It incorporates the ProGuard tool to trim the fat from the resulting APK file, so seems to meet your needs.
https://github.com/jvoegele/gradle-android-plugin/wiki

A: You can use the Scala on Android without SBT, it built externally by Gradle to create Android applications.
https://github.com/yareally/android-scala-intellij-no-sbt-plugin
Gradle is more native building tool for android than SBT.
There is good example of Scala client and server side solution concept, and gradle building tool as advance for IntelliJ IDEA workbench.
Big advance that core classes are common for client and server.
https://github.com/ghik/akkdroid
Good tutorial for IDEA and android-plugin:
http://fxthomas.github.io/android-plugin/

A: The biggest issue with Scala on Android is the compile times.
Possibly because of the Proguard class stripping compiles with IDEA13/Scala plugin on a Dual Quad Core (8-CPU) E5450 Xeon with 8GB can take two minutes or more.
I simply moved back to Java after completing a largish Scala Android project as compile times were too frustrating.

A: There is also an plugin for the Scala-based builder sbt: sbt-android-plugin.

A: For tutorials and examples, see also Stéphane Micheloud's "Exploring Android" page: http://lamp.epfl.ch/~michelou/android/

A: I verified this detailed solution with Eclipse 3.7, Scala 2.10 and the plug-in AndroidProguardScala v50:
https://stackoverflow.com/a/11084146/1287856
Everything works fine. A simple test application with scalafied main activity class only takes 38Kb. Libraries projects are supported. Proguard is activated when exporting the project.

A: I've written some basic Android applications in Scala, nothing too epic.  Not being a Java programmer I was suggested to use a "treeshake", I was explained by a friend that this strips out all the unnecessary libraries from the jar files.
I have not documented it, but I found that someone else already has:
http://chneukirchen.org/blog/archive/2009/04/programming-for-android-with-scala.html
Proguard is not the only solution, you might find something that suits your work flow or is more suited for your environment.
Additionally google have just realised JACK , which deals with quite a lot of reducing build and memory times see https://source.android.com/source/jack.html


text:
Q: Update account with verification document I created an account using createToken (client side JS)
I want to update the verification document for that account.
I have successfully uploaded a file and obtained a fileId
I am trying to attach it to the account. I am using .net server side
I have done this:
  var options = new AccountUpdateOptions
        {
             Individual = new PersonUpdateOptions()
             {
                 Verification = new PersonVerificationOptions()
                 {
                     Document = new PersonVerificationDocumentOptions() { FrontFileId = fileId}
                 }
             }
        };

        var service = new AccountService();
        Account account = service.Update(accountId, options);

However, this does not work, I get the error:

This account can only be updated with an account token, because it was
  originally created with an account token. (Attempted to update param
  'individual' directly.)

Am I supposed to save the token created in my db for each account in order to update?
Also how then should i update the account?

A: Assuming that you are using Custom connected accounts, you'll want to follow the steps in Using Connect with Custom Accounts.
As recommended there:

Store the received account ID. You need this information to perform
  requests on the user's behalf.

The account id will be in the form of acct_**********.


text:
Q: Can't pass objects returned by Observable as input component Angular 5 I have a small component where I have only one input
Ts component Code
 @Input() variables;

      ngOnInit() {
        console.log(this.variables);
    }

Where I use my component TS
envVars$: Observable<{
            names: String[],
            values: {}
          }>;

Where I use my component HTML
 <app-code  [variables]="(envVars$ | async)?.values | json"></app-code>

In the console log I HAVE NULL though my object is full

A: the log says null because you're logging ON INIT before the object has been asynchronously defined. The async pipe is working exactly as intended. if you need the object to be defined on init then you need to change your structure a little.
do this instead to ensure the observable is populated prior to component instantiation:
<app-code *ngIf="envVars$ | async as enVars" [variables]="envVars.values | json"></app-code>

the ngIf here tells angular to not instantiate the component until envVars$ emits a value.


text:
Q: tengo problemas con parámetros por valor y referencia y recursividad Sólo pido que me ayuden en como crear la función y que me compile para sacar la raíz de polinomio, ya que al momento de solicitar datos en la función no me deja.
Éste es el código, todo esta bien sólo me falta crear la función para hacer la raíz.
Agradecería que me orientaran para saber cuál es mi error o como hacer bien la sintaxis al momento de crear la función de manera correcta.
mi error va al momento de crear una funcion leer los datos a,b,c en la funcion raiz de polinomio y retornar el resultado, eh puesto mi propia idea pero al crear la funcion pero algo falla, solo pido que me orienten para saber como resolverlo
#include<iostream>
#include <stdio.h>
#include <conio.h>
#include <cmath>

// declarar protitipos de funciones AQUI
int raizdepolinomio(float &a, float &b, float &c);
int fibonacci( int j);
main()
{
   int x,n,op;
   float X1,X2,a,b,c;

   op=1;
   while(op!=3){
        printf("\n -- MENU DE OPCIONES --");
        printf("\n 1) Calcular 2 raices de un polinomio cuadrado");
        printf("\n 2) Calcular un numero de la serie de FIBONACCI");
        printf("\n 3) TERMINAR y SALIR");
        printf("\n ingrese numero de opción:-> ");
        scanf("%d",&op);
        switch(op){
            case 1:
                printf("\n... Calculando raices de un polinomio cuadrático");
                printf("\n se usara la formula general INGRESE LOS 3 COEFICIENTES");
                printf("\n ingrese coneficiente a: ");
                scanf("%f",&a);
                printf("\n ingrese coneficiente b: ");
                scanf("%f",&b);
                printf("\n ingrese coneficiente c: ");
                scanf("%f",&c);
                X1=raizdepolinomio(a,b,c);
                X2=a;
                printf("\n ... las 2 raices del polinomio son: ");
                printf("\n X1= %f y X2= %f \n",X1,X2);
                break;
            case 2:
                printf("\n... Calculando el numero N de la serie de FIBONACCI");
                printf("\n se usara una función recursiva");
                printf("\n ingrese el numero N a calcular: ");
                scanf("%d",&x);
                n=fibonacci(x);
                printf("\n El N numero de la serie de fibonacci es:-> %d",n);
                break;
            case 3:
                printf("\n seleccionó salir, el programa TERMINARÁ ");
                break;
            default:
                printf("\n Error... ha seleccionado una opcion incorrecta, intente de nuevo");
        }
   }
   printf("\n PROGRAMA TERMINADO ... pulse [enter]");
   getch();

}

// PROGRAMAR LAS FUNCIONES AQUI
int raizdepolinomio(float &a, float &b, float &c){
    float r,p,i;
    r = ((b*b)-(4*b*c));
    p = 2*a;
    i = -b + sqrt(r)/2*a;
    a=i;
}

A: cambia tu declaración de int raizdepolinomio(...) como float[] raizdepolinomio(...)
En tu método
// PROGRAMAR LAS FUNCIONES AQUI
float raizdepolinomio(float &a, float &b, float &c){
   float[2] raices;
   float r,p,i;
   r = ((b*b)-(4*b*c));
   p = 2*a;
   i = -b + sqrt(r)/2*a;
   raices[0] = i;
   i = -b - sqrt(r)/2*a;
   raices[1] = i;
   return raices; // no olvides poner tu return, luego en tu main solo lee el valor 0 y 1 del array.
}


text:
Q: SQL where condition return all records I have one PHP model function (far more complicated than this one in example). The example is only to simplify things.
public function findProduct($size, $material, $category) {
    $sql = new Sql($this->dbAdapter);
    $select = $sql->select(array('p' =>'products'));
    $select->where(array('size'=>$size, 'material'=>$material,'category'=>$category));
 }

The function works of course. Now, I would like to use the same function in case when I don't need $material query (when I want products for all materials).
Is there any value which I could put in $material=?; to get products for all materials in db table?That's what would suit me the best.
The solution when i put $material =''; and then in function check
if($material =='') {
    $select->where(array('size'=>$size, 'category'=>$category));
 } else {
    $select->where(array('size'=>$size, 'material'=>$material,'category'=>$category));
}

complicates function (which is already enough complicated and long) and I don't want to use.