text:
Q: Serialize multidimensional form data into a JSON object-array to work with application/json I am building a Laravel application. In the back-end, the $controller->wantsJson() method is TRUE if the content type of the request is application/json. So, to satisfy this, my jQuery AJAX call is this.
jQuery.ajax({
    type:        "POST",
    method:      "PUT",
    url:         $form.attr('action'),
    data:        $form.serialize(),
    dataType:    "json",
    contentType: "application/json; charset=utf-8"
})

This correctly triggers the wantsJson() response I need. The problem then is that jQuery cannot supply POST data as an application/json correctly. It tries to write it as a query string, which doesn't work for the PHP backend when it receives that content type.
To satisfy this, I need to stringify a JavaScript object-array into the data field.
JSON.stringify(dataObj)

So now the problem is, I don't have a concise way of turning a multidimensional form into an object-array. If I just try to convert the output of $.serializeArray(), I get this, which isn't able to be interpreted by the backend.
{
    'something' : 1,
    'field[foo]' : 2,
    'field[bar][]' : "a",
    'field[bar][]' : "b",
    'field[bar][]' : "c",
}

And that of course doesn't work. I need some sort of RegEx parser that can convert this form ...
<input name="something" value="1" />
<input name="field[foo]" value="2" />
<input name="field[bar][]" value="a" />
<input name="field[bar][]" value="b" />
<input name="field[bar][]" value="c" />

Into ...
{
    'something' : 1,
    'field'     : {
        'foo'   : 2,
        'bar'   : [
            'a',
            'b',
            'c',
        ]
    }
}

You'd expect something like this to exist already, but I can't find anything satisfactory.

A: I had the same problem but this package did the trick: jQuery Serialize Object
It's easy to use, just call this on your form (after loading the script)
$('form#contact').serializeJSON(); // to get the form as a JS object

A: I agree with @mdamia
Here is the snippet with more detail.
After JSON.stringify(dataObj); You will get a json string as below:
JSON:
[
   {
      "name":"something",
      "value":"1"
   },
   {
      "name":"field[foo]",
      "value":"2"
   },
   {
      "name":"field[bar][]",
      "value":"a"
   },
   {
      "name":"field[bar][]",
      "value":"b"
   },
   {
      "name":"field[bar][]",
      "value":"c"
   }
]

PHP Code:
<?php
//your raw json string
$rawData = '[{"name":"something","value":"1"},{"name":"field[foo]","value":"2"},{"name":"field[bar][]","value":"a"},{"name":"field[bar][]","value":"b"},{"name":"field[bar][]","value":"c"}]';

$json = json_decode($rawData);

$string = '';
foreach($json as $key => $val){
    $string .= $val->name.'='.$val->value.'&';
}

parse_str(rtrim($string,'&'),$data);

//var_dump($data);
echo json_encode($data); //your requied data
?>

//Output
{
   "something":"1",
   "field":{
      "foo":"2",
      "bar":[
         "a",
         "b",
         "c"
      ]
   }
}

A: You can use  PHP parse_str

parse_str — Parses the string into variables

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

Hope this help.


text:
Q: Bit Manipulation (extract 5th bit from X and return number of 1 bits in X) Assume X is an unsigned integer how will I be able to extract the 5th bit from X and return the number of 1 bits in X. Note: these two operations don't depend on each other.
For extracting the 5th bit from X I was thinking to use the & operation to do something like this: XXXX1X & 000010
I am not really sure how to do the return the number of 1 bits in X.
Thanks!

A: Counting the number of 1-bits is relatively straightforward; you iterate over all of the bits of your number and add to some accumulator the number of bits that are set:
unsigned int X;
unsigned int count;

for (count = 0; X; X >>= 1) {
   count += X & 1;
}

How it works:

*

*Initialize count to 0

*Start from the MSB (most significant bit) [this is the current bit]

*Add to count the result of the current bit & 1

*

*1 if the bit is set

*0 if the bit is not set

*Shift X to the right 1 bit, so the current bit is now the next MSB

*Repeat step 3

Extracting the 5th bit is also straightforward, simply right shift your number X by 5 and compute the logical AND with 1:
unsigned int fifthBit (unsigned int X) {
   return (X >> 5) & 1;
}

A: A shorter and simpler way to find number of set bits in an int is following:
int num_1_bits(unsigned int x)  // or unsigned long x; or unsigned short x;
{
   int bitcount = 0;
   while(x)
   {
      x &= (x - 1);
      ++bitcount;
   }
   return bitcount;
}

How does this work?
For an unsigned number x, the sequence of bits in x - 1 will be the complement of x till the first set bit of x counted from LSB.
i.e. for x = 20 [0b11100];     x - 1 = 19 [0b11011]
Here Bit sequence of 19 is complement of 20 till first set bit in 20 (first set bit at position 3 from LSB).
Therefore,
if you do x & (x - 1), this operation will consume one set bit from x.
Hence,
if you want to continue doing this until x becomes 0, you will need to do it as many times as there are set bits in x, which in turn will give you the count of set bits in x.
This method is better because the loop will run only as many times as there are 1 bits in x and hence doesn't depend on datatype of x.

A: As a complement, I precise that if you are looking for efficiency there are some built-in hardware instructions to perform computations on bits (counting zeros: you can deduce how many 1-bit you have then) see this article as an example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image (Error) reduce.median: Can't apply calendarRange filter to objects without a timestamp I tried illumination correction on Sentinel-2 images and obtain monthly median images.
However, I'm struggling with the following error:
Image (Error) reduce.median: Can't apply calendarRange filter to objects without a timestamp.
Could you look at my code and help me.
I tried these two methods.
return img_plus_ic.set('system:time_start',img.get('system:time_start'));

return img_plus_ic.copyProperties(img);

But they did not work.
Full code below (Also here, https://code.earthengine.google.com/c3a6647a1013ffcebcbe750ac7b07a5a)
var roi = ee.Geometry.Polygon([[[-115.51858045584667, 45.29650713146457],
          [-115.51858045584667, 44.2632748294202],
          [-113.60146619803417, 44.2632748294202],
          [-113.60146619803417, 45.29650713146457]]], null, false);
Map.centerObject(roi);
Map.addLayer(roi);

function cloud_mask(image) {
  var qa = image.select('QA60');
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(
             qa.bitwiseAnd(cirrusBitMask).eq(0));
  var out = image.updateMask(mask).divide(10000)
      .select("B.*")
      .copyProperties(image);
  return out;
  }

var dem = ee.Image("USGS/SRTMGL1_003");

function topoCorr_IC(img){

  // Extract image metadata about solar position
  var SZ_rad = ee.Image.constant(ee.Number(img.get('MEAN_SOLAR_ZENITH_ANGLE'))).multiply(3.14159265359).divide(180).clip(img.geometry().buffer(10000));
  var SA_rad = ee.Image.constant(ee.Number(img.get('MEAN_SOLAR_AZIMUTH_ANGLE')).multiply(3.14159265359).divide(180)).clip(img.geometry().buffer(10000));
  // Creat terrain layers
  var slp = ee.Terrain.slope(dem).clip(img.geometry().buffer(10000));
  var slp_rad = ee.Terrain.slope(dem).multiply(3.14159265359).divide(180).clip(img.geometry().buffer(10000));
  var asp_rad = ee.Terrain.aspect(dem).multiply(3.14159265359).divide(180).clip(img.geometry().buffer(10000));

  // Calculate the Illumination Condition (IC)
  // slope part of the illumination condition
  var cosZ = SZ_rad.cos();
  var cosS = slp_rad.cos();
  var slope_illumination = cosS.expression("cosZ * cosS",
                                          {'cosZ': cosZ,
                                           'cosS': cosS.select('slope')});
  // aspect part of the illumination condition
  var sinZ = SZ_rad.sin();
  var sinS = slp_rad.sin();
  var cosAziDiff = (SA_rad.subtract(asp_rad)).cos();
  var aspect_illumination = sinZ.expression("sinZ * sinS * cosAziDiff",
                                           {'sinZ': sinZ,
                                            'sinS': sinS,
                                            'cosAziDiff': cosAziDiff});
  // full illumination condition (IC)
  var ic = slope_illumination.add(aspect_illumination);

  // Add IC to original image
  var img_plus_ic = ee.Image(img.addBands(ic.rename('IC')).addBands(cosZ.rename('cosZ')).addBands(cosS.rename('cosS')).addBands(slp.rename('slope')));
  return img_plus_ic.copyProperties(img, ["system:time_start"]);
}

var S2 = ee.ImageCollection("COPERNICUS/S2")
                              .filterDate("2019-01-01", "2019-12-31")
                              .filterBounds(roi)
                              .map(cloud_mask)
                              .map(topoCorr_IC);

var m1 = S2.filter(ee.Filter.calendarRange(1, 31, 'day_of_year')).median();

print (m1);

Image (Error) reduce.median: Can't apply calendarRange filter to objects without a timestamp.

A: The cloud masking, at line 18, is discarding the system:time_start property (by default system properties aren't copied).  Add another copy_properties to catch it:
var out = image.updateMask(mask).divide(10000)
    .select("B.*")
    .copyProperties(image)
    .copyProperties(image, ["system:time_start"])

or better, just replace the bands in the original image with the scaled ones and don't fiddle with properties at all:
function cloud_mask(image) {
  var qa = image.select('QA60')
  var cloudBitMask = 1 << 10
  var cirrusBitMask = 1 << 11
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(
             qa.bitwiseAnd(cirrusBitMask).eq(0))
  var scaled = image.select("B.*").updateMask(mask).divide(10000)
  return image.addBands(scaled, null, true)
}


text:
Q: Why positive definite matrix implies minimum? Suppose $f(x) = x^TAx$. Why $x^TAx >0$ implies that  $f$ has a minimum?

A: I assume that $A$ is understood to be symmetric and that the underlying space is $\mathbb{R}^d$. Then there is an orthonormal basis $\left\{\mathbf{e}_i\right\}_{i=1}^d$ for $\mathbb{R}^d$, such that each $e_i$ is an eigenvector of $A$. Denote the corresponding eigenvalue by $\lambda_i$. We show that $f$ is strictly convex.
Let $0 < \mu < 1$ and consider $f(\mu x + (1-\mu)y)$ with $x \neq y$. Then $$f(\mu x + (1-\mu)y) = \left\langle \mu x + (1-\mu)y , A  \left( \mu x + (1-\mu)y \right) \right\rangle = \left\langle \sum \limits_{i=1}^d \mu x_i \mathbf{e}_i + (1-\mu)y_i \mathbf{e}_i , A \sum \limits_{i=1}^d \mu x_i \mathbf{e}_i + (1-\mu)y_i \mathbf{e}_i  \right\rangle \\= \sum \limits_{i=1}^d \lambda_i \left(\mu x_i + (1-\mu)y_i \right)^2$$
Since $x_i \neq y_i$ for some $i$ and $x^2$ is strictly convex $$\sum\limits_{i=1}^d \lambda_i \left(\mu x_i + (1-\mu)y_i \right)^2 <\sum\limits_{i=1}^d \lambda_i \left(\mu x_i^2 + (1-\mu)y_i^2 \right) = \mu f(x) + (1-\mu)f(y). $$
Thus $f$ is strictly convex.
Clearly as $\left\| x \right\| \to \infty$, then $f(x) \to \infty$. Thus $f$ is strictly convex "coercive" function and attains its infimum, or in other words has a unique minimizer in $\mathbb{R}^d$.


text:
Q: Pivoting , Dynamic columns in SQL Server I have tables like these
LoanPrograms
Id  Name
------------
1   LP1
2   LP2
3   LP3

Channels
Id  Name
----------
4  Channel1
5  Channel2
6  Channel3

LoanProgramsChannels
LoanProgramId      Channelid
----------------------
1                   4
1                   5
2                   4

I wanted to get data like these
LoanProgarmNames   channel1 channel2  channel3
----------------   -------- --------  --------
LP1                 y            y       N
LP2                 y            N       N
LP3                 N            N       N

I am quite new to SQL, I know I have to use PIVOT to achieve these, but not sure how can I achieve in these scenario. Can anybody help on this ?

A: Because you need to "fill in the gaps" the best way is to create a cartesian product using a CROSS JOIN:
;WITH CTE AS (
SELECT A.NAME AS LOANPROGRAMNAME
, B.NAME AS CHANNELNAME
, CASE WHEN C.CHANNELID IS NULL THEN 'N' ELSE 'Y' END AS LOANPROGRAMCHANNELS
FROM LOANPROGRAMS AS A
CROSS JOIN CHANNELS AS B
LEFT JOIN LOANPROGRAMSCHANNELS AS C
ON CAST(A.ID AS VARCHAR)+CAST(B.ID AS VARCHAR) =
CAST(C.LOANPROGRAMID AS VARCHAR)+CAST(C.CHANNELID AS VARCHAR))
SELECT LOANPROGRAMNAME, [CHANNEL1], [CHANNEL2], [CHANNEL3]
FROM CTE
PIVOT(MAX(LOANPROGRAMCHANNELS) FOR CHANNELNAME IN ([CHANNEL1], [CHANNEL2], [CHANNEL3])) PIV

Once you've got the condition (Y/N) you can pivot the required columns, as done here.

A: There might be better ways to code this, but I believe the following will provide what you want:
declare @tbLoanPrograms table (
    ID int, Name varchar(12)
)

insert into @tbLoanPrograms (
    ID      , Name
)
values    (1, 'LP1')
        , (2, 'LP2')
        , (3, 'LP3')

declare @tbChannels table (
    ID int, Name varchar(12)
)

insert into @tbChannels (
    ID      , Name
)
values    (4, 'Channel1')
        , (5, 'Channel2')
        , (6, 'Channel3')

declare @tbLoanProgramsChannels  table (
    LoanProgramId int, Channelid int
)

insert into @tbLoanProgramsChannels (
    LoanProgramId      , Channelid
)
values    (1, 4)
        , (1, 5)
        , (2, 4)

select
    t.Name
    , Channel1 = max(Channel1)
    , Channel2 = max(Channel2)
    , Channel3 = max(Channel3)
from (
    select
        lp.Name
        , Channel1 =
                case
                when lpc.LoanProgramId is not null and lpc.Channelid = 4
                    then 'y'
                else 'N'
            end
        , Channel2 =
            case
                when lpc.LoanProgramId is not null and lpc.Channelid = 5
                    then 'y'
                else 'N'
            end
        , Channel3 =
            case
                when lpc.LoanProgramId is not null and lpc.Channelid = 6
                    then 'y'
                else 'N'
            end
    from
        @tbLoanPrograms lp
        left join @tbLoanProgramsChannels lpc on lpc.LoanProgramId = lp.ID
        left join @tbChannels c on c.ID = lpc.Channelid
) t
group by t.Name


text:
Q: Melhor forma de cadastrar duas chaves estrangeiras em uma tabela Possuo 3 tabelas, sendo elas: pessoa_fisica, pesso_juridica e endereco.
Tanto a tebela pessoa_fisica, quanto a tebela pessoa_juridica usam a tabela endereco. Gostaria de adicionar duas chaves estrangeiras na tabela endereço. Sendo uma vinculada ao id de pessoa_fisica e outra ao id de pessoa_juridica. Assim, caso um registro de pessoa_fisica ou pessoa_juridica seja excluído, o endereço também será.
O meu problema é que o MySQL não permite que eu cadastre um registro na tabela endereco se não existir a referencia das chaves estrangeiras nas tabelas pessoa_fisica e pessoa_juridica.
Existe alguma forma de tratar isso sem que seja necessário criar duas tabelas de endereco (sendo uma para pessoa_fisica e outra para pessoa_juridica)?

A: Você tem que criar na tabela 2 chaves estrangeiras podendo elas serem nulas,
Exemplo do create das tabelas:
CREATE TABLE IF NOT EXISTS forum.pessoa_fisica (
  id INT NOT NULL AUTO_INCREMENT,
  nome VARCHAR(60) NOT NULL,
  cpf VARCHAR(15) NOT NULL,
  PRIMARY KEY (id))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS forum.pessoa_juridica (
  id INT NOT NULL AUTO_INCREMENT,
  razao_social VARCHAR(255) NOT NULL,
  cnpj VARCHAR(30) NOT NULL,
  PRIMARY KEY (id))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS forum.endereco (
  id INT NOT NULL AUTO_INCREMENT,
  id_pessoa_juridica INT NULL,
  id_pessoa_fisica INT NULL,
  rua VARCHAR(255) NOT NULL,
  numero VARCHAR(10) NOT NULL,
  PRIMARY KEY (id),
  INDEX fk_endereco_pessoa_juridica_idx (id_pessoa_juridica ASC),
  INDEX fk_endereco_pessoa_fisica1_idx (id_pessoa_fisica ASC),
  CONSTRAINT fk_endereco_pessoa_juridica
    FOREIGN KEY (id_pessoa_juridica)
    REFERENCES forum.pessoa_juridica (id)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT fk_endereco_pessoa_fisica1
    FOREIGN KEY (id_pessoa_fisica)
    REFERENCES forum.pessoa_fisica (id)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

Aqui irei inserir nas tabelas 1 dado fake para cada tabela
INSERT INTO pessoa_fisica(nome, cpf)VALUES('PessoaFisica', '00000000000');
INSERT INTO pessoa_juridica(razao_social, cnpj)VALUES('PessoaJuridica', '000000000000000');
INSERT INTO endereco(id_pessoa_fisica, rua, numero) VALUES(1,'Rua Pessoa Física', '1');
INSERT INTO endereco(id_pessoa_juridica, rua, numero) VALUES(1,'Rua Pessoa Juridica', '2');

Para consultar os endereços das pessoas fisicas e juridicas usamos as seguintes querys:
/** CONSULTA ENDERECO PESSOA FISICA ID 1*/
SELECT
    pf.nome,
    pf.cpf,
    e.rua,
    e.numero
FROM pessoa_fisica pf
LEFT JOIN endereco e
ON e.id_pessoa_fisica = pf.id
WHERE pf.id = 1;

/** CONSULTA ENDERECO PESSOA JURIDICA ID 1*/
SELECT
    pj.razao_social,
    pj.cnpj,
    e.rua,
    e.numero
FROM pessoa_juridica pj
LEFT JOIN endereco e
ON e.id_pessoa_fisica = pj.id
WHERE pj.id = 1;

Porém não é a melhor forma de modelagem, as tabelas pessoas_fisicas e pessoas_juridicas deveriam ser apenas 1 tabela onde existiriam referencia com tipo pessoa porque tem muitas colunas que podem ser iguais, e caso existisse algo a mais em alguma tabela, você criaria outras tabelas com essas informações, mas isso resolve seu problema.


text:
Q: Linux Mint 18.3, black screen after booting I have LINUX Mint 18.3 KDE 64-bit, with Linux 4.10.0-38-generic. Unfortunately after some installing of python packages and update && upgrade, when I am restarting my systems stops after grub on black screen and nothing happens. I am able to enter in recovery mode and tryed to make update && upgrade once again but did not help. Could somebody suggest how I can find the problem and how to solve it?
Result of command  lspci | grep -i --color 'vga\|3d\|2d'  :

A: In the history file, /var/log/apt/history.log, I have found that liblightdm-gobject-1-0:amd64 (1.18.3-0ubuntu1.1) was deleted by apt-get autoremove. After reinstalling, all started to work well.
Thanks everybody for suggestions and special thanks you for guru from my job that helped me to find this issue.

A: I had a similar issue running MATE where mdm and the mate-desktop were somehow uninstalled.
The solution in short if this happens is to run these commands:
sudo apt-get install mate-desktop-environment mdm

http://realtechtalk.com/Linux_Mint_Black_Screen_after_boot_no_graphics_solution-2016-articles


text:
Q: React Native - Navigation with functional components I installed Navigation to take some data from a page and send to another (hopefully I will).
But it doesn't work and I get
"We couldn't find a navigation object. Is your component inside a navigator?"

File Insert.js
import React, { useState } from "react";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import { useNavigation } from "@react-navigation/native";

import ViewData from "./ViewData";

const MainNavigator = createStackNavigator({
  ViewDataPage: ViewData
});

...

const Insert = props => {

...

  createAppContainer(MainNavigator);

  const navigate = useNavigation();

  return (
    <TouchableWithoutFeedback
      onPress={() => {
        Keyboard.dismiss();
      }}
    >
      <View style={styles.inputContainer}>
        <Input
          placeholder="Your Name"
          onChangeText={text => setEnteredName(text)}
          value={enteredName}
        />

...

        <View>
          <Button
            title="Submit"
            onPress={() => sendValues(enteredName, enteredSurname)}
          />
          <Button
            title="Click"
            onPress={() =>navigate("ViewDataPage", { name: "Jane" })
            }
          />
        </View>
      </View>
    </TouchableWithoutFeedback>

I think I made a mess, I can't even get the page "ViewData".
I would like to change page sending some values in the hooks
Any idea where I mistook?

A: "@react-navigation/native" is for React Navigation 5. You can't use it with React Navigation 4.


text:
Q: Multiplying factors of a positive number The task is to find a singel positive whole number(X), where all the factors of that number(X) multiplied together equal $24^{240}$

A: First we write $24^{240}$ as the product of its prime factors:
$$24^{240}=2^{720}3^{240}$$
Then note that for any positive integer $n=\prod_{1=1}^m p_i^{\alpha_i}$, where each $p_i$ denotes a distinct prime number, the product of all its factors are
$$\prod_{i_1=0}^{\alpha_1}\prod_{i_2=0}^{\alpha_2}\cdots\prod_{i_m=0}^{\alpha_m}p_1^{i_1}p_2^{i_2}\ldots p_m^{i_m}$$
From this information we can infer that such number $n$ has the form $2^a3^b$ for some positive integer $a,b$. Then multiplying all factors together, we have
$$\prod_{i=0}^{a}\prod_{j=0}^{b}2^i3^j=2^{(b+1)(1+2+\ldots+a)}3^{(a+1)(1+2+\ldots+b)}=2^{720}3^{240}$$
(exercise: show that the expressions on the left and middle of the equation are equal)
Now we have two equations and two unknowns in the exponents of $2$ and $3$. Can you finish the rest?


text:
Q: Display full path in title bar of nano editor The nano editor by default displays only the filename being edited, but not its full path.
This can be a problem, if I need to edit old vs new versions of files by the same name.
Does anyone know of a way to toggle or change this behaviour to display a full path?
Or is there no way short of figuring out where this happens in the source code and recompiling?

A: man nano say's nothing about files' paths. /etc/nanorc nano configuration file also gives no such option. But if you want nano to display filename's full path, use full path during file's opening:
nano /home/user/test/test.sh will show it the next way:


text:
Q: How can I scroll a ScrolledComposited in Eclipse SWT Design view? I have a Composite that is nested in a ScrolledComposite.  The ScrolledComposite works fine when running but I am wanting to find a way to be able to edit content in the Design view that falls beneath the ScrolledComposite height.  As of now I have to re-size my entire window (drag it down to view the components), edit the content, then size the window back.  I don't want to have to do this each time though.  Does anyone know of a workaround for this?

A: No it is not possible. What is possible is to set the size of the gui outside the Class u are editing.
In my case i have a GUI class with shell.setSize(500,500) and compositie classes who have a bigger size setSize(1000,1000).


text:
Q: how to run vcvarsall.bat from python subprocess I know how to use Popen to run one .bat file. In this case I need to first run vcvarsall.bat and initialize compiler tools, and then in the same environment run a third part .bat that will actually use compiler tools. Whats the best way of doing this?
thanks!

A: This should work:
subprocess.Popen('"vcvarsall.bat" x86&&"invoke_compiler.bat"', shell=True)


text:
Q: Internet explorer always trigger window onbeforeunload The problem is that the Internet explorer fires every time ... here's my code:
    window.onbeforeunload = function() {

        if( !gdymc.info.isSaved && !gdymc.info.isSaving ) {

            return jQuery('#gdymc_adminbar').attr('data-unload');

        } else {

            return null;

        }

    }

Is there any known issue with ie? This works on all other browsers just fine.

A: Im pretty sure that you will need to return undefined instead of null:
window.onbeforeunload = function() {
    if( !gdymc.info.isSaved && !gdymc.info.isSaving ) {

        return jQuery('#gdymc_adminbar').attr('data-unload');
    } else {
        // returns undefined
        return void 0;
    }
}

The above is testet in IE8 and it works.


text:
Q: Force TFS to detect changes Seems like this should be something very simple, but I can't find how to do this...
I made a changes to several files spread within a repo by using a script that I wrote. Problem is TFS in its infinite wisdom does not think the files have changed. Aside from manually finding each file and clicking "checkout for editing" is there any way to tell TFS to just rescan everything and detect changes?

A: If any of your changes occured when you were offline, you can go to File > Source Control > Go Online, and all files will be checked for modification.

A: If none of the above work, you can also try to rebind your projects by going to File -> Source Control -> Advanced -> Change Source Control.

A: In Visual Studio 2015:
Source Control -> Advances -> Refresh Status

A: A Folder Compare (File->Source Control->Compare...) should do the trick. Select the top folder from where to start comparison, and select to compare with Latest Version. The result hould show files that are changed, and whether they are checked out or not.

A: TFS has a "Reconcile" command for this. See https://stackoverflow.com/a/22860674/932282 for a complete answer.

A: Local Workspace
You need to work with a local Workspace. Here's how to manage workspaces:
visualstudio.com: "Create and work with workspaces".
When adding or editing the workspace you click Advanced >> . Then you set Location: to Local.
Now when your script or anything else changes files outside Visual Studio, your workspace detects the changes automatically.
It also detects adds or deletes but you have to include them to your Pending Changes manually with the link under Excluded Changes

BUT BE CAREFUL. When adds or deletes get detected and you add them to your Pending Changes, the files aren't automatically included to your project. So you maybe check them in to TFS, but they aren't listed under the Solution Explorer.
Matt Burke has a fix for that problem:
mattburkdev.com: "Automatically Include All Files in Folder in Visual Studio"
To edit the Project file you rightclick your project, chosse Unload Project, then rightclick on it again and choose Edit. After you edited the project files save and close it. Then rightclick and chose Load Project.
But with that you also need to be careful, because the Project only searches for new files in these folders to include, when you load the project and not while you have the project open. So when some files get added outside Visual Studio, you just reload the project.

Server Workspace
But if you have to stick to a Server Workspace for some reason i got another trick for you:
FIRST:
Check out all Files that maybe have pending changes (better check out many files). Then go to Team Explorer -> Pending Changes and choose all files you just checked out. Then choose "undo changes". After this you get a message "Confirm Undo Checkout". This message ONLY pops up for the files, which actually HAVE changed! Press "NO" for each files or "No to All".
FINALLY: Under pending changes all files get removed from the list except the ones which have pending changes.

I hope I could help someone and you didn't have to search for this solution as long as I had to ^^

A: I had this problem a while age when i moved project from one pc to another.
the solution was to remove temporary files that TFS had created in solution folder.
Delete .vs and hidden $tf folder.
If no luck,on your local PC copy your solution folder to another, remove all files inside solution, get latest version from TFS server ,then from the copied folder just grab neccessary and edited files and put them back to solution folder (this will overwrite some files).
After all don't forget to check project mappings and if everything seems correct try right clicking on solution and 'Add to source control' option.

A: Dtsx file dropped in TFS folder was not being recognized.

*

*On your Visual Studio (2015) home screen, click on the Team Foundation Server link. Make navigate to the correct branch.

*On the window on the left side of the screen, navigate to the folder that contains your file.  Expand the folder.

*To the right of the folder you will see three dots.  Click on those and then click on " + Add File(s)".

Choose "Upload Existing Files". Then you can drag and drop your .dtsx files into the window and then click Okay.
Finally, you'll have to do a 'Fetch' to add the files there.  Then you need to do a 'Pull'. Lastly, you can commit the change to remote branch.


text:
Q: CSS and JS bundle not found in MVC When I publish or run application on local machine with Release mode bundles not working properly. It generates URL something like this:
http://localhost:60676/Content/css/?v=rRDBls2mnY7IG-YV_CwsQLv__74wfMTc-gyS9foHN601
http://localhost:60676/bundles/jquery?v=FVs3ACwOLIVInrAl5sdzR2jrCDmVOWFbZMY6g6Q0ulE1
http://localhost:60676/bundles/jqueryval?v=0EJjPUV3D0sQSPyawK-IAWWKeZ8W_Vg3wDTJ1MI1v3M1
http://localhost:60676/bundles/modernizr?v=wBEWDufH_8Md-Pbioxomt90vm6tJN2Pyy9u9zHtWsPo1

In console error read like this:
*

Failed to load resource: the server responded with a status of 403 (Forbidden)

My code in Global.asax is as per below in Application_Start()
BundleConfig.RegisterBundles(BundleTable.Bundles);
 BundleTable.EnableOptimizations = true;

A: This error mostly occurs due to a collisions between bundle urls and a physical files/folders.
For example if your solution has a following structure:
   -root
     -bundles
        -jquery.js

And you define a bundle like this:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/bundles/jquery-{version}.js"));

This will result in 403
So what you need to do, is to ensure that bundle urls have no corresponding folders in your solution.

A: I had a similar issue except I was getting a 500 error.
I did the following:

*

*Make sure that you do not have a separate script block or any references to Session outside of scripting in your _Layout.cshtml page

*

*place any script blocks inside the head section after the Scripts.Render calls

*do not do this, (I think this may be where it was complaining about referencing session - not sure):
@Html.Hidden("TimeOutSetting", Session.Timeout)
then reference it in the script block outside of the head section
    $("#TimeOutSetting").val()

- instead use this in the scripting:

    @Session.Timeout

*Make sure all script blocks are surrounded by @section Scripts {} on
all the other pages

*in the RegisterBundles function add this so it compiles correctly
depending on whether you've selected Debug or Release
#if DEBUG
        BundleTable.EnableOptimizations = false;
#else
        BundleTable.EnableOptimizations = true;
#endif

*And lastly I had some debug code that I had added to the Global.asx.cs file and I think it was complaining about referencing Session here. This may not be the case, but I removed it & it worked...
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
    HttpContext context = HttpContext.Current;
    var session = context.Session;
    var newSession = session.IsNewSession;
    var cookieLess = session.IsCookieless;
    var sessionId = session.SessionID;
    string sessionCookie = context.Request.Headers["Cookie"];
}

I hope this helps prevent you from going insane as I almost did before I finally figured this one out.
Good luck!


text:
Q: Consequences of abusing nltk's word_tokenize(sent) I'm attempting to split a paragraph into words. I've got the lovely nltk.tokenize.word_tokenize(sent) on hand, but help(word_tokenize) says, "This tokenizer is designed to work on a sentence at a time."
Does anyone know what could happen if you use it on a paragraph, i.e. max 5 sentences, instead? I've tried it on a few short paragraphs myself and it seems to work, but that's hardly conclusive proof.

A: nltk.tokenize.word_tokenize(text) is simply a thin wrapper function that calls the tokenize method of an instance of a TreebankWordTokenizer class, which apparently uses simple regex to parse a sentence.
The documentation for that class states that:

This tokenizer assumes that the text has already been segmented into
      sentences.  Any periods -- apart from those at the end of a string --
      are assumed to be part of the word they are attached to (e.g. for
      abbreviations, etc), and are not separately tokenized.

The underlying tokenize method itself is very simple:
def tokenize(self, text):
    for regexp in self.CONTRACTIONS2:
        text = regexp.sub(r'\1 \2', text)
    for regexp in self.CONTRACTIONS3:
        text = regexp.sub(r'\1 \2 \3', text)

    # Separate most punctuation
    text = re.sub(r"([^\w\.\'\-\/,&])", r' \1 ', text)

    # Separate commas if they're followed by space.
    # (E.g., don't separate 2,500)
    text = re.sub(r"(,\s)", r' \1', text)

    # Separate single quotes if they're followed by a space.
    text = re.sub(r"('\s)", r' \1', text)

    # Separate periods that come before newline or end of string.
    text = re.sub('\. *(\n|$)', ' . ', text)

    return text.split()

Basically, what the method normally does is tokenize the period as a separate token if it falls at the end of the string:
>>> nltk.tokenize.word_tokenize("Hello, world.")
['Hello', ',', 'world', '.']

Any periods that fall inside the string are tokenized as a part of the word, under the assumption that it's an abbreviation:
>>> nltk.tokenize.word_tokenize("Hello, world. How are you?")
['Hello', ',', 'world.', 'How', 'are', 'you', '?']

As long as that behavior is acceptable, you should be fine.

A: Try this sort of hack:
>>> from string import punctuation as punct
>>> sent = "Mr President, Mr President-in-Office, indeed we know that the MED-TV channel and the newspaper Özgür Politika provide very in-depth information. And we know the subject matter. Does the Council in fact plan also to use these channels to provide information to the Kurds who live in our countries? My second question is this: what means are currently being applied to integrate the Kurds in Europe?"
# Add spaces before punctuations
>>> for ch in sent:
...     if ch in punct:
...             sent = sent.replace(ch, " "+ch+" ")
# Remove double spaces if it happens after adding spaces before punctuations.
>>> sent = " ".join(sent.split())

Then most probably the follow code is what you need to count frequency too =)
>>> from nltk.tokenize import word_tokenize
>>> from nltk.probability import FreqDist
>>> fdist = FreqDist(word.lower() for word in word_tokenize(sent))
>>> for i in fdist:
...     print i, fdist[i]


text:
Q: how to combine 2 grep checks in a while loop This is basically what I'm trying to do:
while string1 is not present in foo.log OR string2 is present in foo.log do
    echo .
loop

Examples of input files:
this should keep the while running
string1
foo
bar
string2

this should keep the while running
foo
bar

this should stop the while loop
foo
bar
string1

A: "string1 is not present in foo.log OR string2 is present in foo.log" should translate to
while ! grep -q "string1" foo.log || grep -q "string2" foo.log; do
    echo .
done


text:
Q: jQuery Selector Test For All of a ClassType I have a table. The table data elements each have a div with a class in them. The div displays a small CSS box, which based on the background color gives the appearance of a light, which turns on or off.
I want to turn the lights on and off individually by clicking on them (at random), but then I need to test when any light is turned off, are all lights now off.

    ...

In other words, if the most recent click turned off the last "on" light, so that all lightbox-on classes have been removed and replaced with lightbox-off classes, trigger something.
The question goes to testing whether a group of divs all contain the same set of identical classes.

A: I think the most direct thing to do is just turn off all of them before adding the on to the one you want to.
$('.lightbox').removeClass('lightbox-on');

A: After click or toggle, use .length to count the number of visible elements, something like:
if ( $('.lightbox-on:visible').length == 1) {
// only 1 lit, do something here
}

or
if ( $('.lightbox-on:visible').length == 0) {
// they're all off, do something here
}

A: With JQuery you can do this quite easily with something like this:
$(".lightbox").click(function() {

  // Remove the lastturnedon class from all lights
  $(".lightbox").removeClass("lastturnedon");

  if (!$(this).hasClass("lightbox-on")) {
    // Add the the lastturnedon class to the clicked light only if we are turning it on.
    $(this).addClass("lastturnedon");
  }

  // Changing the lights state (on/off).
  $(this).toggleClass("lightbox-on");

  if (!$(".lightbox").hasClass("lightbox-on")) {
    // Alert if now that we turned off this light, all lights are off
    alert("All lights are off");
  }
});

Here is an example:
http://codepen.io/nathanfelix/pen/XdVrvo


text:
Q: How to connect to the internet from DPDK running in a VM DPDK is a library for kernel bypass packet processing: https://www.dpdk.org/. F-Stack is a TCP/IP library built atop it: https://github.com/F-Stack/f-stack. I've set up a Linux VMWare VPN with two NICs, have given the second to DPDK, and am attempting to run a very simple test application on it that uses F-Stack and DPDK to connect to the internet. This is however failing (fails to connect).
When I attempt to run a simple server, it also fails, in that I cannot connect to it from Curl or a browser running in the VM.
The test application displays no errors (the DPDK initialisation works fine), and behaves correctly when the DPDK stuff is replaced with standard Linux networking functions that don't bypass the kernel.
My question is, is there anything I need to do to make the above setup work, so that DPDK running on the second NIC in my VM can connect to the internet? E.g. set up some kind of mapping somewhere, or change the virtual network connection type on the VM (currently set to NAT). My networking knowledge is limited so it's quite possible I'm missing something very basic.

A: Summarizing the answer based on the updates from the comments as
Send packets directly between userspace and Kernel using DPDK, there are 3 options

*

*KNI PMD

*TUN/TAP PMD

*veth pair with one interface to DPDK via PCAP PMD.

the easiest way to try it out is by using DPDK example/skeleton with ./build/basicfwd -l 3 --vdev=net_tap0,ifaace=dpdk-kerenl0 -w [pcie bus address for DPDK NIC-2]. This will allow packets to send and receive over kernel via DPDK (where DPDK will act as pass-through). You can modify the basicfwd.c to process packets which you desire too.
If using FSTACK, I humbly request to check carrier section https://github.com/F-Stack/f-stack/blob/dev/README.md this makes use of KNI or veth to accomplish the same


text:
Q: Drawing a TikZ arc specifying the center The TiKz command for an arc:
\draw (0,0) arc (-30:30:2) ;

Draws an arc that starts at (0,0), and would be the part of the circle from -30 degrees to +30 degrees of radius 2.

It is very hard to place these arc sometimes.  This is the symbol i want to draw:

(This represents an eye and needs more detail).
I want to draw the arc as _part of a circle with center at where the < meets, but I have to currently fudge the start location of the arc so it properly crosses the < (and it's not even exact).
If I could do a circle from -45 to +45 degrees CENTERED at the <, then that would be much easier.

A: Here is an answer, using the technique described here, with more detail,
\pgfmathsetmacro{\ex}{0}
\pgfmathsetmacro{\ey}{1}

\draw (\ex,\ey) -- ++(-15:1)
      (\ex,\ey) -- ++(15:1);
\draw (\ex,\ey) ++(45:.8) arc (45:-45:.8);

The secret to this is in the last line,
\draw (\ex,\ey) ++(45:.8)

Jumps the draw cursor to "the 45 degree position on a circle of radius 0.8", without drawing anything (achieved by using only ++ and not any -- in the command)
Then, from there, we draw an arc
arc (45:-45:.8);

from 45 degrees to -45 degrees, of what would be a circle of radius .8.
Pretty roundabout way to do this, but still it works fine.
Edit:
My finished eye:

\begin{tikzpicture}

%eye
\pgfmathsetmacro{\eyeSize}{1}
\pgfmathsetmacro{\ex}{0}
\pgfmathsetmacro{\ey}{1}
\pgfmathsetmacro{\eRot}{-10}
\pgfmathsetmacro{\eAp}{-55}
\draw[rotate around={\eRot:(\ex,\ey)}] (\ex,\ey) -- ++(-.5*\eAp:\eyeSize)
     (\ex,\ey) -- ++(.5*\eAp:\eyeSize);
\draw (\ex,\ey) ++(\eRot+\eAp:.75*\eyeSize) arc (\eRot+\eAp:\eRot-\eAp:.75*\eyeSize);

% IRIS
\draw[fill=gray] (\ex,\ey) ++(\eRot+\eAp/3:.75*\eyeSize) % start point
  arc (\eRot+180-\eAp:\eRot+180+\eAp:.28*\eyeSize);

%PUPIL, a filled arc
\draw[fill=black] (\ex,\ey) ++(\eRot+\eAp/3:.75*\eyeSize) % start point
  arc (\eRot+\eAp/3:\eRot-\eAp/3:.75*\eyeSize);

\end{tikzpicture}

A: Now as TikZ 3.0 is here we can use pic.
\documentclass[tikz,border=5]{standalone}
\tikzset{
  pics/carc/.style args={#1:#2:#3}{
    code={
      \draw[pic actions] (#1:#3) arc(#1:#2:#3);
    }
  }
}
\begin{document}
\begin{tikzpicture}
  \pic{carc=-30:30:2cm};
  \draw[thick] (4,0) circle (1 cm) pic[red, -latex]{carc=100:150:1.3cm};
\end{tikzpicture}
\end{document}

Note 1: This question was treated before here How to extend TikZ drawing commands
Note 2: I arrived here from this closed quastion Tikz: Curved parallel arrow around a circle, so I gave the answer here too.

EDIT: Here are some examples how we can use carc to create logos ;)

\documentclass[varwidth,border=50]{standalone}
\usepackage{tikz}
\tikzset{
  pics/carc/.style args={#1:#2:#3}{
    code={
      \draw[pic actions] (#1:#3) arc(#1:#2:#3);
    }
  }
}
\begin{document}
  \begin{tikzpicture}
    % --- RSS
    \begin{scope}[xshift=-1.5cm]
      \fill[orange, rounded corners=5mm] (-0.5,-0.5) rectangle (3.7,3.7);
      \fill[white] (0.5,0.5) circle (0.5);
      \draw[white, line width=7mm] (0,0) pic{carc=0:90:1.9} pic{carc=0:90:3};
    \end{scope}

    % --- Radioactif
    \begin{scope}[yshift=-4cm, yellow, line width=1.4cm]
      \fill[black] circle (2.5);
      \fill circle (.5);
      \draw pic{carc=-60:0:1.4} pic{carc=60:120:1.4} pic{carc=180:240:1.4};
    \end{scope}

    % --- Wi-Fi
    \begin{scope}[yshift=-10cm, purple, line width=7mm]
      \fill circle (0.5);
      \foreach \d in  {0,1,2}
          \draw pic{carc=135:225:1.55+1.4*\d} pic{carc=-45:45:1.55+1.4*\d};
      \pic[line width=3.9cm]{carc=-105:-75:3.1};
    \end{scope}

    \begin{scope}[yshift=-21cm, blue]
      \fill (0,0) circle (0.5);
      \foreach \d in  {0,1,2}
        \draw[line width=7mm, line cap=round] (0,0) pic{carc=45:135:1.55+1.4*\d};
    \end{scope}

    % --- Goethe Institut
    \begin{scope}[yshift=-25cm, xshift=-5cm, green, line width=1.25 mm]
      \draw (2.5,2.5) circle (0.5);
      \foreach \d in  {0,1,...,4}
          \draw (1.5,1.5) pic{carc=90:360:0.5+0.25*\d};
      \node[anchor=north west, scale=2, black, draw] at (3.2,1.6) {\textsf{GOETHE-INSTITUT}};
    \end{scope}

    % --- off
    \begin{scope}[yshift=-29cm, line width=7mm, line cap=round]
      \draw[black] (0,0) pic{carc=130:410:2};
      \draw[red] (0,0) -- (0,2.2);
    \end{scope}

  \end{tikzpicture}
\end{document}

A: Adopted for an arc with x and y radius (ellipse).
\documentclass[10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{math}
\begin{document}
\begin{tikzpicture}

% Grid
\draw [step = 1, black!60!white ] (0,0) grid (9,4);

\tikzmath{
   \l= 6;     % length of cylinder
   \rx= 0.5;  % x radius of ellipse
   \ry= 1.5;  % y radius of ellipse
};

% right - left
\coordinate  (A) at (2,2);
\coordinate  (B) at ($ (A) + (\l,0) $);

% B above and below
\coordinate  (Bo) at ($ (B) + (0,   \ry) $);
\coordinate  (Bu) at ($ (B) + (0,  -\ry) $);

% A above and below
\coordinate  (Ao) at ($ (A) + (0,   \ry) $);
\coordinate  (Au) at ($ (A) + (0,  -\ry) $);

% Axis
 \draw [blue] (A) -- (B);

 % Annotation
 \node [above] at (A) {A};
 \node [above] at (B) {B};
 \node [above] at (Ao) {Ao};
 \node [above] at (Bo) {Bo};
 \node [below] at (Au) {Au};
 \node [below] at (Bu) {Bu};

% Ellipse at B (right)
\draw [ultra thick] (B) ++({\rx*cos(0)},{\ry*sin(0)})
               arc [start angle=0, end angle=360,
                         x radius=\rx, y radius=\ry];

% Ellipse at A (left)
\draw [ultra thick] (A) ++({\rx*cos(90)},{\ry*sin(90)})
               arc [start angle=90, end angle=270,
                         x radius=\rx, y radius=\ry];

% lines of cylinder
\draw[ultra thick] (Ao) -- (Bo);
\draw[ultra thick] (Au) -- (Bu);

% Patch on cylinder surface
\coordinate (C) at ($(A)!0.2!(B)$);
\draw [ultra thick] (C) ++({\rx*cos(110)},{\ry*sin(110)}) coordinate (C1)
               arc [start angle=110, end angle=140,
                         x radius=\rx, y radius=\ry] coordinate (C2);

\coordinate (D) at ($(A)!0.3!(B)$);
\draw [ultra thick] (D) ++({\rx*cos(110)},{\ry*sin(110)}) coordinate (D1)
               arc [start angle=110, end angle=140,
                         x radius=\rx, y radius=\ry] coordinate (D2);

\draw[ultra thick] (C1) -- (D1) (C2) -- (D2);

 % Annotation
 \node [above] at (C1) {C1};
 \node [below] at (C2) {C2};
 \node [above] at (D1) {D1};
 \node [below] at (D2) {D2};

\end{tikzpicture}
\end{document}


text:
Q: I am unable to implement the methods in the wsdl link class it don't consists any client class My service provider provided me a web service descriptive language link(WSDL) and asked me to call the methods from the client class, but I didn't find any client class.
I used eclipse and dynamic web project for extracting the file of the web service descriptive language link. I have tried to create a class of my own and tried to call the methods of the classes they provided to me but nothing worked for me.


text:
Q: Can a ray of light deviate passing from a rarer to a denser medium deviate beyond the normal?
Is this allowed? Technically, if the difference in the refractive indexes is big enough, and the ray of light has a low wavelength (violet), it should be able to deviate beyond the normal.

A: No, this kind of refraction will not occur due to a high refractive index. Snell's law tells us that
$$ n_1 \sin \theta_1 = n_2 \sin \theta_2 $$
where both angles are measured counterclockwise from the normal (or both are measured clockwise; the sign convention is arbitrary). If passing from air $n_1 \approx 1$ to a material with a very high refractive index, then because $n_2$ is so large relative to $n_1$, $\sin \theta_2$ must be very small relative to $\sin \theta_1$, but still of the same sign, so the refracted ray will still be on the opposite side of the normal from the incident ray; it'll just be much closer to the normal than the incident ray was.
In order to get the incident and refracted rays on the same side of the normal, you have to pass from a material with positive refractive index to one with negative refractive index or vice versa. Materials with negative refractive index do not occur in nature, but can be made in the lab.


text:
Q: foreman register changes only after restart
Possible Duplicate:
Foreman not reflecting changes

Can anyone please help me fix this problem:

*

*foreman register changes only after restart

What do I need to do that foreman registers changes when I refresh my page


text:
Q: EditText swipes out of visible view, but keyboard remains In my single-activity app, I have a ViewPager which has a PagerTabStrip. Let's say I have two tabs and two corresponding fragments. On fragment one (Frag1) I have an EditText view and on fragment two (Frag2), there is only a listview with no editable text (just a list of CheckedTextViews).
When the app starts, Frag1 is visible and focus is on the EditText and, thus, the soft keyboard appears. No problem yet. However, when I swipe to the other tab and Frag2 slides into view and Frag1 is no longer visible, the keyboard remains even though there is nothing on the visible screen (Frag2) to edit. Even if I check one of Frag2's CheckedTextViews, the keyboard remains.
Programmatically, how can I robustly and dynamically check for this type of situation and hide the keyboard?

A: You can hide the keyboard on the swipe event. Put this in your tabselected method or whatever you're using to switch fragments:
EditText myEditText = (EditText) findViewById(R.id.myEditText);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Hope this helps! :D


text:
Q: Prompted for password in Outlook after restart I have a few domain users that wants an external mailaddress as primary mail address in Outlook. (Mostly to have that as default send-as address)
The user account mail address is then added as another mail in the Outlook profile. (Not as an additional mailbox in the account)
These users are prompted for password to the external mail every time they restart their computer.
I have cleared windows vault and re-created the profiles but it doesn't work.
Anyone has a solution for this, or an explanation as to why this happens?
Thanks

A: next time it asks your for a password do the following :
Chose another user > in the username field type : DOMAiN\EMAIL or DOMAIN\LDAP depends on how your exchange is configured then type in the password hit remember password once outlook is open close and reopen and voila .


text:
Q: Flutter - Disable TextField image insert options I searched everywhere and couln't find any solution...
How to disable the image insert/gif/translation options in the TextField/TextFormField widgets?

A: make the enableInteractiveSelection property to false of the TextField
enableInteractiveSelection:false,

you can read the details in the official documentation here

A: Try setting the KeyboardType to accept only text in the TextField:
TextFormField(
  keyboardType: TextInputType.text,
  // or keyboardType: TextInputType.multiline,
  ...
)

A: You can use the bellow property for TextField and TextFormField
enableSuggestions: false,

to stop the keyboard suggesion.

A: Have a look at this and see if this workaround helps in your usecase.
hide gif/sticker in keyboard
This is usually normal keyboard behaviour to have those options not that it would work even if users tapped on it.
If you wish, you can code a custom keyboard without distractions by following add custom keyboard

A: You can disable the option to insert images into a TextField in Flutter by creating a custom

TextEditingController

and overwriting the

buildView

method to return a plain TextField.
create this
class NoImageTextEditingController extends TextEditingController {
  @override
  TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
    return super.buildTextSpan(style: style, withComposing: false);
  }
}

and use it like this
TextField(
  controller: NoImageTextEditingController(),
  decoration: InputDecoration(
    hintText: "Enter your text here",
  ),
)

A: Your gif and all suggestion is coming from the keyboard app there is some way to disable it, like if we apply password container textformfiled then it is possible like below :
Another way is you have to make custom keyboard for it
           TextFormField(
                      keyboardType: TextInputType.visiblePassword, // add this line
                      controller: textEditingController,
                      cursorColor: AppTheme.secondaryColor,

Other solution is please add this property

  keyboardType: TextInputType.multiline
  enableSuggestions: false,
  autocorrect: false,


text:
Q: Can I download genuine Ubuntu from www.ubuntu.com? Can I download the genuine version of Ubuntu from http://ubuntu.com? or do I need to make it genuine after downloading just like Microsoft Windows?

A: Ubuntu is always genuine!

Ubuntu is legally free in all conditions.

*

*Microsoft refers Genuine to as 'None Pirate' version of its Operating System (Windows).

*It would be legal if you install it on as many of your computers or even to let your friends or family install it on theirs.
After Edit:
You mean 'Activation'. No since there is no licence granted to individual users unlike Windows, so you are not required to activate. You don't need any CD/Licence keys.


text:
Q: Angular component naming limitations - 'selector [your component name] is invalid' In Angular 6 (6.0.7) I'm trying to generate a component via the CLI. I type in ng g c t1-2-3-user and get the error message Selector (app-t1-2-3-user) is invalid.
Is there something inherently not allowed in this name? I've already created a parent module called t1-myModule via ng g module t1-myModule and it was created successfully. Within that module is where I'm trying to generate this component.
I've tried creating a different name like ng g c t1-testComponent and it works fine - so the CLI doesn't appear to be broken. Something about naming a component t1-2-3-user in my setup is not liked by Angular.
EDIT: after further testing, it appears Angular doesn't like the first character after a dash - to be a number. Possibly a similar limitation as in JavaScript variables. I assume since it gets compiled into JavaScript? Can anyone elaborate on/confirm this component naming constraint?

A: As per W3C standards selector should qualify below set of things

In CSS, identifiers (including element names, classes, and IDs in
  selectors) can contain

*

*only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_);

*they cannot start with a digit, two hyphens, or a hyphen followed by
  a digit

*Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

So Angular is following the W3C convention for selector name. I was expected to see similar thing baked in inside code somewhere. After digging into CLI code It turns out that angular uses regex (/^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/) to validate selector name before creating files.
So while running ng generate component component-name command it calls @angular/schematics for component command and pass the component name parameter to it. While executing command with set of instruction it fires below line to validate selector.
validateHtmlSelector(options.selector);

validation.ts
export const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/;
export function validateHtmlSelector(selector: string): void {
  if (selector && !htmlSelectorRe.test(selector)) {
    throw new SchematicsException(tags.oneLine`Selector (${selector})
        is invalid.`);
  }
}


text:
Q: Symfony UID - How to save the ID as base32? I'm trying to use Symfony UID component to generate IDs. Everything works fine and I can communicate with the DB perfectly.
However, I observed that the ID is saved as binary in database. I'd like to persist the ID as base32 instead of binary.


text:
Q: ouc process running at 98% CPU When I open a few different applications, the temperature quickly surpasses 200 F, however, when I'm working lightly, it is around 170 F.  It just seems like ever since I upgraded to Mavericks, it's heating up very often and fans go crazy, which is by design I guess.
I just don't know what this ouc process is and why it's using so much CPU.  I force quit it, but it comes back in a few minutes again.

A: Given ouc is not a process that ships with Mac OS X it appears a third party product is causing the problem.
Searching the web suggests ouc is embedded within an application called "Mobile Partner.app".
If you have this application, please report the problem to the developers.
Manual Removal
It is always better to use the removal process provided by the developer; however, if Mobile Partner does not provide a removal tool, you might like to disable the ouc process manually.
You mention force quitting results in an immediate relaunching. This suggests the ouc process is managed by a launchd job ticket. launchd is a watchdog process that will monitor processes and relaunch any that run into trouble - such as crashing or being force quit.
Take a look in the following folders for a launchd job ticket associated with ouc:

*

*~/Library/LaunchAgents

*~/Library/LaunchDaemons

*/Library/LaunchAgents

*/Library/LaunchDaemons

The files in these folders are text files and can be read using TextEdit or a dedicated text editing tool, such as TextWrangler.
If you find a file mentioning ouc, move it out of the parent folder and restart.
As @oma mentions, if you can not find a launchd job ticket, look inside /Library/StartupItems for a folder or file containing ouc. Delete the ouc folder and restart.


text:
Q: Parcel data duplicates I'm trying to populate a table with parcel information and assign sequential numbers while dealing with some parcels that have anywhere between 2-50+ entries.  One owner has many parcels.  Is there a way to query out just duplicates to identify them.

A: I've had this exact problem with BUP (Building Unit Plans) where title for each unit in an apartment block was stacked neatly on top of each other.
If you use the feature to point tool to create the centroids it will dutifully create one centroid per polygon. From this you can collect events for exact duplicates, but if they are not exact you will not find them. I planarized the polygons by using feature to line then integrate to snap the boundaries together and feature to polygon - this creates one polygon only for each group of boundaries that should be identical. Then using intersect and summary statistics with a count of the polygon id I could recognize duplicate centroids.


text:
Q: how to add a character at the beginning of each line in Richtextbox I am doing an app that adds a certain character for each selected line if you click the button. for example "//" in each line in a Richtextbox and colored the text into red, it is like the function of comment out in visual studio
i tried this but it did'nt work
private void toolStripButton1_Click(object sender, EventArgs e)
    {
        int firstCharPosition = richTextBox1.GetFirstCharIndexOfCurrentLine();
        int lineNumber = richTextBox1.GetLineFromCharIndex(firstCharPosition);
        int lastCharPosition = richTextBox1.GetFirstCharIndexFromLine(lineNumber + 1);

        if (richTextBox1.SelectionLength > 0)
        {
            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.SelectedText = "//" + richTextBox1.SelectedText.ToString();
        }
        else
        {
            richTextBox1.Select(firstCharPosition, lastCharPosition - firstCharPosition);
            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.SelectedText = "//" + richTextBox1.SelectedText.ToString();
        }
    }

guys please help me thanks!

A: if (richTextBox1.Text.Length > 0 && richTextBox1.SelectionLength >= 0)
    {
        string[] lines = richTextBox1.Text.Split(new string[] { Environment.NewLine, "\n", "\r", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        Color normalColor = Color.Black, commentColor = Color.Red;
        int selStart = richTextBox1.SelectionStart, selEnd = selStart + richTextBox1.SelectionLength,
        startLine = -1, endLine = -1, lineSum = 0, k = 0;

        for (k = 0; k < lines.Length; k++)
            if (startLine == -1)
            {
                if ((lineSum += lines[k].Length + 1) > selStart)
                {
                    startLine = k;
                    if (selEnd <= lineSum) endLine = k;
                }
            }
            else if (endLine == -1)
            {
                if ((lineSum += lines[k].Length + 1) >= selEnd)
                    endLine = k;
            }
            else break;

        for (int i = 0; i < lines.Length; i++)
            lines[i] = (i >= startLine && i <= endLine ? "//" : "") + lines[i];

        richTextBox1.Text = "";
        richTextBox1.SelectionStart = 0;
        for (int i = 0; i < lines.Length; i++)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.SelectionColor = lines[i].TrimStart().StartsWith("//") ? commentColor : normalColor;
            richTextBox1.SelectedText = lines[i] += (i == lines.Length - 1 ? "" : "\r\n");
        }

        int selectStarIndx = richTextBox1.GetFirstCharIndexFromLine(startLine), selectEndIndx = richTextBox1.GetFirstCharIndexFromLine(endLine + 1);
        if (selectEndIndx == -1) selectEndIndx = richTextBox1.Text.Length;

        richTextBox1.Select(selectStarIndx, selectEndIndx - selectStarIndx);
        richTextBox1.Focus();
    }

A: Manipulating a RichTextBox correctly is a little more involved than changing the Text. Here is a code example that will help you.
Note that is never changes the Text directly, so it won't mess up the previous formatting and that it tries to restore the selection.
It allows you to comment out several sections independently. It takes the comment string from a TextBox for testing and it restores to Black..

// get all line numbers that belong to the selection
List<int> getSelectedLines(RichTextBox RTB)
{
    List<int> lines = new List<int>();

    int sStart = RTB.SelectionStart;
    int sEnd = RTB.SelectionLength + sStart;

    int line1 = RTB.GetLineFromCharIndex(sStart);
    int line2 = RTB.GetLineFromCharIndex(sEnd);

    for (int l = line1; l <= line2; l++) lines.Add(l);
    return lines;

}

// prefix a line with a string
void prependLine(RichTextBox RTB, int line, string s)
{
    int sStart = RTB.SelectionStart;
    int sLength = RTB.SelectionLength;

    RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
    RTB.SelectionLength = 0;
    RTB.SelectedText = s;

    RTB.SelectionStart = sStart;
    RTB.SelectionLength = sLength;
}

// color one whole line
void colorLine(RichTextBox RTB, int line, Color c)
{
    int sStart = RTB.SelectionStart;
    int sLength = RTB.SelectionLength;

    RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
    RTB.SelectionLength = RTB.Lines[line].Length; ;
    RTB.SelectionColor = c;

    RTB.SelectionStart = sStart;
    RTB.SelectionLength = sLength;

}

// additional function, may come handy..
void trimLeftLine(RichTextBox RTB, int line, int length)
{
    int sStart = RTB.SelectionStart;
    int sLength = RTB.SelectionLength;

    RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
    RTB.SelectionLength = length;
    RTB.Cut();

    RTB.SelectionStart = sStart;
    RTB.SelectionLength = 0;
}

// remove a string token from the start of a line
void trimLeftLine(RichTextBox RTB, int line, string token)
{
    int sStart = RTB.SelectionStart;
    int sLength = RTB.SelectionLength;

    RTB.SelectionStart = RTB.GetFirstCharIndexFromLine(line);
    RTB.SelectionLength = token.Length;
    if (RTB.SelectedText == token) RTB.Cut();

    RTB.SelectionStart = sStart;
    RTB.SelectionLength = 0;
}

This is the comment button:
private void button1_Click(object sender, EventArgs e)
{
    List<int> lines = getSelectedLines(richTextBox1);

    foreach (int l in lines) prependLine(richTextBox1, l, tb_comment.Text);
    foreach (int l in lines) colorLine(richTextBox1, l, Color.Firebrick);

}

This is the uncomment button:
private void button2_Click(object sender, EventArgs e)
{
    List<int> lines = getSelectedLines(richTextBox1);

    foreach (int l in lines) trimLeftLine(richTextBox1, l, tb_comment.Text);
    foreach (int l in lines) colorLine(richTextBox1, l, Color.Black);

}

A: This might do the job
if (richTextBox1.SelectionLength >= 0 && richTextBox1.Text.Length > 0)
{
    int firstCharIndex = richTextBox1.GetFirstCharIndexOfCurrentLine();
    if (richTextBox1.SelectionLength == 0)
    {
        int lineNumber = richTextBox1.GetLineFromCharIndex(firstCharIndex);
        int lastCharIndex = richTextBox1.GetFirstCharIndexFromLine(lineNumber + 1);
        if (lastCharIndex == -1) lastCharIndex = richTextBox1.Text.Length;
        richTextBox1.Select(firstCharIndex, lastCharIndex - firstCharIndex);
        richTextBox1.SelectionColor = Color.Red;
        richTextBox1.SelectedText = "//" + richTextBox1.SelectedText;
        richTextBox1.Select(firstCharIndex--, lastCharIndex - firstCharIndex);
        richTextBox1.Focus();
    }
    else
    {
        int selStart = richTextBox1.SelectionStart;
        int selLen = richTextBox1.SelectionLength;
        richTextBox1.SelectionStart = selStart + selLen;
        int lastLineFirstChar = richTextBox1.GetFirstCharIndexOfCurrentLine();
        int lastLineNumber = richTextBox1.GetLineFromCharIndex(lastLineFirstChar);
        int lastLineLastChar = richTextBox1.GetFirstCharIndexFromLine(lastLineNumber + 1);
        if (lastLineLastChar == -1) lastLineLastChar = richTextBox1.Text.Length;

        string beforeSelection = richTextBox1.Text.Substring(0, firstCharIndex);
        string afterSelection = richTextBox1.Text.Substring(lastLineLastChar, richTextBox1.Text.Length - lastLineLastChar);
        string selectionText = richTextBox1.Text.Substring(firstCharIndex, lastLineLastChar - firstCharIndex);

        string[] lines = selectionText.Split(new string[] { Environment.NewLine, "\r", "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        string commentedText = "";
        for (int i = 0; i < lines.Length; i++) commentedText += "//" + lines[i] + "\r\n";

        richTextBox1.Text = beforeSelection + afterSelection;
        richTextBox1.SelectionStart = firstCharIndex;
        richTextBox1.SelectedText = commentedText;
        richTextBox1.Select(firstCharIndex, lastLineLastChar - firstCharIndex + (lines.Length * 2));
        richTextBox1.SelectionColor = Color.Red;
        richTextBox1.Focus();
    }
}


text:
Q: How to calculate number of unique strings given a blacklist of avoided substrings. If you use the lowercase alphabet a-z plus the numbers 0-9 to construct a random string, the question is how to mathematically figure out in advance (i.e. without doing brute force approach) how many possibilities you can have given that you want to blacklist a few words so they don't appear in the text. So there are $26 + 10 = 36$ characters.
Say all strings are 256 characters long. Say the blacklist words we want to avoid are:
abc
defg
hijk
lmnop
qrs
tuv
wx
yz

If there's no blacklist, then the value is simply $36^n$, or $36^{256}$ in this case.
But if there is a blacklist, wondering how to calculate the number of possible strings of length $n$ or 256. I understand how to create an algorithm for this, but not how to calculate how many values it contains.
My attempt is as follows.... Say each value $v$ can appear at any position $i$ in the string of length $n$ up to $n-l(v)$, where $l(v)$ is the length of $v$. But you also have to take into account that the strings can't overlap, and all the combinations of them showing up together or not. You also want to consider repeats, so randomrandomabcrandomrandomabcrandom sort of thing. Etc.. Now I'm starting to get lost. I'd have to try writing out an algorithm to see how it works.
I would like to learn how to solve these kinds of problems better, not really sure how to avoid the brute force approach of trying out variations and possibilities.

A: One approximate approach, which works well for long blacklisted strings and not well for short ones is to compute the number containing the string.  An overestimate for the number of $n$ character strings containing lmnop is $(n-4)36^{(n-5)}$.  There are $n-4$ places to put the $l$ and $n-5$ other characters to choose.  The reason this is an overestimate is that we count twice the strings that have two copies of lmnop, three times the ones that have three copies, and so on.  If the blacklisted string is long, the chance of having two of them is small and we can ignore it.
In this example, $36^{256} \approx 2.6\cdot 10^{398}, 252\cdot 36^{251}\approx 1.1\cdot 10^{393}$ so we are already down a factor $10,000$.  Having two copies will be down by $10^8$ or so.  To get it right, you use the inclusion-exclusion principle to correct the count.  On the other hand, your two character blacklists will happen a lot, so occurrences of more than one will be common.  It will be a lot more work for them.
Another approach is coupled recurrence relations.  Count the number of acceptable $n$ character strings that end with every combination of interest. If you have a string ending in lmn you can add any character to it without making it unacceptable.  If you add an a, you are in the state ending in a.  If you add a digit you are in the state that doesn't start any blacklisted string.  You can just build up the number of strings of any length.

A: For every finite (and valid) string $\alpha$ we can define $f(\alpha)$ as
the longest prefix of a blacklisted word that is a suffix of $\alpha$. Knowing only $f(\alpha)$ (and the sturcture of the blacklist), we can determine for each character $x$ whether $\alpha x$ is valid (namely, whether $f(\alpha)x$ is not a blacklisted word), and if so, what $f(\alpha x)$ is.
For each prefix $p$ of at least one blacklisted word (including the empty prefix, but none of the complete words), let $F(n,p)$ be the number of valid strings $\alpha$  of length $n$ and such that $f(\alpha)=p$. As described above, we can compute $F(n,p)$ from all $F(n-1,p')$. So if there are $m$ prefixes, the $m$-dimensional vector $F_n:=(f(n,p_1),\ldots,f(n,p_m))^T$ is obtained from $F_{n-1}$ by a matrix multiplication,
$$ F_n=AF_{n-1}.$$
Note that $F_0$ is the vector with $1$ in the entry corresponding to the empty prefix and the final result we want is the sum of all components of  $F_n$, or its scalar product with $(1,1,\ldots,1)^T$. The behaviour of this for large $n$ is governed by the largest eigenvalue $\lambda$ of $A$ in that there is a constant $c$ such that there are roughly $$c\lambda^n$$ valid strings of length $n$.

In your specific example, we'd have to deal with a $19\times 19$ matrix, which may be tedious. A very rough lower bound however is this (for that specific list of words): At any point, at most one character is "forbidden" (this property may not hold for a different blacklist). Hence there are at least $35^n$ valid words. While this is very rough and the difference between $35^n$ and $36^n$ is enormous for large $n$, it is perhaps a good enough figure for an application you may have in mind.


text:
Q: Caching downloads for offline apps In my web app, I give users the ability to download various files. When trying to give the app a capability to work offline, I want to cache files that users have already downloaded, so they're able to "redownload" then, even if user is offline (in this case, file will be taken from the local cache, obviously, not from the server).
Is it possible to implement this use case? File API or Blobs, maybe?
Thank you in advance.


text:
Q: Apache 2.2: Restrict access via basic authentication generally - but NOT ON a server with a specific IP or domain WITHOUT VirtualHosts Is it possible to restrict access via basic authentication generally, but not on a server that has a specific IP or domain name - without the use of virtual-hosts (and no use of Satisfy) ?
Addition: htpasswd can't be used as the solution.

A: Have you tried using a htpassword? You can restrict users at a basic level (username and password) using just a few lines. It shouldn't make a difference if your server has a dynamic IP, and you don't need virtual hosts.
This generator makes it pretty simple
I hope this is the solution you need!


text:
Q: C# Returning a generic interface from a factory I've implemented a Vehicle service that is responsible for servicing vehicles such as cars and trucks:
public interface IVehicleService
{
    void ServiceVehicle(Vehicle vehicle);
}

public class CarService : IVehicleService
{
    void ServiceVehicle(Vehicle vehicle)
    {
        if(!(vehicle is Car))
            throw new Exception("This service only services cars")

       //logic to service the car goes here
    }
}

I also have a vehicle service factory that is responsible for creating a vehicle service according to the type of vehicle passed in to the factory method:
public class VehicleServiceFactory
{
    public IVehicleService GetVehicleService(Vehicle vehicle)
    {
        if(vehicle is Car)
        {
            return new CarService();
        }

        if(vehicle is Truck)
        {
            return new TruckService();
        }

        throw new NotSupportedException("Vehicle not supported");
    }

}

The main issue I have is specifically with CarService.ServiceVehicle method. It's accepting a Vehicle when ideally it should accept a Car instead, as it knows that it will only service cars. So I decided to update this implementation to use generics instead:
public interface IVehicleService<T> where T : Vehicle
{
    void ServiceVehicle(T vehicle);
}

public class CarService : IVehicleService<Car>
{
    void ServiceVehicle(Car vehicle)
    {
        //this is better as we no longer need to check if vehicle is a car

        //logic to service the car goes here
    }
}

The issue I'm having is how to update VehicleServiceFactory to return the generic version of the vehicle service. I've tried the following but it results in a compilation error as it's unable to cast CarService to the generic return type IVehicleService:
public class VehicleServiceFactory
{
    public IVehicleService<T> GetVehicleService<T>(T vehicle) where T : Vehicle
    {
        if(vehicle is Car)
        {
            return new CarService();
        }

        if(vehicle is Truck)
        {
            return new TruckService();
        }

        throw new NotSupportedException("Vehicle not supported");
    }

}

Any suggestions would be appreciated.

A: Simply cast the service to the interface:
return new CarService() as IVehicleService<T>;

You know T is car but the compiler doesn't, its not smart enough to follow the method logic nor is it meant to be; as far as the compiler knows, T can be anything as long as its a Vehicle. You need to tell the compiler, "Hey, I know what I'm doing, T and Car are in fact the same type."

A: Solution that @InBetween suggests is the most straightforward one. Yet, if number of inheritors is more than 2 or 3, or if it's expected to grow, I would advocate for a different solution.
If we write if (vehicle is Car) and if (vehicle is Truck), we probably follow this pattern in multiple places in the code. What happens when we need to introduce another kind of Vehicle? We'll have to change every place in the code where we check for concrete implementations. This is not how OOP is intended to be used.
The design goal is avoiding multiple changes in existing code when introducing a new implementation of an abstraction.
public class VehicleServiceFactory
{
    // the code of this method doesn't change when new Vehicle type is introduced

    public IVehicleService<T> GetVehicleService<T>(T vehicle) where T : Vehicle
    {
        Func<object> concreteFactory;

        if (_factoryByType.TryGetValue(typeof(T), out concreteFactory))
        {
            var serviceInstance = (IVehicleService<T>)concreteFactory();
            return serviceInstance;
        }

        throw new NotSupportedException("Vehicle not supported");
    }

    // the simplest service locator below is just an example
    // of decoupling clients of an abstraction from its implementations

    // instead of hard-coded initialization, the dictionary can be built
    // from configuration or a database, for example

    private static readonly Dictionary<Type, Func<object>> _factoryByType =
        new Dictionary<Type, Func<object>> {
            { typeof(Car),   () => new CarService() },
            { typeof(Truck), () => new TruckService() }
            // .... the rest of Vehicle types
        };

}

So here I just use Dictionary inside the factory, since I don't know much about the rest of your system. In general, think how you introduce new types of Vehicle with minimal changes in the rest of your code.

A: Does this work for you?
public class VehicleServiceFactory
{
    public S GetVehicleService<T, S>(T vehicle)
        where T : Vehicle
        where S : IVehicleService<T>, new()
    {
        return new S();
    }
}


text:
Q: Drag and drop function is not working in chromedriver using selenium webdriver and Node js for Test automation Is there a way where I can make drag and drop to in selenium using Node.js? I am using the function shown below but it does not seem to work.
driver.actions().dragAndDrop(source,destination).perform())

A: First of all, you forgot the build() method.
Second of all, inspect the html code and find if your drag&drop is into Iframe tag.
If it is, then you need to switch to that Iframe.
So:
driver.switchTo().frame(driver.findElement(By.xpath("PutYourXpathIframe")));

Actions a = new Actions(driver);
WebElement source = driver.findElement(By.id("PutYourSourceId"));
WebElement target = driver.findElement(By.id("PutyourTargerId"));
a.dragAndDrop(source,target).build().perform();

In the end you may want to switch back to default content:
driver.switchTo().defaultContent();

A: As a workaround could you use the following?:
 browser.actions()
    .mouseDown(element1) //optionally
    .mouseMove(source)
    .mouseMove(destination)
    .mouseUp()
    .perform();

A: This page has a good example of how to do this.
var assert = require('assert');
var webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;

var chrome = require("selenium-webdriver/chrome");

var options = new chrome.Options();
options.addArguments("start-maximized");
options.addArguments("disable-popup-blocking");
options.addArguments("test-type");
var driver = new webdriver.Builder().
withCapabilities(options.toCapabilities()).build();

driver.get('http://www.softpost.org/selenium-test-page/');
var e3 = driver.findElement(By.tagName('select'));

//You can use ActionSequence class to perform actions in selenium

new webdriver.ActionSequence(driver).
keyDown(webdriver.Key.SHIFT).
click(e3).
//dragAndDrop(element3, element4).
keyUp(webdriver.Key.SHIFT).
perform();

//In the same way, you can perform below actions.
//sendKeys, mouseUp , mouseMove, mouseDown, dragAndDrop, doubleClick

driver.sleep(5000);

driver.quit();
//Similarly we can also do touch actions on mobile phones`


text:
Q: removeClass works instantly, addClass only works on lose focus I have buttons which allow users to toggle the visibility of elements on the page. When an element is visible, the button should be highlighted.
When it becomes invisible, the highlighting vanishes instantly, as desired. But when it becomes visible, the highlighting only appears when the button loses focus.
if (column.visible()) {
    $(button).addClass("highlight");
}
else {
    $(button).removeClass("highlight");
}

In other words, "remove CSS class" has an instant effect, but "add CSS class" does not. What might be going on here?
Update:
Here's JSFiddle showing this behaviour: https://jsfiddle.net/f7cwfr3x/7/

A: The jsFiddle works. I don't see any issues.
$(button).toggleClass("highlight", column.visible());

When you first click, then the column.visible() returns false, the highlight class is removed. When you secondly click the button, the column.visible()==true - the highlight class is added.
Though, I'd not recommend to use the -webkit-focus-ring-color outline, as it's not supported by most of the browsers, except webkit.


text:
Q: How do I add a char variable to a string? I am making a Hangman game as a first C++ project, and I need to keep a bank of all the letters that the player has already used. Right after the player guesses a letter, I need to add it to the guessed bank. The guess is a char variable defined globally, as is the guessed variable. I have tried to do it like this:
#include <iostream>
#include <vector>
using namespace std;

char guess;
string guessed;

int main() {
    cin >> guess;
    guessed->push_back(guess);
}

However that doesn't work. I have also tried using the += operator, and I get an error

error: incompatible types in assignment of 'char' to 'std::__cxx11::string [0]' {aka
'std::__cxx11::basic_string<char> [0]'}

I am guessing something is wrong with my variable types, however this is my very first C++ project and I can't exactly figure out how to fix this.

A: for your purpose I think the best will be to use std::set< char >.
This will hold no duplicates and return an answer in O(log n) time.
or actually because it's a small limited range, you can actually use binary array of length 26
an example, as you requested:
#include <iostream>
#include <string>
#include <set>

int main()
{
  char guess;
  std::set<char> lettersBank;
  std::cout << "Plz enter your letter guess:";
  std::cin >> guess;
  lettersBank.insert(guess);

  // check if some letter is already inside the set:
  char checkLetter = 'd';
  if(lettersBank.find(checkLetter) != lettersBank.end())
    std::cout << "you already guessed this letter" << std::endl;
}

A: Rather than making a bank of the characters been used, I think it would be better to just keep them by the index 0-25.
You could create a array of 26 bools. If the user enters a, then the corresponded bool, or index 0 would be set true. Code below:
#include <iostream>
#include <array>
#include <cctype> // for std::toupper(char c)

int main()
{
    char guess;
    std::array<bool, 26> guessed;
    std::cout << "Take a guess!\n";
    std::cin >> guess;
    guess = std::toupper(guess); // Make it to uppercase so you don't need to check the case
    if(guessed[guess - 'A'])
    {
        std::cout << "You already guessed it!\n";
    }
    else
    {
        guessed[guess - 'A'] = true;
    }
}

With this way, you don't need any .find(char) functions, although it's not a large list to go through.
You can also easily print all guessed letters:
    for(int i = 0; i < guessed.size(); ++i)
    {
        if(guessed[i])
        {
            std::cout << static_cast<char>(i + 'A') << ", ";
        }
    }

Gameplay wise, this prints letters in alphabetic order, instead of chronological, which I think is easier to find the letter's you haven't guessed yet.


text:
Q: Spinner con LiveData y Room Soy nuevo con la programación en Android y me ha surgido un problema. Tengo un Spinner que muestra una lista de Strings que vienen de la base de datos (uso Room) y me gustaría que cuando se añade un registro a la tabla de donde salen los datos se actualice dicho Spinner.
En la query del Dao ya he hecho que se devuelva una lista LiveData:
LiveData<List<String>> getAllNames();

Me falta la parte de la actualización. Tengo entendido que tengo que añadir un observador pero no sé cómo. No uso viewModel ni Recycler View (aún no sé que son) y el siguiente código es lo que tengo actualmente para rellenar el Spinner.
Un saludo
    spinner = findViewById(R.id.mainSpinner);
    List<String> marcas = AppDatabase.getDatabase(this).dbMarcaDao().getAllNames();
    marcas.add(0,"Todas");
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, marcas);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

-----------EDIT-------------
Gracias a la guia de Jorgesys he conseguido dar con la solución, aunque han surgido varios detalles:
- Puesto para obtener el Dao de Room se necesita el contexto, mi nueva clase "MyViewModel" se debe extender de AndroidViewModel ya que ViewModel no tiene contexto.
- No he usado el MutableLiveData, sino LiveData por todo.
- No es necesario "inicializar" el spinnner, de eso se encarga la nueva clase.
Mi código quedaría así:
MainActivity:
spinner = findViewById(R.id.mainSpinner);
marcas = new ArrayList<String>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, marcas);        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
MyViewModel model = new ViewModelProvider(this).get(MyViewModel.class);
model.getMarcas().observe(this, new Observer<List<String>>() {
  @Override
  public void onChanged(List<String> nuevas_marcas) {
     marcas.clear();
     for (String term : nuevas_marcas) {
       marcas.add(term);
     }
     marcas.add(0,"Todas");
     adapter.notifyDataSetChanged();
   }
});

"MyViewModel"
public class MyViewModel extends AndroidViewModel {
    private LiveData<List<String>> nombresMarcas;
    public MyViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<List<String>> getMarcas() {
        if (nombresMarcas == null) { ;
            cargaMarcas();
        }
        return nombresMarcas;
    }

    private void cargaMarcas() {
        nombresMarcas = AppDatabase.getDatabase(getApplication().getApplicationContext()).dbMarcaDao().getAllNames();
    }
}

A: En realidad antes de añadir el observador debes crear una clase que extienda de ViewModel, en la cual obtendrás una lista
private MutableLiveData<List<String>> namesList;

y donde debes implementar el método para obtener los nombres, por ejemplo:
LiveData<List<String>> getAllNames() {

    if (namesList == null) {
        //Instancia lista
        namesList = new MutableLiveData<>();
        //Carga usuarios.
        loadUsers();
    }
    return usersList;
}

private void loadNames() {

   //Obtiene Nombres.

}

ahora con esta clase puedes definir tu observer para que identifique cambios:
 NamesViewModel model = ViewModelProviders.of(this).get(NamesViewModel.class);

        model.getAllNames().observe(this, new Observer<List<String>>() {
            @Override

            public void onChanged(List<String> usersList) {

                // Actualiza datos
                spinner.setAdapter(adapter);
                spinner.notifyDataSetChanged();

            }
        });

Muy importante revisar:
Descripción general de ViewModel
Descripción general de LiveData


text:
Q: Dojo Dijit Dialog relative position. is it possible? I want to position Dojo's Dijit Dialog relative to one of my html element. is it Possible?
If yes. How?
currently it always shows dialog in middle of viewport.
Can any one help me regarding the matter?
Thanks.
amar4kintu

A: Another way that I do this (not great because I override a private method but it gives me the flexibility I want):
var d = new Dialog({
    title:"Your Dialog",
    _position:function(){
        if(this.refNode){
            p = Geo.position(this.refNode);
            Style.set(this.domNode,{left:p.x + "px", top:p.y + "px"});
        }
    },

    showAround:function(node){
        this.refNode = node;
        this.show();
    }
});
d.showAround(dojo.byId("someNode"));

This example uses "dojo/dom-style" as Style and "dojo/dom-geometry" as Geo.

A: I did that by adjusting default absolute position of dijit.dialog using dojo..
I used following code to readjust absolute position of dialog to what I want..
dijit.byId('dialog').show();

dojo.style('dialog','background-color','#AAAAAA');

var co = dojo.coords('period'); // element below which I want to display dialog

dojo.style('md1','top',(co.y + 25)+'px');
dojo.style('md1','left', co.x+'px');

Hopefully this will help someone..
Thanks.
amar4kintu

A: I think dijit.TooltipDialog is what you need.

A:     var dialog = new dijit.Dialog({
        title: myTitle,
        content: myDialogContent,
        style: "width: 300px;",
        onShow: function() { dojo.style(this.containerNode.parentNode,'visibility','hidden'); },
        onLoad: function() { dojo.style(this.containerNode.parentNode,{top:'100px', visibility:'visible'}); }

    });

Instead top:'100px' you can use also top:'20%' but not tested well. My dojo is 1.7.1.