text:
Q: Make Keycloak log in JSON format How do get Keycloak 4.5.0.Final to log in JSON format?
I'm running Keycloak in Kubernetes using the Helm chart, which provides hooks for running JBoss CLI scripts (keycloak.cli.custom) or shell scripts (keycloak.preStartScript).
But I would like to avoid having to customize the Docker image.

A: I'm using keycloak 8.0.1 so this may not apply to your 4.5 version but all I had to do was to supply a jboss cli script to use the json formatter instead of the PATTERN formatter
# Undertow HTTP Server Configuration

echo Started configuring Undertow ....

# Create a new log formatter to output json with full stacktrace details
/subsystem=logging/json-formatter=SUMO_FORMATTER:add(pretty-print=false, exception-output-type=detailed-and-formatted, print-details=false)
# Disable the original console output that was in plain text format
/subsystem=logging/console-handler=CONSOLE/:write-attribute(name=enabled,value=false)
# Create a new console logger that uses the new json formatter
/subsystem=logging/console-handler=SUMO_CONSOLE:add(enabled=true, named-formatter=SUMO_FORMATTER)
# Make the root logger use the new console logger
/subsystem=logging/root-logger=ROOT/:write-attribute(name=handlers,value=["SUMO_CONSOLE"])

echo ... Completed configuring Undertow

There's some doco on it here

*

*https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.2/html/configuration_guide/logging_with_jboss_eap#configure_json_log_formatter

*https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.2/html/configuration_guide/reference_material#json_log_formatter_attributes

A: Following this great article (which also link to Github), one can achieve JSON logs following these steps:

*

*Create a JAVA project which implements Keycloak SPI plugin - This plugin will listen to Keycloakevents and may replace the default logger

*Modify the code to stringify event objects in JSON format

*Build the project as a library and place the jar executable file in Keycloakdeployments folder (please follow the article to get the full details)

*Go to Keycloakadmin interface, select relevant realm and replace default logger with your logger

Final code may looke something like this:
public class MyEventListenerProvider implements EventListenerProvider {

    public MyEventListenerProvider() {
        // use c'tor to init variables / connections / etc. - plugin load hook
        this.jsonMapper = new ObjectMapper();
    }

    ObjectMapper jsonMapper;

   private stringify(Object obj) {
       try {
          return this.jsonMapper.writeValueAsString(obj);
       } catch (Exception ex) {
          ex.printStackTrace();
          return null;
       }
   }

    @Override
    public void onEvent(Event event) {
        System.out.println(this.stringify(event));
    }

    @Override
    public void onEvent(AdminEvent adminEvent, boolean b) {
          System.out.println(this.stringify(adminEvent));
    }

    @Override
    public void close() {
       // use close to close connections / reset variables - plugin unload hook
    }

This sample is written on the fly (it's partial, sorry if there are compilation errors) and uses Jackson lib as described here


text:
Q: Why does the SizedBox not constrain the Text widget width? So I am making a simple messaging app and have run into the following problem:
I set the width of the SizedBox to 100, but when the child is a Text widget it overrides the SizedBox's width.
This widget is called from a ListView.builder in a different file.
Is there a different widget that I should be using for this, instead of a sizedbox?
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: SizedBox(
        width: 100,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(14.0)),
            color: currentUserIsSender ? Styles.accentColor30 : Colors.grey.shade200,
          ),
          padding: EdgeInsets.all(8.0),
          child: Text(
            message,
            softWrap: true,
          ),
        ),
      ),
    );
  }

Thanks
Picture of app problem

A: The problem is, SizedBox can set widget size only within the constrains set by the parent.
Many widgets, like Padding, want their child to occupy 100% of the space available to them. This makes sense, because if the child is smaller they wouldn't know where to put it.
If you want the child to be smaller than the parent you could use Center or Align, e.g. replace
Padding(
  child: SizedBox(
    width: 100,
    child: ...
    ),
  ),
);

with
Padding(
  child: Center(
    child: SizedBox(
      width: 100,
      child: ...
      ),
    ),
  ),
);

(for a chat app you might want to use Align rather than Center)
Related reading: https://flutter.dev/docs/development/ui/layout/constraints

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't load IA 32-bit .dll on a AMD 64-bit platform on windows 2008 server system Today when i migrate a project from old server to new server, i encounter this problem when i test the deployed service codes.
javax.servlet.ServletException: java.lang.UnsatisfiedLinkError: E802: Can't load shared library. E:\Rochade\bin\msvcr71.dll E:\Rochade\bin\msvcr71.dll: Can't load IA 32-bit .dll on a AMD 64-bit platform
no msvcr71 in java.library.path
i googled it on the internet and found some tips on installing a 36 bit jdk, i tried but didn't sovle the problem, does any one has any comment on this? i am really in hurry to get this problem solved, which is the road block for us moving forward on the migration process.

A: I think you cannot load library compiled for 32-bit architecture in 64-bit environment.
Solution is to recompile the library for x64 or obtain 64-bit version if you do not have its sources.

A: You either can use a 32-bit JVM or install the 64-bit version of the Microsoft Visual Studio C/C++ Redistributable Package.
Or better reinstall the software on the new server. Moving only the folders to a new computer is not a good idea on Windows, especially when the old PC was a 32-bit system and the new PC is a 64-bit system.


text:
Q: In a vim function, how do you set a register to a value that includes new lines? When I run the following as a :command in vim, the register is set properly.
let @a='line1^@line2'

When I press "ap, I get
line1
line2

When I put the line in a function in my .vimrc,
function! SetA()
    let @a='line1^@line2'
endfunction

call it,
:call SetA()

vim generates the following error.
E115: Missing quote: 'line1
E15: Invalid expression: 'line1

It seems like ^@ (that I entered with Ctrl+v Ctrl+@) is getting interpreted as an extra line when it's part of a function.  How do I escape this, or prevent it from happening?

A: this would do:
function! SetA()
    let @a="line1\nline2"
endfunction

A: In addition to Kent's answer that you found working for you, instead of Ctrl+v Ctrl+@ that you tried, try Ctrl+v Ctrl+j.
Hope that helps.


text:
Q: Moving wordpress to Amazon Web Services I'm planning to move my Website which is using multiple wordpress to Amazon Services. However, my daily vistors are about 22,000 and sometimes goes to over 90k and the web crashes! However, the hosting company charge me nearly $100 including support without support it would cost $50. the average bandwidth is about 400GB.
Can I ask please how much will it cost me? and how I can start with Amazon Services?
Kind regards

A: Start out by looking at the different types of hosting that Amazon offers and which one will be the correct fit for your site.  Amazon's EC2 (Elastic Cloud Computing) is the servers that you can get hosted in the cloud.
Depending on how much storage space and bandwidth, the costs differ.  They have a helpful cost guide on their EC2 page.  They offer different pricing for the different types of servers you need.  They have on demand spot instances which can be brought up and down on the fly.  If you need a server to be running constantly you can put a down payment and have a reserved instance to provide the server.

A: You can calculate your fees depending on your current usage from the tools AWS provides. http://calculator.s3.amazonaws.com/calc5.html
This is also a good article for getting started with using WordPress under AWS.
http://wp.tutsplus.com/tutorials/scaling-caching/deploy-your-wordpress-blog-to-the-cloud/
AWS also provides a Free Tier of services provided you stay under a certain amount of usage. That is detailed at http://aws.amazon.com/free/ . I also found this YouTube video on setting up EC2 instances very helpful. http://www.youtube.com/watch?v=JPFoDnjR8e8 . From what I understand, unless your WordPress install gets a crazy number of hits you will probably fall under the Free Tier.


text:
Q: Drawing bar graphs using \foreach Using the following code from the answer to this question, How to draw the following bar graphs.
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\usepackage{pgfplots}
\begin{document}
\begin{frame}[t]
\frametitle{}
\begin{tikzpicture}[scale=.4, transform shape,linecolor/.style={thick,blue}]
\pgfmathsetmacro{\incrmnt}{1.}
\pgfmathsetmacro{\inc}{5}
\draw [thick,-latex](0,0) -- (8,0) node [black, xshift=.35cm, yshift=0cm] {Age};
\draw [thick,-latex](0,0) -- (0,6) node [black, xshift=0cm, yshift=.3cm] {Fr.};
\foreach \y [evaluate=\y as \aff using int(\y*2)]in {1,...,5}{
\draw [linecolor] (.15,\incrmnt*\y) -- +(0:-.3) node [left] {\aff};
}

\foreach \x [evaluate= \x as \aff using int(\inc*\x+20)]in {1,...,6}{
\draw [linecolor] (\incrmnt*\x,.15) -- +(-90:.3) node [below] {\aff};
}
\end{tikzpicture}
\end{frame}
\end{document}

A: Tikz allows you to build graphs as a bar graph like the one in your example or as a curve with the plot operation.
Here, to draw the sticks from one coordinate to another, there is the option ybar interval which draws the sticks in the interval between two consecutive coordinates.
As on your axes, the ordinates (number of the vertical axis) are multiplied by two, it is enough to divide by two the ordinates.
\draw[ybar interval,pattern=north west lines]
plot coordinates{(1,1) (2,4) (3,5) (4,2) (5,0)};

(1,1) (2,4) draws a stick, i. e. a rectangle whose upper left corner is located at the point (1,1) and whose lower right corner is at point of abscissa 2 i. e. at the point of coordinates (2,0).
(1,1) (2,4) (3,5) does the same by adding a second rectangle whose upper left corner is located at the coordinate point (2,4) and the lower right corner is the abscissa point 3.
Etc.
First graph:

\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\usetikzlibrary{patterns}
\begin{document}
\begin{frame}[t]
\frametitle{}
\begin{tikzpicture}[scale=.4, transform shape,linecolor/.style={thick,blue}]
\pgfmathsetmacro{\incrmnt}{1.}
\pgfmathsetmacro{\inc}{5}
\draw [thick,-latex](0,0) -- (8,0) node [black, xshift=.35cm, yshift=0cm] {Age};
\draw [thick,-latex](0,0) -- (0,6) node [black, xshift=0cm, yshift=.3cm] {Fr.};
\foreach \y [evaluate=\y as \aff using int(\y*2)]in {1,...,5}{
\draw [linecolor] (.15,\incrmnt*\y) -- +(0:-.3) node [left] {\aff};
}

\foreach \x [evaluate= \x as \aff using int(\inc*\x+20)]in {1,...,6}{
\draw [linecolor] (\incrmnt*\x,.15) -- +(-90:.3) node [below] {\aff};
}

\draw[ybar interval,pattern=north west lines]
plot coordinates{(1,1) (2,4) (3,5) (4,2) (5,0)};
\end{tikzpicture}

\end{frame}
\end{document}

Second graph:
For the second graph, it is enough to draw a rectangular stick. For example:

\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\usetikzlibrary{patterns}
\begin{document}
\begin{frame}[t]
\frametitle{}
\begin{tikzpicture}[scale=.4, transform shape,linecolor/.style={thick,blue}]
\pgfmathsetmacro{\incrmnt}{1.}
\pgfmathsetmacro{\inc}{5}
\draw [thick,-latex](0,0) -- (14,0);
\draw [thick,-latex](0,0) -- (0,6);
\foreach \y [evaluate=\y as \aff using int(\y*2)]in {1,...,5}{
\draw [] (.15,\incrmnt*\y) -- +(0:-.3) node [left] {\aff};
}

\draw[ybar,bar width=2cm,pattern=north west lines
]
plot coordinates{(2,3.5)  (7,5.5) (12,2)
};
\node[below] at (2,0) {Pass};
\node[below] at (7,0) {Good};
\node[below] at (12,0) {V. Good};
\end{tikzpicture}

\end{frame}
\end{document}

Translated with www.DeepL.com/Translator


text:
Q: Parsing serialized string examples using TF-SLIM I am trying to parse data using the TF-SLIM dataset classes.
I am combining two images into a 640x480x6 numpy array (because I combine the RGB channels of both the images) and serializing them to save them to a .tfrecords file. Here's the code to do so.
img_pair = combine_images(images[i][0],images[i][1])
img_flo = read_flo_file(labels[i][0])

height = img_pair.shape[0]
width = img_pair.shape[1]

img = img_pair.tostring()
flo = img_flo.tostring()

example = image_to_tfexample(
        img, height, width, flo)
tfrecord_writer.write(example.SerializeToString())

def image_to_tfexample(image_data, height, width, flo):
  return tf.train.Example(features=tf.train.Features(feature={
      'image/img_pair': bytes_feature(image_data),
      'image/flo': bytes_feature(flo),
      'image/height': int64_feature(height),
      'image/width': int64_feature(width),
  }))

def combine_images(img1,img2):
  img1 = np.array(Image.open(img1))
  img2 = np.array(Image.open(img2))
  return np.concatenate((img1,img2),axis=-1)

Where img_pair is a 640x480x6 numpy array and flo is a 640x480x2 numpy array.
Now I want to read these examples. Here's what I have so far from the tf-slim flower.py (updated to suit me) example.
def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
  if split_name not in SPLITS_TO_SIZES:
    raise ValueError('split name %s was not recognized.' % split_name)

  if not file_pattern:
    file_pattern = _FILE_PATTERN
  file_pattern = os.path.join(dataset_dir, file_pattern % split_name)

  # Allowing None in the signature so that dataset_factory can use the default.
  if reader is None:
    reader = tf.TFRecordReader

  keys_to_features =  {
      'image/width': tf.FixedLenFeature([], tf.int64),
      'image/height': tf.FixedLenFeature([], tf.int64),
      'image/img_pair': tf.FixedLenFeature([], tf.string),
      'image/flo': tf.FixedLenFeature([], tf.string)
  }

  items_to_handlers = {
    'image': slim.tfexample_decoder.Tensor('image/img_pair'),
    'label': slim.tfexample_decoder.Tensor('image/flo'),
  }
  decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features, items_to_handlers)

  return slim.dataset.Dataset(
      data_sources=file_pattern,
      reader=reader,
      decoder=decoder,
      num_samples=SPLITS_TO_SIZES[split_name],
      items_to_descriptions=_ITEMS_TO_DESCRIPTIONS)

The problem here is that image/img_pair and image/flo are binary strings. They first needed to be converted to Tensors in order to feed them as item_handlers, as far as I understood.
Like this.
items_to_handlers = {
    'image': slim.tfexample_decoder.Tensor('image/img_pair'),
    'label': slim.tfexample_decoder.Tensor('image/flo'),
  }

I don't know how to parse it back into the tensor with the same shape i.e. 640x480x6 for img_pair and 640x480x2 for flo.
I get an error.
Will save model to /tmp/tfslim_model/
Traceback (most recent call last):
  File "main.py", line 16, in <module>
    images, _, labels = helpers.load_batch(dataset)
  File "/home/muazzam/mywork/python/thesis/SceneflowTensorflow/new_stuff/helpers.py", line 36, in load_batch
    common_queue_min=8)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/dataset_data_provider.py", line 97, in __init__
    tensors = dataset.decoder.decode(data, items)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py", line 424, in decode
    outputs.append(handler.tensors_to_item(keys_to_tensors))
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py", line 321, in tensors_to_item
    return self._decode(image_buffer, image_format)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py", line 350, in _decode
    pred_fn_pairs, default=decode_image, exclusive=True)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 3169, in case
    case_seq = _build_case()
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 3151, in _build_case
    strict=strict, name="If_%d" % i)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py", line 296, in new_func
    return func(*args, **kwargs)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 1819, in cond
    orig_res_t, res_t = context_t.BuildCondBranch(true_fn)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/control_flow_ops.py", line 1694, in BuildCondBranch
    original_result = fn()
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/slim/python/slim/data/tfexample_decoder.py", line 338, in decode_image
    return image_ops.decode_image(image_buffer, self._channels)
  File "/home/muazzam/anaconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/python/ops/image_ops_impl.py", line 1346, in decode_image
    raise ValueError('channels must be in (None, 0, 1, 3, 4)')
ValueError: channels must be in (None, 0, 1, 3, 4)


text:
Q: How to add python dictionary as a command line argument when running other file? I'm running a python file from another python file using subprocess.call() method.
import job_parser.py

job_info=dict()

job_info['key1']='v1'

job_info['key2']='v2'

job_command="python job_parser.py --job {0}"

subprocess.call(job_command.format(job_info).split())

here I want place this job_info dictionary into the job_command. later I will parse this argument in job_parser.py and use it as dictionary.
I tried doing json.dumps() and converting to a raw string , these methods are not working.
Thanks in Advance

A: subprocess module is for calling external command like you want to run a os command or any external file you can use subprocess module.
If you want call a python script from another python script, you can import and python module and call the required function from imported python module.
in your case you can define a function call entry_point which is like entry point for the task you want to do in job_parser.py.
job_parser.py
def entry_point(input_dict):
    # do_your_stuff

then you call this function like this in you script
import job_parser

job_info=dict()

job_info['key1']='v1'

job_info['key2']='v2'

job_parser.entry_point(job_info)


text:
Q: Display a custom hook in the Back Office in Prestashop 1.7 I am trying to display some content in the default product table of Prestashop. I already managed to override the twig template {% extends 'PrestaShopBundle:Admin/Product/CatalogPage/Lists:list.html.twig' %}.
I verified it by typing a random string in the overriden template and it successfully appeared on the product list.
After that, I created a custom hook in my module with:
$this->registerHook('displayModProfit');
I verified that the hook was registered in the ps_hook database. It was.
I added a method in my module in order to display a test message with the hook. The method is called hookDisplayModProfit.
Then I used {{ renderhook('displayModProfit') }} in the overriden list.html.twig template.
However, it didn't work. Nothing was shown in the spot I wanted the test message to appear. I checked the database and realized that my module is not attached to the hook. I can't find the hook in the Back Office "Positions" tab either.
I read up a bit on this and people suggested adding a custom_hooks entry in the theme.yml file. The problem is, I am not making a theme specific hook. I am making a Back Office hook. How can I attach my module to it?

A: It seems for me that you just forgot to reset your module after custom hook addition. It is necessary to register your hook in the system. Or maybe you didn't add return statement in your method hookDisplayModProfit.
If you follow the next instructions correctly everything should work like a charm

*

*Override your twig template file. Put a file with the same name in the correct directory inside your module. In your case, it is your_module/views/PrestaShop/Admin/Product/CatalogPage/Lists/list.html.twig and extend the original file {% extends 'PrestaShopBundle:Admin/Product/CatalogPage/Lists:list.html.twig' %}. Do not forget that we can only extend a block which exists in the original template. For example:

{% block product_catalog_form_table_row %}
    {{ renderhook('displayModProfit') }}
{% endblock %}

*In your module main php file add $this->registerHook('displayModProfit') to  the install method.

public function install()
{
    return parent::install() && $this->registerHook('displayModProfit');
}

*In your main php file add a method hookDisplayModProfit with a return statement

public function hookDisplayModProfit()
{
    return 'Hello world!';
}

*Reset your module to register the new hook.


text:
Q: Oracle Date - Get 1 Jan of given year I have year as a parameter in proc which can be 2017,2018,etc.
I want get 1 Jan of that year in Date Format in oracle server.
Is there any way to do that ?

A: Assuming your parameter is P_year...
TO_DATE('01/01/'||P_year,'DD/MM/YYYY')

A: You may need something like:
create or replace procedure checkDate ( pYear IN number) is
    vNum number;
begin
    select count(1)
    into vNum
    from ( select sysdate as dateColumn from dual) someTable
    where dateColumn > to_date('01-01-' || pYear, 'dd-mm-yyyy');
    --
    dbms_output.put_line(vNum);
end;

A: Simply converting a year to a date will do the trick
SQL> select to_date('2017','YYYY') from dual;

TO_DATE('2017','YYY
-------------------
01/01/2017 00:00:00

but if you are concerned that at some stage this default might change, you can also truncate the data down to the year to be absolutely sure
SQL> select trunc(to_date('2017','YYYY'),'YYYY') from dual;

TRUNC(TO_DATE('2017
-------------------
01/01/2017 00:00:00

A: As metioned above TRUNC will be best suited in this case.
SET define ON;
SET serveroutput ON;
DECLARE
  lv_var  VARCHAR2(100):='&Enter_year';
  lv_date DATE;
begin
  SELECT TRUNC(to_date(lv_var,'YYYY')) INTO lv_date FROM dual;
  dbms_output.put_line(lv_date||' --> Req date');
END;


text:
Q: Ansible find module does not exclude folder in the search Here is my playbook where i try to find test-juli.jar under /app directory however, i wish to exclude /app/Patchbackup folder from the search.
Below is my playbook for the same:
  tasks:

    - name: Find test home directories under /app
      find:
        paths: /app
        file_type: any
        recurse: yes
        depth: 4
        patterns: 'test-juli.jar'
        excludes: 'log,tmp,.installation,Patchbackup'
      tags: always
      register: tomjarfound

    - debug:
        msg: "ALL LISTED REFINED JARS: {{ item.path }}"
      loop: "{{ tomjarfound.files }}"

When i run the above, i was expecting the find not to find under /app/Patchbackup but the output shows that it does despite being excluded.
Here is the output:
TASK [debug] ***********************************************************************************************************************************************************
ok: [10.0.0.11] => (item=/app/apache-test-9.0.10/bin/test-juli.jar) => {
    "msg": "ALL LISTED REFINED JARS: /app/apache-test-9.0.10/bin/test-juli.jar"
}
ok: [10.0.0.11] => (item=/app/Patchbackup/app/apache-test-9.0.10/bin/test-juli.jar) => {
    "msg": "ALL LISTED REFINED JARS: /app/Patchbackup/app/apache-test-9.0.10/bin/test-juli.jar"
}

Can you please suggest how can I exclude the folder /app/Patchbackup from ansible's find ?

A: The find module is arguably broken.  The excludes parameter applies only to items in the final result set, and not to intermediate directories.
That is, if you have a directory structure like this:
toplevel/
  foo/
    testfile1.txt
  bar/
    testfile2.txt

And from the parent of the toplevel directory you run a task like this:
- find:
    paths: toplevel
    recurse: true
    excludes: foo
  register: results

Your result set will look like:

*

*toplevel/bar/testfile2.txt

*toplevel/foo/testfile1.txt
Compare that to setting file_type: any, like this:
- find:
    paths: toplevel
    file_type: any
    recurse: true
    excludes: foo
  register: results

In this case, the result set will look like:
- `toplevel/bar`
- `toplevel/bar/testfile2.txt`
- `toplevel/foo/testfile1.txt`

Note that toplevel/bar is included in the results, but toplevel/foo is excluded. That's because:

*

*We set file_type: any, which means we want to find directories as well as files.

*This makes toplevel/foo part of the result set.

*We are excluding from the results anything with the basename foo
You will get more flexible behavior if you simply use the find command:
- name: exclude an intermediate directory with find command
  command: >-
    find toplevel -name foo -prune -o -type f -print
  register: result

Which will return the following items:

*

*toplevel/bar/testfile2.txt
I've put a runnable version of the above on github.

A: Ansible's find module's excludes parameter operates on basenames of files. Per the documentation:

excludes: One or more (shell or regex) patterns, which type is controlled by use_regex option. Items whose basenames match an excludes pattern are culled from patterns matches. Multiple patterns can be specified using a list.

In your case, it is correctly ignoring /app/Patchbackup/ because its basename is Patchbackup, but also correctly including /app/Patchbackup/app/apache-test-9.0.10/bin/test-juli.jar because its basename is test-juli.jar.

A: As you realized, the find module doesn't provide you with an option to start with the root dir of /app but exclude one of its directories. You have a few options:

*

*if the dirs under /app are not many, you can use the clause paths to provide a list of them (excluding the undesired Patchbackup)

*retrieve all results under /app and then filter out the ones from /app/Patchbackup that you don't want. Here is an example of how to filter them out:

Code:
  - set_fact:
      my_results_final: "{{ my_results_final | default([]) + [item] }}"
    when: item is not regex('^/app/Patchbackup(.+)')
    with_items:
    - "{{ tomjarfound.files }}"

  - debug:
      var: my_results_final

A: My solution to this omission is to go with json_query filter:
- find:
    paths: /app
    recurse: true
    patterns: 'test-juli.jar'
  register: results

- set_fact:
    final_result: "{{ results | to_json | from_json | json_query(_query) }}"
  vars:
    _query: "files[?!contains(path, 'Patchbackup')]"

you will need to have jmespath python library installed. (if I remember it correctly that | to_json | from_json | part is needed to deal with another types issue.


text:
Q: Custom cross-platform thread dispatcher for console / asp.net application I've got a .NET application that needs to call a COM object (it always has to be called from the same thread). As I have multiple threads in the application, I need to invoke an action on another thread.
The application does not have a (standard) message loop and I don't really like the idea to add WPF / WinForms just to have a Dispatcher.
What would be a safe and effective way to implement a custom "message loop" / queue that allows invoking an Action / Func (with return type) on another thread?
It would also be nice to have a cross-platform solution for this problem.

A: Based on the information of @theodor-zoulias, I came up with this solution.
Disclaimer: Might be that this is actually a very bad design!
public sealed class DispatcherLoop : IDisposable
{
    #region Instance
    private DispatcherLoop() { }

    static Dictionary<int, DispatcherLoop> dispatcherLoops = new();
    public static DispatcherLoop Current
    {
        get
        {
            int threadId = Thread.CurrentThread.ManagedThreadId;
            if (dispatcherLoops.ContainsKey(threadId))
                return dispatcherLoops[threadId];

            DispatcherLoop dispatcherLoop = new()
            {
                ThreadId = Thread.CurrentThread.ManagedThreadId
            };
            dispatcherLoops.Add(threadId, dispatcherLoop);
            return dispatcherLoop;
        }
    }
    #endregion

    bool isDisposed = false;
    public void Dispose()
    {
        if (isDisposed)
            throw new ObjectDisposedException(null);

        _queue.CompleteAdding();
        _queue.Dispose();
        dispatcherLoops.Remove(ThreadId);
        isDisposed = true;
    }

    public int ThreadId { get; private set; } = -1;
    public bool IsRunning { get; private set; } = false;

    BlockingCollection<Task> _queue = new();
    public void Run()
    {
        if (isDisposed)
            throw new ObjectDisposedException(null);

        if (ThreadId != Thread.CurrentThread.ManagedThreadId)
            throw new InvalidOperationException($"The {nameof(DispatcherLoop)} has been created for a different thread!");

        if (IsRunning)
            throw new InvalidOperationException("Already running!");

        IsRunning = true;

        try
        {
            // ToDo: `RunSynchronously` is not guaranteed to be executed on this thread (see comments below)!
            foreach (var task in _queue.GetConsumingEnumerable())
                task?.RunSynchronously();
        }
        catch (ObjectDisposedException) { }

        IsRunning = false;
    }

    public void BeginInvoke(Task task)
    {
        if (isDisposed)
            throw new ObjectDisposedException(null);

        if (!IsRunning)
            throw new InvalidOperationException("Not running!");

        if (ThreadId == Thread.CurrentThread.ManagedThreadId)
            task?.RunSynchronously();
        else
            _queue.Add(task);
    }

    public void Invoke(Action action)
    {
        if (isDisposed)
            throw new ObjectDisposedException(null);

        Task task = new(action);
        BeginInvoke(task);
        task.GetAwaiter().GetResult();
    }

    public T Invoke<T>(Func<T> action)
    {
        if (isDisposed)
            throw new ObjectDisposedException(null);

        Task<T> task = new(action);
        BeginInvoke(task);
        return task.GetAwaiter().GetResult();
    }
}

A: You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive and add using System.Reactive.Linq; - then you can do this:
var els = new EventLoopScheduler();

Then you can do things like this:
els.Schedule(() => Console.WriteLine("Hello, World!"));

The EventLoopScheduler spins up its own thread and you can ask it to schedule any work on it you like - it'll always be that thread.
When you're finished with the scheduler, just call els.Dispose() to shut down it down cleanly.
There are also plenty of overloads for scheduling code in the future. It's a very powerful class.


text:
Q: LINQ to XML - Group by parent element This is my first experience with LINQ to XML, so bear with me.  I'm parsing a Web Services generated XML file for values to insert into SQL Server.  The XML data looks like:
...
    <row>
        <value>912EOE01L0K0</value>
        <value>4369     </value>
        <value>PTO   </value>
        <value>PTO03 </value>
        <value>3 Days PTO     </value>
        <value>1</value>
        <value>0</value>
        <value>0</value>
        <value>1</value>
        <value>0</value>
        <value>0</value>
        <value>7.36</value>
        <value>0</value>
        <value>0</value>
    </row>
    <row>
        <value>912EOE01L0K0</value>
        <value>4369     </value>
        <value>SICK  </value>
        <value>SCK07 </value>
        <value>7 Sick Days    </value>
        <value>2.34</value>
        <value>0</value>
        <value>0</value>
        <value>2.34</value>
        <value>0</value>
        <value>0</value>
        <value>35.979999</value>
        <value>0</value>
        <value>0</value>
    </row>
...

The C# class that is doing the parsing needs to be dynamic to handle a variable number of rows and values within each row, though I do know how many values will be in each row once I start parsing.  I want to group (pivot?) all of the values in a row into a single object, String and comma separated if possible.  I know I could do this by pulling all of the values into a list, then iterating through them and grouping every X into a "row" object, where X is the number of values in each row but it feels like there should be a more LINQ-y way to do this.  Is there a LINQ query that will for each row, group all of the values into a single object?
Thanks.

A: This is a great application for Linq-to-Xml.  Once you've got the XML loaded into an XDocument, you can write this:
XDocument MyXDoc;
// TODO, load or parse MyXDoc

string[] CsvList = MyXDoc.Root.Elements("row")
    .Select(row =>
        String.Join(", ", row.Elements("value").Select(val => (string)val).ToArray() )
     )
    .ToArray();

This will give you an array of each row with the values represented as a CSV string.


text:
Q: ¿How can i add an npm install --force when i execute ionic build android? I execute this command
ionic capacitor sync android

But i had this conflictive modules ->
C:\Users\DELL\Documents\inspecciones\inpecciones-app>ionic capacitor sync android
> npm.cmd i -E @capacitor/android@3.1.1
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @angular-devkit/build-angular@15.1.5
npm ERR! Found: @angular/compiler-cli@12.0.5
npm ERR! node_modules/@angular/compiler-cli
npm ERR!   dev @angular/compiler-cli@"~12.0.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/compiler-cli@"^15.0.0" from @angular-devkit/build-angular@15.1.5
npm ERR! node_modules/@angular-devkit/build-angular
npm ERR!   dev @angular-devkit/build-angular@"^15.1.5" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/compiler-cli@15.1.4
npm ERR! node_modules/@angular/compiler-cli
npm ERR!   peer @angular/compiler-cli@"^15.0.0" from @angular-devkit/build-angular@15.1.5
npm ERR!   node_modules/@angular-devkit/build-angular
npm ERR!     dev @angular-devkit/build-angular@"^15.1.5" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\DELL\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\DELL\AppData\Local\npm-cache\_logs\2023-02-14T21_22_36_075Z-debug-0.log
[ERROR] An error occurred while running subprocess npm.

        npm.cmd i -E @capacitor/android@3.1.1 exited with exit code 1.

        Re-running this command with the --verbose flag may provide more information.

So when it runs -> execute an npm i but i want to add an --force

A: In your package.json you can define custom scripts that can run multiple commands after each other.
Below is an Implementation that

*

*installs npm Packages with -force flag

*builds your ionic project

*syncs your ionic build with your android build

*opens android studio with your android project

To implement add this to your package.json:
"scripts":
{
    "android": "npm i -force && ionic build && ionic capacitor sync android && ionic capacitor open android"
}

The script can be called with

npm run %script name%

So in this case:

npm run android


text:
Q: Gutenberg InnerBlocks predefined block supports I am using a template for InnerBlocks and adding predefined attributes like heading level and paragraph placeholder:
const MY_TEMPLATE = [
    [ 'core/image', {} ],
    [ 'core/heading', { level: 3 } ],
    [ 'core/paragraph', { placeholder: 'Summary' } ],
];

//...

    edit: () => {
        return (
            <InnerBlocks
                template={ MY_TEMPLATE }
                templateLock="all"
            />
        );
    },

This works well but how can we add predefined values for block supports?
For example when registering a block I can set support values:
supports: {
    className: false // Remove the support for the generated className.
    color: { // Text UI control is enabled.
        background: false, // Disable background UI control.
        gradients: true // Enable gradients UI control.
    }
}

How can I set values for supports through InnerBlocks templates? For example I want to remove the default wp-block- class name from a block. I tried:
const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { classname: false } } ],
  [ 'core/heading', {} ]
];

The supports is not passed to the block. How can I make this work? Or is there another way.

A: Your template for InnerBlocks has a small typo in supports: { classname: false } (it's case-sensitive) and should be className:
const MY_TEMPLATE = [
  [ 'my-block/icon', { supports: { className: false } } ],
  ...
];

The supports definition is correct in your my-block/icon block registration. Assuming your save() function handles <InnerBlocks.Content>correctly, with the className typo fixed, it should work.
When in the Editor view and inspecting the classes applied to your block, there will still be many more classes (eg. "wp-block-my-block etc") applied to your block - they are needed to enable the Editors functionality. To confirm if the supports on the inner blocks are working, check the classes applied on the frontend once the post/page is published.


text:
Q: UIScrollVIew View I'm using iCarousel as a slot machine, for those who doesn't know iCarousel it is a UIScrollview with  (paged, scrolling views). So in my app, I scroll it, then when it stops it shows the Image(Result) for 3 seconds, then a button pop-ups, if you press the button, it will delete the View(Image Result) then Rotates again.
Here is my way of deleting my carousel view:
    NSInteger CurrentImage = carousel.currentItemIndex;
    [carousel removeItemAtIndex:CurrentImage animated:YES];
    [images removeObjectAtIndex:CurrentImage];

But then when the carousel.numberOfItems has 1 item left, it doesnt scroll, instead its just stuck there.
So I made a way to make it scroll even it has only 1 Item(index) left.
I inserted it with the last index, so I tried this:
[self.carousel insertItemAtIndex:0 animated:NO];

(but doesnt work)
then I tried another:
int lastObject = [images objectAtIndex: ([images count]-1)]
[self.carousel insertItemAtIndex:lastObject animated:NO];

(still doesnt work)
and also this:
int count = [images count];
[images objectAtIndex:count - 1];

(still no luck)
Am I doing wrong? or What are other ways?
Or can I just duplicate the last View? Thanks for the help.
EDIT:
Methods
     - (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel
    {
        if ([images count] == 1 || [self.carousel numberOfItems] == 1)
            return 2;

        return [images count];
    }

    - (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel
    {
        //limit the number of items views loaded concurrently (for performance reasons)
        return 7;
    }

    - (UIView *)carousel:(iCarousel *)_carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view
    {

        if (index >= [images count] || index >= [carousel numberOfItems]) {
            index = 0;
        }

        NSDictionary *obj = [images objectAtIndex:index];
        view = [[UIImageView alloc] initWithImage:[obj objectForKey:@"image"]];
        view.tag = index;

        return view;
    }

    - (NSUInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
    {
        //note: placeholder views are only displayed on some carousels if wrapping is disabled
        return 0;
    }

    - (CGFloat)carouselItemWidth:(iCarousel *)carousel
    {
        //usually this should be slightly wider than the item views
        return 400;
    }

 - (BOOL)carousel:(iCarousel *)carousel shouldSelectItemAtIndex:(NSInteger)index{
    return 5;
}
    - (BOOL)carouselShouldWrap:(iCarousel *)carousel
    {
        //wrap all carousels
        return wrap;
    }

Delete Method:
-(void) deleteItem{
    //Removes the object chosen
    if (carousel.numberOfItems >= 1)
    {
        NSInteger index = carousel.currentItemIndex;
        [carousel removeItemAtIndex:index animated:YES];
        //[images removeObjectAtIndex:index];
        //[images replaceObjectAtIndex:index withObject:[NSNull null]];
    }

}

A: What you could do is make
- (NSUInteger)numberOfItemsInCarousel:(iCarousel*)carousel;

return always a value >1 (eg. 2); then make sure that
- (UIView*)carousel:(iCarousel*)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView*)view;

always returns a correct view for the minimum number of elements you return from numberOfItemsInCarousel.
Eg.
- (NSUInteger)numberOfItemsInCarousel:(iCarousel*)carousel {
   if (numberOfViews == 1)
      return 2;
   return numberOfViews;
}

- (UIView*)carousel:(iCarousel*)carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView*)view {

  if (index >= numberOfViews) {
      index = 0;
  }

  NSDictionary *obj = [images objectAtIndex:index];
  view = [[UIImageView alloc] initWithImage:[obj objectForKey:@"image"]];
  view.tag = index;
  return view;
}

You should also make sure that the last element is never deleted of add some guards in the code above to manage the case when no elements are left.


text:
Q: calculating areas of polygons in R in a for loop Dear people of stackoverflow.
I am trying to calculate the area of each separate polygon of a SPDF. I am trying to make a function of it which allows me to put the data in and get a list of areas out. I am stuck with creating a for loop that returns all areas of my polygons. For the surface calculation of one polygon the following code works:
surfacefirstpolygon <- gArea(inputSPDF[1,1])

This code prints the i's one by one when I run the following code.
polys <- slot(inputSPDF,"polygons")
for(i in 1:length(polys)){
  print(i)
}

Then I try to put these pieces of code together in a for loop by doing the following:
polys <- slot(inputSPDF,"polygons")
areasofpolygons <- for(i in 1:length(polys)){
  gArea(inputSPDF[i,i])
}

This does not work and gives me the following error.
Error in is.projected(spgeom) :
  error in evaluating the argument 'obj' in selecting a method for function 'is.projected': Error in [.data.frame(x@data, i, j, ..., drop = FALSE) :
  undefined columns selected.
Anybody know what is going wrong?
Result =
dd = dim(inputSPDF)
for(i in 1:dd[1]){
   areasofpolygons[i] <- gArea(inputSPDF[i,1])
}

A: Try:
dd = dim(inputSPDF)
for(i in 1:dd[1]) for(j in 1:dd[2]){
      areasofpolygons[length(areasofpolygons)+1] = gArea(inputSPDF[i,j])
    }
areasofpolygons

The error mentioned in the question probably indicates that i is exceeding the dimensions ("undefined columns selected"). Also, only identical row and column numbers will be accessed if [i,i] is used.


text:
Q: How to convert Datetime.utcnow to DateTime,UTCtoLocal()? when convert utcnow to local time, it shows error like

"LINQ to Entities does not recognize the method 'System.DateTime
  ToLocalTime()' method, and this method cannot be translated into a
  store expression."

I am using SQL Server 2014 and not mango db. It will work when I use the function UTCtoLocal outside the query. But I need to use it within the linq query to speed up the execution. There is any other way to do that.
group new
{
    Id = ord.Id,
    ShipmentInfoId = shipment.Id,
    PartnerName = partner.Name,
    PartNumber = ordItem.SellerProductID,
    OrderNumber = ord.UniqueOrderID,
    PartCount = shipment.PartCount,
    DeliveryDate = ord.DeliveryDate,
    IsSentInvoice = shipment.IsSentInvoice != null ? shipment.IsSentInvoice : false,
    IsSentASN = shipment.IsSentASN != null ? shipment.IsSentASN : false,
    ShippingPartCount = 0,
    IsManualEntered = ord.IsManualEntered,
    LastGeneratedInvoiceDate = shipment.LastGeneratedInvoiceDate.Value.UtcToLocal(),
    LastGeneratedASNDate = shipment.LastGeneratedASNDate.Value.UtcToLocal(),

A: Solution here by playing around with your DateTimeKind.Utc and ToLocalTime()
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
Console.WriteLine(s);

Source: datetime to string with time zone


text:
Q: How to rotate skeleton segments in Three JS skinning example? I would like to use this Three JS example in my project. But I have my own dataset of movements I would like to implement, consisting of quaternion rotations of each segment (hands, arms, trunk...). However, I am new to using Three JS and JavaScript in general. Can I access the skeleton parts in
skeleton = new THREE.SkeletonHelper( model );

and apply the rotations? and how?
E.g. I would like to apply the following rotation to the elbow joint:
quat = [0.5412077307701111,-0.5664581656455994,-0.34294596314430237,-0.5182857513427734]

A: You can apply the following code to get the specific joint and then apply the quaternion as so:
rightArm = model.getObjectByName( 'mixamorigRightArm' );

rightArm.quaternion.set(w,x,y,z);


text:
Q: Howto Isolate a computer from my network using a billion 7800n and a busybox prompt My only router is a billion 7800n connected to the internet using the ewan port.  I have 4 computers connected to it 2 wired and 2 using wifi.  I want to isolate one of the wired ports from seeing the other computers but I still want all of them to access the internet.  It seems impossible to setup using the web gui but i can access a busybox prompt.  Any suggestions on how I would do that.
Thanks Dan

A: You will have to use iptables. Let us assume your router is 192.168.1.1, your normal clients are 192.168.1.2-4, and the one you want to isolate is 192.168.1.100. Then the following rules will do:
iptables -A FORWARD -s 192.168.1.100 -d 192.168.1.2 -j DROP
iptables -A FORWARD -s 192.168.1.100 -d 192.168.1.3 -j DROP
iptables -A FORWARD -s 192.168.1.100 -d 192.168.1.4 -j DROP

In line of principle this should be enough. But if the person using 192.168.1.100 has access (even physical!) to the other machines, it might make sense to prevent the establishment of reverse tunnels, in which case I would add these rules:
iptables -A FORWARD -s 192.168.1.2 -d 192.168.1.100 -j DROP
iptables -A FORWARD -s 192.168.1.3 -d 192.168.1.100 -j DROP
iptables -A FORWARD -s 192.168.1.4 -d 192.168.1.100 -j DROP

There are two conditions for this to work: first,  it is essential that the communications through 192.168.1.100 pass through the router. In other words, you must connect 192.168.1.100 to the router, not to a switch. If you connect it to a switch, since it is internal traffic, the switch will be able to forward the communication attempts from 192.168.1.100 to the other pcs connected to the switch without passing through the router, i.e., directly, and the above commands will never be applied. Second, the pcs must always have the same IP addresses; you can achieve this either with static IPs, or with reserved IPs, a feature which is set in your router GUI.
EDIT:
According to Wikipedia,

In computer networking, a single layer-2 network may be partitioned to create multiple distinct broadcast domains, which are mutually isolated so that packets can only pass between them via one or more routers; such a domain is referred to as a Virtual Local Area Network, Virtual LAN or VLAN.

A situation where "packets can only pass between them via one or more routers" is exactly the one I just described. Only difference is 192.168.1.100 would be able to intercept broadcast traffic. Not much use for that here, bt I can still amend the iptables rules in such a way to obtain that effect, if you wish me. Otherwise, the solution I descrive above is identical to the one you are referring to in your comment.


text:
Q: What does "Watermelon makes me clean" mean? I am watching a youtube video, "Largest Watermelon? World's Largest Fruit" and there's a comment with many likes saying:

Watermelon makes me clean

What does the word clean mean here?

A: According to Merriam-Webster, the word clean can be defined as

free from dirt or pollution
free from contamination or disease
UNADULTERATED, PURE

Therefore, the speaker likely had in mind that the consumption, or use of watermelon results in one of the aforementioned states.


text:
Q: Are tempdb allocations released after transaction is commited? In addition to this I am again wondering if the code in a transaction and loop release the tempdb allocations. For the template below:
SET NOCOUNT ON;

WHILE EXISTS(....)
BEGIN

    BEGIN TRY;

        BEGIN TRANSACTION;

        --

            UPDATE TOP(X) ...

        --

        COMMIT TRANSACTION;

    END TRY
    BEGIN CATCH

        IF @@TRANCOUNT > 0
        BEGIN;
            ROLLBACK TRANSACTION;
        END;

        THROW;

    END CATCH;

    WAITFOR DELAY '00:00:01';

END;

In sp_whoisactive I can see millions of tempdb allocations. The question is can these allocations cause tempdb spill or they are summarized and the allocations are release after each transaction commit?


text:
Q: Do the index number and size information of array in crash report remain same as original code? In my android app I am using following proguard rules.
-keepattributes SourceFile,LineNumberTable

-renamesourcefileattribute SourceFile

Following is bug report summary and it does not mention the proper line number and class name. Are the Index number and size mentioned in this report supposed to be same as original or are they changed?
java.lang.IndexOutOfBoundsException: Index: 11, Size: 10
at java.util.ArrayList.get(ArrayList.java:437)
at c.b.a.F.b(SourceFile:21)
at androidx.recyclerview.widget.RecyclerView$a.a(SourceFile:14)
at androidx.recyclerview.widget.RecyclerView$p.a(SourceFile:157)
at androidx.recyclerview.widget.LinearLayoutManager$c.a(SourceFile:10)
at androidx.recyclerview.widget.LinearLayoutManager.a(SourceFile:108)
at androidx.recyclerview.widget.LinearLayoutManager.a(SourceFile:95)
at androidx.recyclerview.widget.LinearLayoutManager.e(SourceFile:119)
at androidx.recyclerview.widget.RecyclerView.f(SourceFile:8)
at androidx.recyclerview.widget.RecyclerView.d(SourceFile:9)
at androidx.recyclerview.widget.RecyclerView.onLayout(SourceFile:2)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at androidx.constraintlayout.widget.ConstraintLayout.onLayout(SourceFile:12)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:757)
at android.view.View.layout(View.java:20710)
at android.view.ViewGroup.layout(ViewGroup.java:6198)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2839)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2366)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1505)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7353)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1100)
at android.view.Choreographer.doCallbacks(Choreographer.java:895)
at android.view.Choreographer.doFrame(Choreographer.java:826)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1086)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6864)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)

A: This exception was removed after removing the call to 11th index of array.So the answer to original question would be yes, the index number and size information of array in crash report remain same as original code.


text:
Q: How can I get same hierarchy from UITestControl same as in CUIT assertion from I am writing small utility on top up MS Coded UI. I want to get same hierarchy from UITestControl as shown in Coded UI assertion form.
I am constructing UITestControl as shown in below code
 UITestControl test = UITestControlFactory.FromPoint(Mouse.Location);

After that I want to get control hierarchy.
Is there any way?
Regards,
Rajendar.

A: test.GetParent().GetChildren();

It will return UITestControlCollection and you can foreach through it


text:
Q: Obtaining the urldata of a background-image with Javascript (possibly using canvas) Let's assume there is a DIV element and it has CSS background-image property.
I want to get urldata(base64) of the background image with Javascript.
I can get urldata of IMG elements but how about this one ?
Thanks.

A: You can obtain the value of the background-image property with window.getComputedStyle, then create a canvas and an image, apply the value to the src of the image, draw it on the canvas, and finally get the data ? =°
function getBgImageData(el,callback) {
  var url,
      image,
      canvas = document.createElement('canvas'),
      ctx = canvas.getContext('2d');

  // Allows el to be an element or an id
  if(typeof el==='string') {
    el = document.getElementById(el);
  }

  // Gets the value of the background-image property
  url = window.getComputedStyle(el,null).backgroundImage;
  // Removes the url("") part
  url = url.substring(5,url.length-2);

  // Creates the image
  image = new Image();
  image.src = url;
  image.onload = function() {
    canvas.width = image.width;
    canvas.height = image.height;
    // Draws the image
    ctx.drawImage(image,0,0);

    if(callback) {
      // Passes the data to the callback function
      callback(canvas.toDataURL());
    }
  };
}

getBgImageData('someId',function(data) {
  alert(data);
});

(getComputedStyle does not work in IE... but neither does Canvas)


text:
Q: Dual power supply switch-over LED circuit I need a simple circuit that work with two LEDs to do the following:

*

*When a 12VDC power supply is on, LED1 must be on and the LED for the battery LED2 must be off.

*When the power supply is of LED1 is off and then LED2 of the battery must come on.

*When the 12V supply is returned, the battery LED must be off and the 12V supply LED is back on.
Bottom circuit was given by someone but I don't know how to incorporate it to the one above.

A: As simple as it is it could be done with one P-channel MOSFET rated for your current & voltages and a small pull-down resistor as long as your battery voltage less than DC source (+12V). And the battery voltage also should be high enough for the rated current/gate voltage.

simulate this circuit – Schematic created using CircuitLab
Once V1 source are connected, gate voltage becomes higher than source the M1 are closed and aren't conducting. So LED2 are off. And LED1 are directly powered from V1.
If V1 are disconnected LED1 are powered off. And M1 gate are pulled down to ground via R1 it opens and starts conducting current from BAT1 to LED2.
Note that I didn't put LED current limiting resistors on the schematic, providing you have some sort of integrated LED modules which you can power from DC source and battery already directly.

A: Connect a SPDT relay to the 12 V supply, and use the contacts to switch between the 12 V supply and the battery.


text:
Q: C# Constructors Ambiguity with explicit call - Error CS0012 There is an unexplained ambiguity in C#, where I explicitly try to call a constructor but the compiler thinks it is a different constructor. I will start with showing a short C# architecture we use. Then show a small "working" example I created, and the possible solution to this, but still I like to understand why this happens.
The Architecture:

*

*CLR DLL which bridges the C++ API.

*C# API which uses the bridge level.

*C# Client applications that use the C# API.

*

*Note that the C# Clients are not allowed to use the CLR level.

Example I created
A class in the CLR DLL:
#pragma once

#include <string>

using namespace System;

namespace Inner {
    public ref class AInner
    {
    public:

        AInner() : _data(new std::wstring(L"")) {}

        ~AInner() {
            delete _data;
        }

        property String^ Val
        {
            String^ get()
            {
                return gcnew String((*_data).data());
            }

            void set(String^ value) {
                System::IntPtr pVal = System::Runtime::InteropServices::Marshal::StringToHGlobalUni(value);
                *_data = (const wchar_t*)pVal.ToPointer();
                System::Runtime::InteropServices::Marshal::FreeHGlobal(pVal);
            }
        }

    private:

        std::wstring* _data;
    };
}

Class wrapping the CLR level, in a DLL:
using System;

using Inner;

namespace Outer
{
    public class A
    {
        public A()
        {
            _inner.Val = String.Empty;
        }

        public A(string val)
        {
            init(val);
        }

        public string Val
        {
            get
            {
                return _inner.Val;
            }
            set
            {
                _inner.Val = value;
            }
        }

        internal A(AInner inner)
        {
            _inner = inner;
        }

        private void init(string Val)
        {
            _inner = new AInner();
            _inner.Val = String.Empty;
        }

        private AInner _inner;
    }
}

Note that there is an internal constructor and a public constructor.
Executable Client using the C# API DLL:
using Outer;

namespace OneClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string myString = "Some String";
            A testA = new A(myString);
        }
    }
}

Twist in the story:
In the DLL wrapping the CLR level, not ALL API should be used by external clients, but can be used by internal clients, thus the internals are exposed to the internal clients by adding [assembly: InternalsVisibleTo("OneClient")] to the 'AssemblyInfo.cs' of the DLL wrapping the CLR level.
The issue
When compiling the Client code I get the following error:
error CS0012: The type 'AInner' is defined in an assembly that is not referenced. You must add a reference to assembly 'InnerOne, Version=1.0.7600.28169, Culture=neutral, PublicKeyToken=null'.

*

*I cannot use InnerOne because clients are not allowed to use this level.

*The client is exposed to both A(string val) and  A(AInner inner) constructors.

Possible Workarounds:

*

*Remove the [assembly: InternalsVisibleTo("OneClient")] - This is unacceptable due to other classes internals that the specific client needs to use.

*Change the A(string val) constructor to A(string val, bool unique=true) and use it A testA = new A(myString, true) - Not a nice solution.

*Use default constructor A() and call testA.Val = myString; - This is actually OK but to much code.

*Change the client code from A testA = new A(myString) to A testA = new A(val:myString); - This is actually the chosen solution.

Question
Why does this ambiguity happen?

*

*I call the A(string val) with the myString which is actually a string value
This is very strange.

Is this a bug in Microsoft compiler?
Example Sources:
Source Code One.zip

A:
Why does this ambiguity happen?

Because to satisfy the constructor overload resolution, the compiler needs to know what all the argument types are, and it doesn't know what an AInner is.
Why not expose the AInner version as a factory method:
static internal A Create(AInner inner)
{
    return new A { _inner = inner };
}

A: I don't see any issue in this, the problem is we are used to do the things in a wrong/briefly way.
The correct answer fot this is:
A testA = new A(val:myString);

Furthermore, all your calls (in this way is a call to a constructor/initializer but it's a call anyway) should be with the parameter name. No one (even me) writes them, but...


text:
Q: Find longest possible sequence for jumps on next bigger number Guys I am thinking on this problem several days and I have no solution even I have lots of experience.
Given a sequence of numbers, calculate the longest possible sequence of jumps from each number.

*

*You can only jump on a number that is greater than the current one

*You can jump on a number, only if there isn't one with a greater value between

*You can jump only from left to right

I have this solution but I need to make it much faster:
 private static List<Integer> slow(int[] numbers){

        int n = numbers.length;

        int initialJump = 0;
        int next = 0;

        List<Integer> list = new ArrayList<>();

        int counter = 0;
        int maxNum = Arrays.stream(numbers).max().getAsInt();
        for (int i = 0; i < n; i++) {
            initialJump = numbers[i];
            if (initialJump == maxNum) {
                list.add(0);
                continue;
            }
            for (int j = i + 1; j < n; j++) {
                next = numbers[j];
                if (initialJump < next) {
                    counter++;
                    initialJump = next;
                }
            }
            list.add(counter);
            counter = 0;
        }

        return list;
    }

Here is example:
Input
1 4 2 6 3 4
Output
2 1 1 0 1 0
Explanation
Element 1:
    1 -> 4 -> 6 (2 jumps)
Element 2:
    4 -> 6 (1 jump)
Element 3:
    2 -> 6 (1 jump)
Element 4:
    6 (0 jumps)
Element 5:
    3 -> 4 (1 jump)
Element 6:
    4 -> (0 jumps)

Do you have any idea?
Here is what I tried :
private static List<Integer> fast(int[] numbers){
    int n = numbers.length;

    int[] jumplist = new int[n];

    int initialJump = 0;
    int count = 0;
    int maxNum = Arrays.stream(numbers).max().getAsInt();

    Map<Integer, Integer> map = new HashMap<>();

    for(int i=n-1; i>=0; i--) {
        if(i-1 >= 0 && map.get(i+1) != null && numbers[i+1] > numbers[i]){
            jumplist[i] = map.get(i+1)+1;
            continue;
        }

        initialJump = numbers[i];

        if (initialJump == maxNum) {
            jumplist[i] = 0;
            continue;
        }
        for(int j=i; j<n; j++) {
            if(initialJump < numbers[j]) {
                count++;
                initialJump = numbers[j];
                map.put(i,count);
            }
        }
        jumplist[i] = count;
        count = 0;
    }

    return Arrays.stream(jumplist).boxed().collect(Collectors.toList());
}

Here is some test code:
        int randomLimit = 50000;
        Random random = new Random();
        List<Integer> randomList = new ArrayList<>();
        for (int i = 0; i < randomLimit; i++) {
            randomList.add(random.ints(0, randomLimit).findFirst().getAsInt());
        }
        System.out.println("Input: " + randomList.stream().limit(20).collect(Collectors.toList()));
        int[] randomArray = randomList.stream().mapToInt(i->i).toArray();

        Instant fastStarts = Instant.now();
        List<Integer> fastRes = fast(randomArray);
        System.out.println(fastRes.stream().limit(20).collect(Collectors.toList()));
        Instant fastEnds = Instant.now();
        System.out.println("fast: " + Duration.between(fastStarts, fastEnds).toMillis());

        Instant slowStarts = Instant.now();
        List<Integer> slowRes = slow(randomArray);
        System.out.println(slowRes.stream().limit(20).collect(Collectors.toList()));
        Instant slowEnds = Instant.now();
        System.out.println("slow: " + Duration.between(slowStarts, slowEnds).toMillis());

        if(slowRes.size() != fastRes.size()){
            System.out.println("Not Equal Result !!");
        }else {
            for (int i = 0; i < slowRes.size(); i++) {
                if (!slowRes.get(i).equals(fastRes.get(i))) {
                    System.out.println("Not Equal Result !!");
                    break;
                }
            }
        }

A: Here is some optimized code but I need more optimized ...
   private static List<Integer> fast(int[] numbers){
        int n = numbers.length;
        int[] jumplist = new int[n];
        Arrays.fill(jumplist, -1);
        int initialJump = 0;
        int count = 0;
        int maxNum = Arrays.stream(numbers).max().getAsInt();

        for(int i=n-1; i>=0; i--) {

            if(i+1 < n && jumplist[i+1] != -1 && numbers[i+1] > numbers[i]){
                jumplist[i] = jumplist[i+1] + 1;
                continue;
            }

            initialJump = numbers[i];
            if (initialJump == maxNum) {
                jumplist[i] = 0;
                continue;
            }
            for(int j=i+1; j<n; j++) {
                if(initialJump < numbers[j]) {
                    count++;
                    initialJump = numbers[j];
                }
            }
            jumplist[i] = count;
            count = 0;
        }

        return Arrays.stream(jumplist).boxed().collect(Collectors.toList());
    }


text:
Q: PHP wordpress string formatting error I have a bit of PHP where I want to store a URL in a string.
The code itself seems fine, but for some reason, when I use the characters $sectionId=, it causes problems, in fact, it alters $sectionId= and changes it to §ionId=.
If I misspell it to $secionId then it works fine.
The full url SHOULD be:
http://url.com/file.php?appKey=$appkey&storeId=$storeid&sectionId=$sectionid&v=3

but when I do an echo $myURL; on it, it gives me:
http://url.com/file.php?appKey=$appkey&storeId=$storeid§ionId=$sectionid&v=3

Notice the §ionId= instead of $sectionId=.
Can anyone help me with this? It seems like basic PHP, but I don't understand why it just doesnt like those 4 or 5 characters in a row!!
Thanks.

A: Are you echoing it right to HTML? Well, some over-helpful browsers will do character conversions without being asked explicitly to with a semicolon; all you need to do is run it through htmlentities or replace all &s with & and it will display correctly.


text:
Q: script name in setup.py, why do I need file extension for script filename? Related to my previous answer--I am very new to using setup.py to distribute python packages.
According to python documentation, when passing script parameters to setup() in the setup.py file, it looks like you should use the script name without file extension.
setup(...,
      scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
      )

However, I found for my own test case that I needed to add the ".py" extension to the script parameter in order for packaging to work.  E.g.:
config = {...
    'scripts': ['bin/testscript3.py'],
    }
....

setup(**config)

Am I doing something wrong, or is that the expected behavior?  My guess is that this is expected, but I am just confused by the python documentation.  I do realize this may have a trivial explanation, but after some googling I couldn't figure it out, and maybe some other newbies will benefit from this question.  Thanks!

A: You must write the script name exactly as it is represented on your file system.
I think you're confused by the documentation as, on some platforms (Unix), filename extensions are not a standard way to choose in which program a file will be executed (look for "unix shebang" if you want to learn more), so, often, there is not filenames extensions on scripts.


text:
Q: Play Framework JSON Reader and custom JSErrors I'm trying to read a JSON that could have the following parameters coming from the client
{
   "email" : "foobar@gmail.com",
   "password" : "XXXX",
   "facebookToken": "XXXXXXXXXXX"
}

The facebookToken could be Null or Not present, in which case the Email/Password should be filled, and vice versa.
I'm having trouble constructing this Reader, here's what I have so far:
val loginEmail = (
  ( __ \ "email").read[String] and
  ( __ \ "password").read[String]
)((email: String, password: String) => new User(email, password))

val loginFacebook = (
  ( __ \ "facebookToken").read[String]
)((facebookToken : String) => new User(facebookToken))

val loginReader(RequestBodyJson) = (
    (RequestBodyJson).read[User](loginEmail) or
    (RequestBodyJson).read[User](loginFacebook)
)

Can anyone show me how to do this correctly?
I would also like it to return JSError with customized messages. For instance, if the FacebookToken is not present, and there was something wrong with the Email ("Email was Invalid") instead of "/facebookToken path not found" generic error.

A: You can use this tricks:
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError

....
(__ \ "facebookToken").read[String].orElse(Reads(_ => JsError(ValidationError("custom-error"))))

You can return a custom JsError if the main reader fail.


text:
Q: Intercepting queries oracle database 11g (e-business suite) I want to know which tables the oracle application is using in order to obtain the contact information for a certain customer.
So, i go to the application (html page),i put my username and password. Then, i write the account number and click on "go". Take a look at the picture:

After that, i click on the "communication" button and the contact information appears.
Take a look:

How can i know which tables are used when i click on "go" for that account number?
A friend of mine told me that TOAD was a great tool but i dont know how to use it. Is it free? What query should i use?
Can you help me? I am a little confused :/

A: You can use the below query to get the contact information for a Customer at Party and Party Site levels.
SELECT DISTINCT hp.party_id,
                   hp.party_name,
                   hca.cust_account_id,
                   hca.account_number,
                   party_site_id,
                   party_site_number,
                   hcp.phone_number,
                   NVL (hcp.email_address, hcp.url) email_or_url,
                   hcp.contact_point_type communication_type,
                   hcp.status active,
                   hcp.contact_point_purpose purpose
     FROM apps.hz_contact_points hcp,
          apps.hz_party_sites hps,
          apps.hz_cust_accounts hca,
          apps.hz_parties hp
    WHERE     hps.party_id = hca.party_id
          AND hp.party_id = hca.party_id
          AND hcp.contact_point_type IN ('PHONE','EMAIL')
          AND hcp.owner_table_name = 'HZ_PARTIES'
          AND hcp.owner_table_id = hps.party_id
          AND hcp.status = 'A'
          AND hps.status = 'A'
          AND hca.status = 'A'
          AND hp.status = 'A'
   UNION
   SELECT DISTINCT hp.party_id,
                   hp.party_name,
                   hca.cust_account_id,
                   hca.account_number,
                   party_site_id,
                   party_site_number,
                   hcp.phone_number,
                   NVL (hcp.email_address, hcp.url) email_or_url,
                   hcp.contact_point_type communication_type,
                   hcp.status active,
                   hcp.contact_point_purpose purpose
     FROM apps.hz_contact_points hcp,
          apps.hz_party_sites hps,
          apps.hz_cust_accounts hca,
          apps.hz_parties hp
    WHERE     hps.party_id = hca.party_id
          AND hp.party_id = hca.party_id
          AND hcp.contact_point_type IN ('PHONE','EMAIL')
          AND hcp.owner_table_name = 'HZ_PARTY_SITES'
          AND hcp.owner_table_id = hps.party_site_id
          AND hcp.status = 'A'
          AND hps.status = 'A'
          AND hp.status = 'A'
          AND hca.status = 'A';

Hope this is helpful.

A: This question was answered already in thread: Trying to know which tables are executed in the oracle external application
You would need to look in v$sqlarea or if the SQLs execute slowly enough, you will find them in v$active_session_history. To retrieve the EBS specific user and responsibility information, you can use our active session history Blitz Report.


text:
Q: Recover original timestamp after command line copy Is it possible to recover the original time stamp (date added, date modified) of files after copying them (command line, cp -r folder) The original files are gone.

A: On some Unix-based systems you can say

touch –r file1   file2

to set the modification time of file2 to that of file1.
(In this case -r stands for reference, I believe.)
If you copied an entire directory, as in cp -r old new, then try
cd old
find . –exec touch -r {} ../new/{}

Proceed with care; I haven't tested this.

A: You can use the cp -p flag.
-p    Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions.


text:
Q: npm package to use with angular to create a tree like structure? I am working with Angular 4 and I want to implement a tree like structure in my app. I noticed there are tons of packages for this, but I don't know which one to use.
I tested angular2-tree-component and the tree structure is ok, but I want to display some html content for each node when clicked and I'm not sure this can be done using angular2-tree-component.


text:
Q: Auto-translate a web page, using Google Translator I'm need to modify my code, in order to automatically translate a web page, even (if it's possible) to hide the button for translation:

This is what I've tried:

This is the error that I get:

Uncaught TypeError: Cannot read property 'dispatchEvent' of undefined


text:
Q: Meteor event handler : target. not defined My template is as below:
    <template name="dashboard">

            Register Your bills

{{ #each Utilities}}
        {{.}}

    {{ #each Billers . }}
                    {{state}}

                    ==> Adding event handler for this element {{name}}

    {{ /each }}

{{ /each }}

</template>

In the above HTML, I've added a pointer to which element I'm adding a event handler to. This 'a' class element is part of a hierarchical list, and is 2 levels below the root of the hierarchy. That is, it appears on the page when two higher level links are clicked.
The event handler code is as below:
Template.dashboard.events({
    "click .billername":function(event){
        console.log(event.currentTarget.billername);
    }
});

billername is the name attribute of the  element. However, console.log prints undefined. I don't understand why this is happening..
Update:
The method mentioned in the comment below worked for me. But what is the reason the method above didn't work? That is the method documented by Meteor and numerous other tutorials..I was planning to use event.target.billername.value as suggested everywhere, but event.target.billername itself was undefined


text:
Q: Multiple lists with multiple options I'm trying to create 3 different lists with the first containing different car brands, the second the model of the car and the third the motor of the car.
Once the user has selected the first option, which is the car brand he should then get the options for that car in the next drop-down list and from that option the third drop-down list should adjust to that specific model.
If my explanation was too hard to understand here's an example of the exact thing I'm trying to create. http://www.quantumtuning.se/?page_id=36
Would appriciate if someone could hand me a link to a guide or explanation somewhere because I've been looking everywhere without success.

A: as KJ said - also, you could use jQuery change() eventlistener to see when the value changes, and the repopulate another select box:
<select id="make">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select

>
JS:
$('#make').change(function(e){

    switch($(this).val()){
      case 'volvo':
          //code to populate model list
      break;
      case 'saab':
          //code to populate model list
      break;
      //etc...
    }
});


text:
Q: Mountain Lion : Password expiration for OS X that is currently bound to an Active Directory We have 10 MacBook Pro Mountain Lion  that is currently bound to an Active Directory. AD password expiration date time is 42 days.
My questions are :
1 - Is remind us our password is expiring like Windows OS? or is there any notification related to this?
2 - Let's say MAC users wants change their password. How to reset MAC user's expired passwords ?
is there any equivalent like CTRL+ALT+DELETE combination in windows?
Because when to changing my password in the System Preferences, but that did NOT change my AD password. Am I wrong or correct?

A: (1) The only notification on the newer Mac OS releases is a prompt at the login screen once you successfully authenticate.  As it starts to login it receives the notification from AD that your password is set to expire in X number of days.  For instance, if AD is set to remind users of their password expiration 10 days before it expires then the prompt will be along the lines of "Your password is set to expire in 10 days.  Click change password to change your password or continue to continue logging in."
If you click continue you will continue logging in and you can change your password later.  If you click change password you will be prompted to enter a new AD password.  This will update your mobile user accounts password as well, however it will NOT update your keychain password or other passwords stored within your account.  The Mac OS basically treats this like a password reset from outside of the system, just like it would if you reset the password from your recovery partition.  Once you've logged in you will need to update your login.keychain (and now with Mavericks, your local/iCloud.keychain) password to match the new password.  While you're in keychain it would be smart to update any of your saved entries for the old password as well.
(2) I don't think this is correct, although this could be the case if you were not connected to your office network.  Updating through System Preferences > Users & Groups > Change Password is actually my preferred method for our users to update their passwords. This process updates the AD password, the local/mobile account password as well as the keychain passwords.  The only thing our users have to do afterwards is update their Outlook and phone system password entries in their login.keychain and on their iPads & iPhones.  This process only works when you're connected to the network where your Active Directory resides.  When my users are outside of our network (away from the office) they can change their passwords using the option in Microsoft Outlook Web Access.  This is also the only place they'll receive the password expiring in X number of days warning when they're outside of the network.  When they come back to the office they will need to login while connected to the network in order to update the password, then update their keychain password.
So my recommended method for our users is this.
If you're in the office:

*

*Click continue to login without changing your password

*Put your iPad and/or iPhone into Airplane Mode (to prevent account lockout during the process)

*Open System Preferences > Users & Groups, select your account and click Change Password

*Open Keychain Access (Applications/Utilities) and find the entry for your Exchange account.  Double click it to open and change the stored password.  Repeat this for our phone system (it uses AD credentials) entry in keychain.

*On your iPad and/or iPhone, go to Mail, Contacts & Calendars > Work Account > Account and enter your new password.  Disable Airplane Mode once you're finished.

If you're away from the office and it can't wait:

*

*Put your iPad and/or iPhone into Airplane Mode (to prevent account lockout during the process)

*Login to Outlook Web Access

*Click on Options > Password, change your password

*Open Keychain Access (Applications/Utilities) and find the entry for your Exchange account.  Double click it to open and change the stored password.  Repeat this for our phone system (it uses AD credentials) entry in keychain.

*On your iPad and/or iPhone, go to Mail, Contacts & Calendars > Work Account > Account and enter your new password.  Disable Airplane Mode once you're finished.

*Login to your user account when you're back in the office.

*Update your keychain password once you've logged in by opening Keychain Access and clicking Edit > Change password for "login keychain"


text:
Q: Detect if text is highlighted on mouse up jQuery How can I detect if any text is highlighted using jQuery.
I tried:
$(document).mouseup(function(){
    if(typeof window.getSelection!="undefined"){
        console.log("text highlighted");
    }
});

but it dind't work, the console.log() fired each time the mouse click was released, even if there wasn't any highlighted..

A: Try this:
$(document).mouseup(function(){
    var highlightedText = "";
    if (window.getSelection) {
        highlightedText = window.getSelection().toString();
    }
    else if (document.selection && document.selection.type != "Control") {
        highlightedText = document.selection.createRange().text;
    }
    if(highlightedText != "")
        console.log("text highlighted.");
});

A: $(document).on("mouseup", function() {
    if (window.getSelection().toString() != "") {
        console.log("text highlighted :" + window.getSelection().toString());
    }
});

This is another way this could be done


text:
Q: cannot convert html to pdf when file name has a slash I've issue with html convert to pdf when file name have slash(/).
FileSystemException: Cannot open file, path = '/data/user/0/com.example.etelligens/app_flutter/test_insp_CURR/011.html'..
test_insp_CURR/011 is a file name with slash.
Future savePdf(String htmlContents, String pdfFileName) async {
  Directory documentDirectory = await getApplicationDocumentsDirectory();
  String documentPath = documentDirectory.path;
  print(documentPath);
  print(pdfFileName);
  await FlutterHtmlToPdf.convertFromHtmlContent(htmlContents, documentPath, pdfFileName);
}


text:
Q: The Effect of Input and Feedback Capacitors on an Operational Amplifier Open-Loop Gain Response I have the following circuit that I want to compensate:

As shown from the step response, the circuit is unstable because of the high input capacitance (the green plot is without any additional input capacitance, while the blue plot is with the 520 pF input capacitance connected). I plotted the open-loop gain AC response to calculate the phase margin:

As can be seen from the plot above, the phase margin is around 0 degrees. Comparing between the blue and green plot also shows the additional pole caused by the 520 pF input capacitance at around 600 kHz (This cutoff frequency is exactly as calculated with the equation shown after the following paragraph). As a note, to acquire the open-loop gain AC response with LTSpice, I used the method shown in this video.
As explained in an article by Texas Instruments on Op amp stability and input capacitance, adding a feedback capacitor can create an open-loop zero that can compensate for the input capacitance pole. The equation describing the open-loop gain AC response with both input and feedback capacitor is rewritten below:
$$ A\beta = \frac{a R_{G}}{R_{F}+R_{G}}\frac{1+sR_{G}C_{in}}{1+s(R_{F}||R_{G})C_{F}}$$
Inserting the following values to the above equation,
$$C_{in} = 520 pF, R_{G} = 1 k\Omega, R_{F} = 1 k\Omega, C_{F} = 520 pF, $$
yield the pole and zero to completely cancel each other:
$$ A\beta = 0.5a\frac{1+\frac{s}{2\pi(306k)}}{1+\frac{s}{2\pi(306k)}}$$
When I plot the open-loop gain AC response with the component values listed above:

The pole at 300 kHz (originally at 600 kHz) really is gone, keeping the slope at -20 dB/decade at around that frequency. However, there seems to be another pole introduced at around 50 MHz, causing the phase margin to drop to around 0 degrees again and decreasing the slope at high frequencies from -40 dB/decade to -60 dB/decade.
So my question is: Where does this additional pole come from? Why is it that it doesn't show in the equation above?
P.S: Yes, I can find a value for the feedback capacitor that improves the phase margin of the original circuit by sweeping the feedback capacitor value, therefore I don't have any knowledge of why it works, which I want to find out.