Q: Out-Of-Browser Service Access problem using Silverlight 4 I have a Silverlight 4 application that access a couple of WCF Data Services.
There are no problems accessing the service through the browser.
I set the program to run out-of-browser with elevated trust.  Then I can see the calls to the WCF Service via fiddler, but nothing ever comes back.
If I debug then I get the following error:
$exception  {System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at System.Windows.Controls.ItemCollection.GetValueInternal(DependencyProperty dp)
   at System.Windows.PresentationFrameworkCollection`1.get_CountImpl()
   at System.Windows.PresentationFrameworkCollection`1.get_Count()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.RemoveAll()
   at System.Windows.Controls.ItemContainerGenerator.OnRefresh()
   at System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.NotifyCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemCollection.System.Windows.Controls.ICollectionChangedListener.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.WeakCollectionChangedListener.SourceCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)
   at System.Collections.ObjectModel.ObservableCollection`1.ClearItems()
   at System.Collections.ObjectModel.Collection`1.Clear()
   at ClientFolderExplorer.ViewModels.DocumentExplorerViewModel.clientCatalog_ClientsLoadingComplete(Object sender, ClientLoadingEventArgs e)
   at ClientFolderExplorer.Catalogs.ClientCatalog.<>c__DisplayClass3.<ExecuteClientQuery>b__2(IAsyncResult a)}  System.Exception {System.UnauthorizedAccessException}

Not sure where to start troubleshooting.  I have crossdomain.xml and clientaccesspolicy.xml files in place in the root of the webserver, but I cannot even see these files being requested (in fiddler).
Any Ideas?

A: Yes - you suppose the problem is related to cross-site access, while in reality it's related to cross-thread access (first line of error indicates this clearly).
I'm assuming you're trying to set some UI element's data bound (or not, doesn't matter) property directly from the callback handling the service call. (edit) Forgot to clarify - where the callback is running on a thread different from the UI thread. Silverlight like most other frameworks disallows modifying UI except from the UI thread.
If so, take a look at how to use Dispatcher in order to switch back to the UI thread.


Q: Как отсортировать картинки на php? Есть функция search_img() на php, которая выводит все картинки из папки, картинки выводятся по названию (1.jpg, 2,jpg, 3.jpg и так далее). Как можно отсортировать картинки по дате загрузки на php ?
Php:
function search_img($path)
{
    $html = "";
    foreach (glob($path . "*{.jpg,.gif,.png}", GLOB_BRACE) as $filename) {
        $html .= '';
    }
    return $html;
}

echo search_img("uploads/");

Css:
.pimg{
    width:140px;
    max-height:100px;
    float:left;
    margin: 10px;
    background-color:#fff;
    border: 1px solid #999;
    padding:4px;
    border-radius:4px;
    -moz-border-radius:4px;
    -webkit-border-radius:4px;
    box-shadow: 0 0 4px rgba(0,0,0, .5);
    cursor: pointer;
    position:relative;
}

A: Вам нужно пройтись по каждой картинки, вытащить ее дату создания и отсортирвоать по ней.
Примерно так:
function sortFilesByDateCreation($files) {
    $filesWithDates = Array();
    foreach($files as $file) {
        $filesWithDates[$file] = filemtime([ABS_FILES_PATH] . $file);
    }
    asort($filesWithDates);
    return array_keys($pictWithDates);
}

*

*Если надо сортировать в обратном порядке, то вместо asort()
используйте arsort()

*Вам может понадобиться поставить абсолютный путь к файлам: [ABS_FILES_PATH]

A: Вот пример, как можно отсортировать массив по ключам (key это время, а value это название картинки).
function search_img($path){
      $html="";
    foreach (glob($path."*{jpg,gif,png}", GLOB_BRACE) as $filename){
        $file[filemtime($filename)] = $filename ;
    }
    krsort($file);  //Сортировка
    reset($file);

    foreach ($file as $k => $v){
        // echo "Key : $k; Valuе : $v
\n";
        $html .= '';
    }
      return $html;
}

Применение:
echo search_img("uploads/");


Q: Laravel much better of using if so most of time i do this
@if(!empty($variable)
  @if($variable == "yes")
      do something here
  @endif
@endif

well as you can see it really not a beautiful way, maybe (i really hope there is) a much simpler way to just detect if the variable is exist and not throwing error when it is not exist beside that...?
it making my code so crowded and if by anychance i forgot to add those will got beautiful error (well i design a eye cathing error page by the way)
@if(!empty($variable))
or
@if(isempty($variable))

A: Combine the two checks into a single if statement:
@if (! empty($variable) && $variable == 'yes')
    do something here
@endif

A: if you are searching for one line condition, it will work as expected,
  {{!empty($variable) ? $variable == 'yes' ? 'do something' : 'do something else' : 'variable is empty'}}


Q: Installing Win 10 thru a USB 2.0 Pendrive on a USB 3.0 port I have a 2 year old USB 2.0 SanDisk 32 GB pendrive.
My laptop (HP 15s GR0007au) has only 2 USB ports and they're both USB 3.0
Laptop has currently Windows 10 and I will clean install a different version of Win 10 tomorrow.
My question is, will it be a problem during the installation if I use 2.0 drive on a 3.0 port?
As during installation and formatting, the PC will NO LONGER HAVE USB 3.0 drivers. Hence failure during installation?
2 year back I installed Win 7 on a DOS laptop and it straight away warned me to use USB 2.0 port as it didn't have 3.0 drivers then, making that (3.0) port unusable.
Thoughts please, thank you!

A: USB is backwards compatible. The communication across the port will only occur at USB2 speeds, but that will not be a significant issue for installation.
I've installed Windows 10 many times from USB2 drives over USB3 ports, and never had any issues. There's been no need to install drivers or anything.
Windows 7 is a very old OS compared to Windows 10. I would guess your worries based on your previous experience were likely due to the old software being run on newer hardware. Windows 10 is not old software.
UPDATE: Windows 10 includes, baked-in, support for USB3. While it may lack drivers for your specific controller or chipset in the  base image, it can handle the default USB3 protocol without requiring any additional drivers: https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/supported-usb-classes


Q: Cancelación de eco Estoy trabajando en una aplicación que usa el micrófono, y me encuentro con un eco. Todos los ejemplos que encontré de acousticEchoCanceler usan una variable que llaman microphoneId, algo así:
AcousticEchoCanceler acousticEchoCanceler=AcousticEchoCanceler.create(microphoneId);
acousticEchoCanceler.setEnabled(true);

Pero no encuentro de dónde sale esa variable. ¿Ideas?
PD: El proyecto funciona con un patch de Pure Data.


Q: C function macro to take NSString placeholders In my IOS-Project, I have a custom Logger-class (singleton) containing the function
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message

which is globally available through the following preprocessor macro:
#define MyLog(domain, level, message) [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message]

Now when I make the call:
MyLog(@"common", LL_ERROR, @"There was an error!");

Everything works fine. But in practice, the logMessage will sometimes contain string placeholders. So the big question is:
How can I make my macro accept calls like
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);

With the current solution, Xcode complains: "Too many arguments provided to function-like macro invocation".

A: First, you have to change your log method to take a "variable argument list",
for example like this:
- (void)log:(NSString *)domain logLevel:(int)level logMessage:(NSString *)message, ...
{
    va_list argList;
    va_start(argList, message);
    NSString *fullMessage = [[NSString alloc] initWithFormat:message arguments:argList];
    va_end(argList);

    NSLog(@"domain:%@, level:%d: %@", domain, level, fullMessage);
}

Then you have to change your MyLog macro to work with a variable number of arguments.
This is a GNU feature (http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html), that works
with Clang as well:
#define MyLog(domain, level, message, ...) \
   [[MyLogger sharedInstance] log:domain logLevel:level logMessage:message, ##__VA_ARGS__]

Now
MyLog(@"common", LL_ERROR, @"There was an error!");
MyLog(@"common", LL_ERROR, @"There was an error: %@", [error debugDescription]);

should both work without problems.


Q: Requires API level 21 (current min is 16) I'm new in android development and programming. I'm working on android camera application. I'm new in this so I use the lectures of a youtuber who uses API level 21 and I'm using API level 16 for maximum users but our code is same which causes a problem.

call requires API level 21 (current min is 16):android.hardware.camera2.CameraDevice.StateCallback#StateCallback more...CTRL + f1)
Please help me to fix this. I don't want to change its API level to 21.

A: Use 'android.hardware.camera' instead of 'android.hardware.camera2' API and that allows you to use that API with API level 16.


Q: Best practices on upgrading cassandra I am getting errors from pyspark connecting to cassandra because it appears I am using a too old a cassandra:
[idf@node1 python]$ nodetool -h localhost version
ReleaseVersion: 2.0.17
[idf@node1 python]$

[idf@node1 cassandra]$ java --version
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
[idf@node1 cassandra]$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
[idf@node1 cassandra]$

I want to upgrade to the latest version. However, I have already collected quite a bit of data and I don't want to lose it. I am using CentOS 7.2 with a single cassandra node. My questions are,

*

*where is the cassandra data stored on the local file system

*is it correct to assume that I can compress this directory and move it?

Then once I have the data backed up, what is the correct way to upgrade cassandra? Is it

*

*remove old version completely

*install new version

*copy data back

What is the best practice to do this?

A: I'm guessing you are using OSS version. Default location for data is /var/lib/cassandra and you can backup it if you wan't.
Procedure for upgrade is simple:

*

*run nodetool drain

*stop cassandra

*save your cassandra.yaml

*remove old and install new version

*update new cassandra.yaml with your settings

*start cassandra

*run nodetool ugradesstables

This should leave you with your node running the new version of cassandra with all your schema and data in it.
Be careful if you are upgrading past 2.1 because 2.2 and up require java8. Everything else is the same.


Q: cake php form containing file upload not adding enctype="multipart/form-data" attribute I have a controller Job and controller User
I want to send post data from the view of Job Controller  to User controller
the form contains file upload option too
$this->Form->create('User',array('url'=>array('controller'=>'Users','action'=>'newUser')),array('type' =>'file','enctype'=>'multipart/form-data'))

it will give the out put
<form action="/User/newUser" id="UserViewForm" method="post" accept-charset="utf-8">

but it is not adding attribute of enctype="multipart/form-data"
to form

A: Try this
$this->Form->create('User',
array('type' => 'file', 'class' => 'classname', 'url'=>array('controller'=>'Users','action'=>'newUser') ) );

You don't need to create a separate array for the all options.
Docs: Form Options

A: <?php
echo $this->Form->create('User', array('url' => array('controller' => 'Users','action' =>'newUser'),'class'=>'classname','enctype'=>'multipart/form-data'));
?>


Q: how to schedule a notification using firebase messaging I am trying to push a schedule notification to a group of people using firebase messaging, but the only resources I found were for flutter_local_notifications with the scheduling feature. which, as far as I know, work only for the same device I work with and do not send the notification to other devices.
I tried to customize the local schedule notification to send notifications to other devices but I did not know where to add the tokens for other devices


Q: Create waveform with pyaudio and matplotlib in real time I'm looking for a real time graph of an audio input (microphone) and show this data in a waveform graph using matplotlib. How can I show the data on Y axes and the time (seconds) in X axes ?
I don't know anything for audio processing so I learned a lot with docs and examples but I still don't know how to make the graph react in real time.
from scipy.io import wavfile
from matplotlib import pyplot as plt
import numpy as np

# Load the data and calculate the time of each sample
samplerate, data = wavfile.read('audio.wav')
print(samplerate, data)
times = np.arange(len(data))/float(samplerate)

# Make the plot
# You can tweak the figsize (width, height) in inches
plt.figure(figsize=(30, 4))
print(data[:,0])
plt.fill_between(times, data[:,0], data[:,1], color='k')
plt.xlim(times[0], times[-1])
plt.xlabel('time (s)')
plt.ylabel('amplitude')
# You can set the format by changing the extension
# like .pdf, .svg, .eps
plt.savefig('plot.png', dpi=100)
plt.show()

I expect a waveform looking like that but, using my microphone instead of wav file. I tested other things but it was no so concluding...


Q: RegEx JavaScript: Match consecutive single line comments I am trying to write a RegEx to parse groups of single line comments.
Given this input:
//line 1
//line 2
//line 3

//line 4
//line 5
//line 6

I expect to have two matches: Lines 1-3 and 4-6. With my current RegEx (^\/\/[\S\s]+$) I have one match: Lines 1-6, although there is an empty line in between.
The problem is that \s matches any whitespace character, so the blank line is included. But at the same time, line break are part of the RegEx – but only when the line starts with //, so I am stuck.
How can I prevent the RegEx from matching the blank line?

A: You could try this one:
/(^\/\/[^\n]+$\n)+/gm

see here https://regex101.com/r/CrR9WU/1
This selects first the two / at the beginning of each line then anything that is not a newline and finally (at the end of the line) the newline character itself. There are two matches: rows 1 to 3 and rows 4 to 6. If you also allow "empty comment lines like // then this will do too:
/(^\/\/[^\n]*$\n)+/gm

Edit:
I know, it is a little late now, but Casimir's helpful comment got me on to this modified solution:
/(?:^\/\/.*\n?)+/gm

It solves the problem of the final \n, does not capture groups and is simpler. (And it is pretty similar to Jan's solution ;-) ...)

A: This is what modifiers are for:
(?:^\/{2}.+\n?)+

With MULTILINE mode, see a demo on regex101.com.

Broken apart, this says:

(?:       # a non-capturing group
    ^     # start of the line
    \/{2} # //
    .+    # anything else in that line
    \n?   # a newline, eventually but greedy
 )+       # repeat the group


Q: What is the cosine distance of something and itself? I'm playing with scipy's cosine distance. From what I've gathered, the closer a cosine distance is to 1, the more similar the vectors are. I got some unexpected results in a text mining project, so I decided to investigate the simplest case.
import numpy as np
import scipy.spatial
arr1 = np.array([1,1])
arr2 = np.array([1,1])
print scipy.spatial.distance.cosine(arr1, arr2)

My program prints 0.0.
Shouldn't the result be 1.0? Why or why not?

A: It is the cosine distance, not the cosine similarity.  A basic requirement for a function d(u, v) to be a distance is that d(u, u) = 0.
See the definition of the formula in the docstring of scipy.spatial.distance.cosine, and notice that the formula begins 1 - (...).  Your expectation of the function is probably based on the quantity in (...), but that expression is the cosine similarity.


Q: django: Invalid filter I got an article app and trying to make a custom filter, I have a directory called templatetags in article app, and a tags.py within that directory, here is the directory structure.
-manage.py(f)
-settings.py(f)
-articles(d)
 - templatetags(d)
  - tags.py(f)

On the templates, the articles have its own directory, all article templates extend from a base.html template, here is the template structure.
-base.html(f)
-articles(d)
 -index.html(f)

I load the tags in base.html {% load tags %} and use the custom filter in index.html and got the invalid filter error.
tags.py
from django import template
from django.template.defaultfilters import stringfilter

register = template.Library()

@register.filter
@stringfilter
def space2Dash(s):
    return s.replace(' ', '_');

I just can't figure out what I did wrong.
edit:
I changed the filter name to abcfilter.py and I have the article app loaded in my settings.py
articles/index.html
 {% load abcfilter %}
 {{ "foo bar"|space2dash }}

the error:
Request Method: GET
Request URL:    http://localhost:8080/articles/
Django Version: 1.2.5
Exception Type: TemplateSyntaxError
Exception Value:
Invalid filter: 'space2dash'
Exception Location: ***/lib/python2.7/django/template/__init__.py in find_filter, line 363
Python Executable:  /usr/local/bin/python
Python Version: 2.7.1
Server time:    Sun, 10 Apr 2011 07:55:54 -0500

A: Just for reference, I solved the problem by moving
{% load ... %}

from the base template to the concrete template.
See also this post https://stackoverflow.com/a/10427321/3198502

A: To avoid loading the module in each template using {% load MODULE_NAME %}, you can add it as a 'builtin' in settings.py:
TEMPLATES = [
    {
        'OPTIONS': {
            ...
            ,
            'builtins': [
                ...
                'APP_NAME.templatetags.MODULE_NAME',
                ]
        },
    },
]

A: First off remove the semicolon after your replace.
Do you have a file called __init__.py (this is suppose to have 2 underscores before and after init, hard to format in editor.) under the templatetags directory?
Here is a good page with lots of info if you haven't looked yet.
http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

A: I was nearly going nuts with this problem and none of the above answers helped.
If you have several apps, make sure that the file names containing your custom tags/filters are unique, prefereablyapp_name_filters.py. Otherwise Django will only load the custom filters from the app it finds matching first!


Q: LZ4 compression library in android app How do I use LZ4 compression library in my android application...
The main issue I'm facing is when i try to export a signed application package, the error which comes is
Warning: net.jpountz.util.UnsafeUtils: can't find referenced class sun.misc.Unsafe
When I directly run the application in my device, there is no issue, this error comes only when I try to export the application.


Q: Comparing Laurent series coefficients on different annuli Suppose $f$ is analytic on the annulus $\{z : 1/2 < |z|<2\}$ except for the simple pole at $1$. Suppose that the residue of $f$ at $z=1$ is $1$. Let $\sum a_n z^n$ and $\sum b_n z^n$ be the Laurent expansion of $f$ on the annuli $\{ z: 1/2<|z|<1\}$ and $\{z: 1<|z|<2\}$ respectively. Compute $b_n-a_n$ for every integer $n$.
Here is my thought: I know
$$
a_n = \frac{1}{2\pi i}\int_{|z|=3/4}\frac{f(z)}{z^{n+1}}dz
$$
$$
b_n = \frac{1}{2\pi i}\int_{|z|=3/2}\frac{f(z)}{z^{n+1}}dz
$$
Hence $b_n - a_n$ should be the residue of $\dfrac{f(z)}{z^{n+1}}$ at $z=1$, which is $1$. Hence $b_n - a_n=1$ for all $n$.
Is this argument correct?

A: The computation is correct, with the justification for residue as follows:
Since $f(z)$ has a simple pole at $z=1$, $\dfrac{1}{z^{n+1}}$ is holomorphic around $z=1$, using the limit formula $Res(\frac{f(z)}{z^{n+1}})=\lim_{z \to 1} \dfrac{f(z)(z-1)}{z^{n+1}}=\dfrac{\lim_{z \to 1} f(z)(z-1)}{\lim_{z \to 1} z^{n+1}} = \dfrac{Res(f,1)}{1^{n+1}} = 1$.


Q: Custom XPath rule raises violation in pmd but not in sonar I have a quite strange behavior.
I create a XPath rule for PMD 4.2.6 in a file named pmd-extensions.xml :
...
<rule name="AvoidPrintStackTrace-XPath"
  message="Avoid to use printStackTrace - XPath"
  class="net.sourceforge.pmd.rules.XPathRule">
  <description>Avoid to use printStackTrace - XPath</description>
  <properties>
    <property name="xpath">
     <value>
<![CDATA[
//Name[contains (@Image, "printStackTrace")]
]]>
     </value>
    </property>
  </properties>
  <example>
  <![CDATA[
    // don't do this!
    myException.printStackTrace()
   ]]>
   </example>
</rule>
...

I have an unit test validating this rule and working fine:
 ...
 @Before
 public void setUp() {
     addRule("rulesets/pmd-extensions.xml", "AvoidPrintStackTrace-XPath");
 }
 ...

But when I embed this rule in Sonar, the rule doesn't fire any violation while I expected one:
 ...
 <rule key="AvoidPrintStackStrace-XPath" >
  <name>AvoidPrintStackStrace-XPath</name>
  <configKey>rulesets/pmd-extensions.xml/AvoidPrintStackTrace-XPath</configKey>
  <category name="Usability"/>
  <description>Avoid to use printStackTrace - XPath</description>
 </rule>
 ...

And if I declare this rule directly in Sonar (with same XPath expression), the rule fire a violation as expected:
...
<rule key="AvoidPrintStackStrace-XPath-Sonar" priority="MAJOR">
 <name><![CDATA[AvoidPrintStackStrace-XPath-Sonar]]></name>
 <configKey><![CDATA[net.sourceforge.pmd.rules.XPathRule]]></configKey>
 <category name="Maintainability"/>
 <description>Avoid to use printStackTrace - XPath-Sonar</description>
 <param key="xpath" type="s">
  <description><![CDATA[XPath expressions.]]></description>
  <defaultValue>//Name[contains (@Image, "printStackTrace")]</defaultValue>
 </param>
 <param key="message" type="s">
  <description><![CDATA[Message to display when a violation occurs.]]></description>
  <defaultValue>Prevent use of printStackTrace</defaultValue>
 </param>
</rule>
...

What's wrong ?
Thanks.

A: You probably haven't added this new rule to the profile that you are using for your project.
The fact that you provided a "pmd-extensions.xml" file just means that you added this rule to the rule repository. But if you do not activate this rule on a single profile, it will remain inactive and will never get executed.


Q: XSLT, getting values not in order I have an XML like this
    <row>
        <col>1</col>
        <col>name1</col>
        <col>link1</col>
        <col>junk1</col>
        <col>value1</col>
    </row>
    <row>
       <col>2</col>
       <col>name2</col>
       <col>link2</col>
       <col>junk2</col>
       <col>value2</col>
    </row>

how do I write the XSLT to get this output? the third column in each row contains the link and the fourth value does not need to be printed in output

        1
        name1
        value1

        2
        name2
        value

A: Seeing your XSLT would help understand why you get unsorted output. But in any case, try <xsl:sort select="col/text()"/>.

A: The following XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" indent="yes"/>

   <xsl:template match="/table">
      <xsl:copy>
         <xsl:apply-templates select="row">
            <xsl:sort select="col[1]"/>
         </xsl:apply-templates>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="row">

            <xsl:value-of select="col[1]"/>

               <xsl:value-of select="col[2]"/>

            <xsl:value-of select="col[5]"/>

   </xsl:template>
</xsl:stylesheet>

When applied to the following input XML

    <row>
        <col>1</col>
        <col>name1</col>
        <col>link1</col>
        <col>junk1</col>
        <col>value1</col>
    </row>
    <row>
       <col>2</col>
       <col>name2</col>
       <col>link2</col>
       <col>junk2</col>
       <col>value2</col>
    </row>

will produce the following output

      1

         name1

      value1

      2

         name2

      value2

Do note the use of Attribute Value Templates (AVT) to set the href attribute for the a tag:

You can also do away with the xsl:sort should you just wish the order of the rows in the output to be the same as the order in input XML.


Q: STM32 DMA: bytes remaining in buffer, encoded? For quite a while now I've been struggling with DMA communication with two STM32 boards in some form or another. My current issue is as follows.
I have a host (a Raspberry Pi) running the following code, waiting for the board to initialise communication:
#include <fcntl.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    unsigned int usbdev;
    unsigned char c;
    system("stty -F /dev/ttyUSB0 921600 icanon raw");
    usbdev = open("/dev/ttyUSB0", O_RDWR);
    setbuf(stdout, NULL);
    fprintf(stderr, "Waiting for signal..\n");
    while (!read(usbdev, &c, 1));
    unsigned char buf[] = "Defend at noon\r\n";
    write(usbdev, buf, 16);
    fprintf(stderr, "Written 16 bytes\r\n");
    while (1) {
        while (!read(usbdev, &c, 1));
        printf("%c", c);
    }
    return 0;
}

Basically it waits for a single byte of data before it'll send "Defend at noon" to the board, after which it prints everything that is sent back.
The boards first send out a single byte, and then wait for all incoming data, replace a few bytes and send it back. See the code at the end of this post. The board can be either an STM32L100C or an STM32F407 (in practice, the discovery boards); I'm experiencing the same behaviour with both at this point.
The output I'm seeing (on a good day - on a bad day it hangs on Written 16 bytes) is the following:
Waiting for signal..
Written 16 bytes
^JDefend adawnon

As you can see, the data is sent and four bytes are replaced as expected, but there's an extra two characters in front (^J, or 0x5E and 0x4A). These turn out to be a direct consequence of the signal_host function. When I replace the character with something arbitrary (e.g. x), that is what's being output at that position. It is interesting to note that \n actually gets converted to its caret notation ^J somewhere along the road. It appears that this occurs in the communication to the board, because when I simply hardcode a string in the buffer and use dma_transmit to send that to an non-interactive host program, it gets printed just fine.
It looks like I've somehow miss-configured DMA in the sense that there's some buffer that is not being cleared properly. Additionally, I do not really trust the way the host-side program is using stty.. However, I've actually had communication working flawlessly in the past, using this exact code. I compared it to the code stored in my git history across several months, and I cannot find the difference/flaw.
Note that the code below uses libopencm3 and is based on examples from libopencm3-examples.
STM32L1 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>

void clock_setup(void)
{
    rcc_clock_setup_pll(&clock_config[CLOCK_VRANGE1_HSI_PLL_32MHZ]);
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_USART2);
    rcc_periph_clock_enable(RCC_DMA1);
}

void gpio_setup(void)
{
    gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
    gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}

void usart_setup(int baud)
{
    usart_set_baudrate(USART2, baud);
    usart_set_databits(USART2, 8);
    usart_set_stopbits(USART2, USART_STOPBITS_1);
    usart_set_mode(USART2, USART_MODE_TX_RX);
    usart_set_parity(USART2, USART_PARITY_NONE);
    usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);

    usart_enable(USART2);
}

void dma_request_setup(void)
{
    dma_channel_reset(DMA1, DMA_CHANNEL6);

    nvic_enable_irq(NVIC_DMA1_CHANNEL6_IRQ);

    dma_set_peripheral_address(DMA1, DMA_CHANNEL6, (uint32_t) &USART2_DR);
    dma_set_read_from_peripheral(DMA1, DMA_CHANNEL6);

    dma_set_peripheral_size(DMA1, DMA_CHANNEL6, DMA_CCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_CHANNEL6, DMA_CCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_CHANNEL6, DMA_CCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL6);
    dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL6);

    dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL6);
    dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL6);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL6);
}

void dma_transmit_setup(void)
{
    dma_channel_reset(DMA1, DMA_CHANNEL7);

    nvic_enable_irq(NVIC_DMA1_CHANNEL7_IRQ);

    dma_set_peripheral_address(DMA1, DMA_CHANNEL7, (uint32_t) &USART2_DR);
    dma_set_read_from_memory(DMA1, DMA_CHANNEL7);

    dma_set_peripheral_size(DMA1, DMA_CHANNEL7, DMA_CCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_CHANNEL7, DMA_CCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_CHANNEL7, DMA_CCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_CHANNEL7);
    dma_enable_memory_increment_mode(DMA1, DMA_CHANNEL7);

    dma_disable_transfer_error_interrupt(DMA1, DMA_CHANNEL7);
    dma_disable_half_transfer_interrupt(DMA1, DMA_CHANNEL7);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_CHANNEL7);
}

void dma_request(void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_CHANNEL6, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_CHANNEL6, datasize);

    dma_enable_channel(DMA1, DMA_CHANNEL6);
    signal_host();
    usart_enable_rx_dma(USART2);
}

void dma_transmit(const void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_CHANNEL7, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_CHANNEL7, datasize);

    dma_enable_channel(DMA1, DMA_CHANNEL7);
    usart_enable_tx_dma(USART2);
}

int dma_done(void)
{
    return !((DMA1_CCR6 | DMA1_CCR7) & 1);
}

void dma1_channel6_isr(void) {
    usart_disable_rx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_CHANNEL6, DMA_TCIF);
    dma_disable_channel(DMA1, DMA_CHANNEL6);
}

void dma1_channel7_isr(void) {
    usart_disable_tx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_CHANNEL7, DMA_TCIF);
    dma_disable_channel(DMA1, DMA_CHANNEL7);
}

void signal_host(void) {
    usart_send_blocking(USART2, '\n');
}

int main(void)
{
    clock_setup();
    gpio_setup();
    usart_setup(921600);
    dma_transmit_setup();
    dma_request_setup();

    unsigned char buf[16];

    dma_request(buf, 16); while (!dma_done());

    buf[10] = 'd';
    buf[11] = 'a';
    buf[12] = 'w';
    buf[13] = 'n';

    dma_transmit(buf, 16); while (!dma_done());

    while(1);

    return 0;
}

STM32F4 code:
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>
#include <libopencm3/stm32/usart.h>
#include <libopencm3/cm3/nvic.h>
#include <libopencm3/stm32/dma.h>

void clock_setup(void)
{
    rcc_clock_setup_hse_3v3(&hse_8mhz_3v3[CLOCK_3V3_168MHZ]);
    rcc_periph_clock_enable(RCC_GPIOA);
    rcc_periph_clock_enable(RCC_USART2);
    rcc_periph_clock_enable(RCC_DMA1);
}

void gpio_setup(void)
{
    gpio_mode_setup(GPIOA, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO2 | GPIO3);
    gpio_set_af(GPIOA, GPIO_AF7, GPIO2 | GPIO3);
}

void usart_setup(int baud)
{
    usart_set_baudrate(USART2, baud);
    usart_set_databits(USART2, 8);
    usart_set_stopbits(USART2, USART_STOPBITS_1);
    usart_set_mode(USART2, USART_MODE_TX_RX);
    usart_set_parity(USART2, USART_PARITY_NONE);
    usart_set_flow_control(USART2, USART_FLOWCONTROL_NONE);

    usart_enable(USART2);
}

void dma_request_setup(void)
{
    dma_stream_reset(DMA1, DMA_STREAM5);

    nvic_enable_irq(NVIC_DMA1_STREAM5_IRQ);

    dma_set_peripheral_address(DMA1, DMA_STREAM5, (uint32_t) &USART2_DR);
    dma_set_transfer_mode(DMA1, DMA_STREAM5, DMA_SxCR_DIR_PERIPHERAL_TO_MEM);

    dma_set_peripheral_size(DMA1, DMA_STREAM5, DMA_SxCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_STREAM5, DMA_SxCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_STREAM5, DMA_SxCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
    dma_enable_memory_increment_mode(DMA1, DMA_STREAM5);

    dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM5);
    dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM5);
    dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM5);
    dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM5);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM5);
}

void dma_transmit_setup(void)
{
    dma_stream_reset(DMA1, DMA_STREAM6);

    nvic_enable_irq(NVIC_DMA1_STREAM6_IRQ);

    dma_set_peripheral_address(DMA1, DMA_STREAM6, (uint32_t) &USART2_DR);
    dma_set_transfer_mode(DMA1, DMA_STREAM6, DMA_SxCR_DIR_MEM_TO_PERIPHERAL);

    dma_set_peripheral_size(DMA1, DMA_STREAM6, DMA_SxCR_PSIZE_8BIT);
    dma_set_memory_size(DMA1, DMA_STREAM6, DMA_SxCR_MSIZE_8BIT);

    dma_set_priority(DMA1, DMA_STREAM6, DMA_SxCR_PL_VERY_HIGH);

    dma_disable_peripheral_increment_mode(DMA1, DMA_SxCR_CHSEL_4);
    dma_enable_memory_increment_mode(DMA1, DMA_STREAM6);

    dma_disable_transfer_error_interrupt(DMA1, DMA_STREAM6);
    dma_disable_half_transfer_interrupt(DMA1, DMA_STREAM6);
    dma_disable_direct_mode_error_interrupt(DMA1, DMA_STREAM6);
    dma_disable_fifo_error_interrupt(DMA1, DMA_STREAM6);
    dma_enable_transfer_complete_interrupt(DMA1, DMA_STREAM6);
}

void dma_request(void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_STREAM5, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_STREAM5, datasize);

    dma_channel_select(DMA1, DMA_STREAM5, DMA_SxCR_CHSEL_4);
    dma_enable_stream(DMA1, DMA_STREAM5);
    signal_host();
    usart_enable_rx_dma(USART2);
}

void dma_transmit(const void* buffer, const int datasize)
{
    dma_set_memory_address(DMA1, DMA_STREAM6, (uint32_t) buffer);
    dma_set_number_of_data(DMA1, DMA_STREAM6, datasize);

    dma_channel_select(DMA1, DMA_STREAM6, DMA_SxCR_CHSEL_4);
    dma_enable_stream(DMA1, DMA_STREAM6);
    usart_enable_tx_dma(USART2);
}

int dma_done(void)
{
    return !((DMA1_S5CR | DMA1_S6CR) & 1);
}

void dma1_stream5_isr(void) {
    usart_disable_rx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_STREAM5, DMA_TCIF);
    dma_disable_stream(DMA1, DMA_STREAM5);
}

void dma1_stream6_isr(void) {
    usart_disable_tx_dma(USART2);
    dma_clear_interrupt_flags(DMA1, DMA_STREAM6, DMA_TCIF);
    dma_disable_stream(DMA1, DMA_STREAM6);
}

void signal_host(void) {
    usart_send_blocking(USART2, '\n');
}

int main(void)
{
    clock_setup();
    gpio_setup();
    usart_setup(921600);
    dma_transmit_setup();
    dma_request_setup();

    unsigned char buf[16];

    dma_request(buf, 16); while (!dma_done());

    buf[10] = 'd';
    buf[11] = 'a';
    buf[12] = 'w';
    buf[13] = 'n';

    dma_transmit(buf, 16); while (!dma_done());

    while(1);

    return 0;
}

A: Well, I can be brief about this one.
I recommend against using stty for this sort of thing. I realise I have probably not configured stty properly, and with some option-tweaking it is probably possible to get it right, but it's completely unclear. I ended up throwing it out the window and using pyserial instead. I should've done that weeks ago. The above STM32 code works fine and the required Python code is completely trivial.
#!/usr/bin/env python3
import serial

dev = serial.Serial("/dev/ttyUSB0", 921600)

dev.read(1)  # wait for the signal
dev.write("Defend at noon\r\n".encode('utf-8'))

while True:
    x = dev.read()
    print(x.decode('utf-8'), end='', flush=True)


Q: Dijit TabContainer tabs missing, serif fonts, all containers visible I have a small project I am doing, and am using Dojo for it.  At the moment I can't get everything to load properly.  I am trying to use the Tundra theme.
Essentially, the issue is that the TabContainer is missing tabs, has serif fonts instead of sans-serif, and shows all ContentPanes inside it instead of hiding ones in non-active tabs.  The serif issue also applies to all other Dijit elements I try to create, however Dijit form elements seem to work a bit better (apart from font being incorrect, it has correct styling, and validation and other fancy stuff works fine).
The same issue appears when using the other Dijit themes, however the TabContainer border colour changes with each different theme which leads me to believe the Dijit theme may be loading correctly.  Dojo seems to be correctly creating the Dijit elements though, looking at the Firebug output further below.
Complete copies of Dojo 1.3.2 dojo, dijit and dojox directories exist in js/dojo.  All linked stylesheets and scripts are initially loading and the paths to them are correct (I've tested to confirm that with alert boxes in js and body colour changing in css).
index.html
<!DOCTYPE HTML>

<link href="js/dojo/dijit/themes/tundra/tundra.css" rel="stylesheet">

js/script.js
function xmlEnableDiv(div) {
    dojo.require("dijit.layout.TabContainer");
    dojo.require("dijit.layout.ContentPane");

    var tc = new dijit.layout.TabContainer({
    }, div);

    var cp1 = new dijit.layout.ContentPane({
        id: "xmleditor",
        title: "Editor",
        content: "This is where the editor will actually go"
    });
    tc.addChild(cp1);

    var cp2 = new dijit.layout.ContentPane({
        id: "xmltext",
        title: "Source",
        content: "This is where the source will actually go"
    });
    tc.addChild(cp2);
}

Checking Firebug, I see the following (which to my eyes looks like it should):

This is where the editor will actually go

This is where the source will actually go

The actual output (in Firefox and Chrome) is a box (the TabContainer) with a themed border.  There are no tabs on the TabContainer, and both of the ContentPanes are visible at the same time (both with serif fonts).
The things I've tried without avail:

*

*Doing a dojo.parser.parse() at the end of my init function

*Trying other Dijits.  They act similarly in that they seem to partially load.  Every Dijit has serif fonts instead of sans-serif, but form elements and dialog are both showing correctly apart from the incorrect font

Thanks in advance, this is driving me nuts.

A: The solution was to add startup after creating the TabContainer.
Thanks to this post: http://www.dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/tabcontainer-labels-not-rendering-when-created-programatically
tabContainer = new dijit.layout.TabContainer({
}, div);
tabContainer.startup();

A: Another possibility is that adding TabContainer to a hidden element can have missing tabs, as described above, even after calling startup.  The solution to this is to ensure that the TabContainer receives the resize event.  You can try this yourself by finding the ID of the tab container, and then executing this in the console:
dijit.byId('dijit_layout_TabContainer_0').resize();
If your tabs appear, then you have a resize problem.  Ensure that the parent container handles/passes the resize event to the tab container child.  For example:
    resize: function() {
        this.tabContainer.resize();
    }


Q: Can not access contextVariables in decorator I have python decorator and  I need pass contextVariable inside my decorator or as argument  request_id in function
Step 1: Declare contextVariables and methods
_correlation_id_ctx_var: ContextVar[str] = ContextVar(CORRELATION_ID_CTX_KEY, default=None)
_request_id_ctx_var: ContextVar[str] = ContextVar(REQUEST_ID_CTX_KEY, default=None)

def get_correlation_id() -> str:
    return _correlation_id_ctx_var.get()

def get_request_id() -> str:
    return _request_id_ctx_var.get()

Step 2: The context Variable I declare inside middleware (use FastApi)
@app.middleware("http")
async def log_request(request: Request, call_next):
    correlation_id = _correlation_id_ctx_var.set(request.headers.get('X-Correlation-ID', str(uuid4())))
    request_id = _request_id_ctx_var.set(str(uuid4()))

Step3: I try to pass contextVariable to decorator - it always None
Try to pass as argument in function itself - it always None
What it the problem?
Why contextVars accessible in function body only and not in decorator or argument function?
Is there any solutions to have access to contextVar before function body?
@app.get('/test')
@decorator(request_id=get_request_id())
def test_purpose(request_id=get_request_id()):
    print('get_correlation_id() start', get_request_id())
    return 'ok'

Decorator:
def decorator(request_id=None, *args, **kwargs):
    def logger(func, request_id=None, *args, **kwargs):
        @wraps(func, *args, **kwargs)
        def wrapper(*args, **kwargs):
            try:
                res = func()
                print()
                return res
            except Exception:
              pass
        return wrapper
    return logger

A: @decorator(request_id=get_request_id()) <- this line is executed when your module is imported. Which means your getter function is called only once, when the module is imported, not each time your decorated function is called.
To fix it, just pass the getter function, not its result, to the decorator, and make the call inside the wrapper function, inside the decorator. (For that, just leave the parentheses out):

def decorator(request_id_getter=None, *d_args, **d_kw):
    def logger(func):  # other arguments than the first positional arg here are not used at all.
        @wraps(func, *d_args, **d_kw)
        def wrapper(*args, **kwargs):
            request_id = request_id_getter()  # and here the value is retrieved when the function is actually called
            try:
                res = func()
                print()
                return res
            except Exception:
              pass
        return wrapper
    return logger

@app.get('/test')
@decorator(request_id=get_request_id)  # <- here is the change - do not _call_ the function!
def test_purpose(request_id=get_request_id()):
    print('get_correlation_id() start', get_request_id())
    return 'ok'


Q: Sort simplexml object - without casting to array Is it possible to sort a simplexml object but keep the object as a simplexml object instead of casting to an array.
There doesnt appear to be a way to do this - and if casted to an array it seems very messy to transform the array(s) back to a simplexml object.
So -
Is it possible to sort a simplexml object by an attribute etc.
For example (sort by the position attribute node):
<test_nodes>
  <node position="1"></node>
  <node position="2"></node>
  <node position="3"></node>
</test_nodes>

If not then what is the most painless and efficient way to cast an array to a simple xml object


Q: redirect page with header with string My page cannot redirect to another page using header and below is the code
$v1 = "http://www.google.com";

header('Location: $v1');

instead it redirected to http://localhost/$v1
How can i achieve this type of syntax to redirect

A: Change single quote to double quotes. Note that variables inside the single quotes would not be parsed.
header("Location: $v1");

A: Wrong syntax. Try:
$url = "http://www.google.com/";
header("Location: $url");
//     ^              ^
// You should use double quotes to expand variables.

A: This worked for me:

$v1 = "http://www.google.com";
header('Location:'. $v1);


Q: 4 GPIO 16 Mosfets I have 4 GPIO's and I have to drive 16 mosfets for my application.
MCU -> 4 GPIO -> something must be here(SPI mosfet driver??) -> 16 mosfets
I thought that if I have an SPI mosfet gate driver IC, I can drive 16 mosfets by using 4 GPIO's. If I write my own SPI function.
But I dont know if there is an IC that can drive mosfet's gates by SPI?

A: The general term is "IO expander". This sort of thing:
http://ww1.microchip.com/downloads/en/devicedoc/21952a.pdf
Although you can also do it with a shift register: cheaper, and may have higher drive strength.

A: Just use a shift register (for example 74HC595) to drive the MOSFET gates. You can drive that chip with four GPIO lines (DATA, CLOCK, LATCH, ENABLE).


Q: How to add Lodash debounce to react input? I have a simpel form:
https://codesandbox.io/s/distracted-poincare-2blfq?file=/src/App.js:357-552
      <form>
        <TextField
          onChange={handleChange}
          onBlur={clearInput}
          value={inputValue}
          placeholder="Do an api request"
        />
      </form>

On the onChange I want to do an api request with the value of the input but I would like to add a debounce or throttle. Important is that when the input is blurred the text in the input should be removed and the placeholder should be visible.

A: Method 1.
Use React debounce input, simple method
https://www.npmjs.com/package/react-debounce-input
Method 2
Create timer and call API based on that, no external library needed. and i always suggest this
 let timer = null
 const handleChange = (e) => {
    setInputValue(e.target.value)
    if(timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(()=>yourApiCall(e.target.value), 700)
 }
 const yourApiCall = (val) => {
   //call API here
 }

  <form>
    <TextField
      onChange={handleChange}
      onBlur={clearInput}
      value={inputValue}
      placeholder="Do an api request"
    />
  </form>

a working example
https://codesandbox.io/s/beautiful-goldberg-vyo2u?file=/src/App.js
Method 3
Use loadash debounce
check the answers from this link
Lodash debounce with React Input


Q: php variable in a echo string I'm customizing a wordpress for the first time so I'm pretty new with PHP langage and something is driving me crazy.
I wrote that function to transform my HTML5/CSS3/JQUERY layout into a CMS:
<?php $property = simple_fields_values("pillow_front");
  foreach ($property as $value) {
    echo "
";
      echo "
";
        echo "

";
      echo "
";
    echo "
";
  }
?>

But in the front-end it doesn't work and when I look at the code it appears that the img tag is not closed properly:

I didn't really well understoud if the . in PHP was the exact equivalent of the + in javascript but I tried a lots of thing and I can get that tag to be properly closed !
Thank you

A: You can print in another system, something like this:
<?php
$property = simple_fields_values("pillow_front");
 foreach ($property as $value) {
 ?>

<img src="<?php print wp_get_attachment_url($value);?>"/>

 <?php
 }
 ?>

Please note that i put the echo of the function only because i do not know how it works, it can be not necessary, use php only when needed.

A: Or just a bit more MVC-Pattern or in that case just MV? ;) Try this one without Wordpress.
<?php

    //Init
    $property = simple_fields_values("pillow_front");
    $template = '

';

    foreach ($property as $value) {
        echo str_replace(array('{MARKER:FRONT}'), array($value), $template);
    }
?>

And as i know wordpress view, your code style is not confirm to WP-Styleguide. WP is using HTML/PHP Templating. In WP you view need to look like this.
<?php foreach(simple_fields_values("pillow_front") as $value): ?>

<img src="<?php echo htmlentities(value): ?>"/>

<?php endforeach; ?>


Q: FTP username with | (pipe) in Windows batch file I'm trying to FTP files to a remote location. But here is the issue I'm facing.
When I use the below script, I'm able to login to the remote server but I'm not able to place any files over there, 550 access denied log prompt.
echo user domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt

ftp -n -s ftp.txt Servername>ftp_logs.txt

del ftp.txt

I tried to login via command prompt. I successfully Ftp'd, if the username is like Servername|domain/username.
I modified the script as below, script is not even executing.
echo user Servername|domain/username> ftp.txt
echo password>> ftp.txt
echo cd remotepath>> ftp.txt
echo put FTPTest.txt>>ftp.txt
echo quit>> ftp.txt

ftp -n -s ftp.txt Servername>ftp_logs.txt

del ftp.txt

Searching for clues...

A: You have to escape the |, as that has a special meaning in Windows:
echo user Servername^|domain/username> ftp.txt

The above will get you
user Servername|domain/username

in the ftp.exe.


Q: Binding a field to a reactive form does not show value If I hardcode the value to something like 'xxx' it is fine. But when I call a service and then try to bind the value nothing happens. I thought it was data bound so when the field is set it would show on the UI ?
      <form [formGroup]="saveFileForm" (ngSubmit)="onExpSubmit()">

                Notes:

                <input type="text" formControlName="Notes">

fileData: AttachmentVm = new AttachmentVm();

  constructor(private service: AttachService,
    private formBuilder: FormBuilder,
    private router: Router,
    public dialogRefSpinner: MatDialogRef<DialogRedirectToLandingSpinnerModule>,
    public snackBar: MatSnackBar,
    public dialog: MatDialog,
  ) { }

  ngOnInit(): void {
    this.saveFileForm = this.formBuilder.group({
      PaymentDate: [''],
      IsPaid: [false],
      Notes: [this.fileData.GlobalNotes],
      //Notes: ['xxx'],
      FileDescription: ['']
    });

    if (this.formIdFromParent) {
      this.service.getFiles(this.formIdFromParent).subscribe(result => {
        this.fileData = result;
      })
    }
  }

A: You need to update the form control value:
if (this.formIdFromParent) {
  this.service.getFiles(this.formIdFromParent).subscribe(result => {
     this.fileData = result;
     this.formIdFromParent.controls['Notes'].setValue(this.fileData. GlobalNotes);
  })
}


Q: REDIS LIST MOVE recovery/rollback strategy I have the following scenario:

*

*Redis SENTINEL with one main REDIs and two replicas

*Redis Connection timeout configured to 30 seconds

*Lettuce's Java REDIS client

*Spring Data on top of Lettuce's REDIS client

I have a REDIS LIST which I am using as a QUEUE. As expected, each element on the queue must be processed by one and only one element processor. However, in some weird corner cases, I sometimes experience THIS:
-> BLMOVE A B 8
     (*) I get a timeout here after 30 seconds

(this is, move from list A to list B and block for 8 seconds
The problem I have is that the ELEMENT actually moves from list A to list B and I still get the timeout, so after this exception the element gets lost in queue B and never gets processed. I understand that this might be a network issue with the REDIS CONNECTION.
My question is: What's the best way to handle cases like this? Is there a way to "recover" the unprocessed element and try again?

A: There are a few ways to solve this issue:

*

*Use a REDIS SENTINEL with failover capabilities. This way, if the primary REDIS instance goes down, the sentinel will automatically failover to the replica instance and your elements will not be lost.

*Use a REDIS CLUSTER. This will provide you with high availability and will ensure that your elements are not lost in the event of a failure.

*Use a REDIS Replication setup. This will provide you with a hot standby REDIS instance that can take over if the primary instance goes down.

*Use a REDIS Persistence setup. This will ensure that your elements are not lost in the event of a failure.

*Use a REDIS Backup setup. This will ensure that your elements are not lost in the event of a failure.


Q: My own mini-framework is not compatible with some projects I failed to create a mini-library with some useful functions that I have found over the Internet, and I want to use them easily by just including a file to the HTML (like jQuery).
The problem is that some vars and functions share the same name and they are causing problems.
Is there a better solution to this instead of giving crazy names to the vars/funcs like "bbbb123" so the odds that someone is working with a "bbbb123" var is really low?

A: I would put all of your functions and variables into a single object for your library.
var MyLibrary = {
  myFunc: function() {
    //do stuff
  },

  myVar: "Foo"
}

There are a few different ways of defining 'classes' in JavaScript. Here is a nice page with 3 of them.

A: You should take one variable name in the global namespace that there are low odds of being used, and put everything else underneath it (in its own namespace).
For example, if I wanted to call my library AzureLib:
AzureLib = {
    SortSomething: function(arr) {
        // do some sorting
    },
    DoSomethingCool: function(item) {
        // do something cool
    }
};

// usage (in another JavaScript file or in an HTML <script> tag):
AzureLib.SortSomething(myArray);

A: You could put all of your library's functions inside of a single object.  That way, as long as that object's name doesn't conflict, you will be good.  Something like:
var yourLib = {};

yourLib.usefulFunction1 = function(){
    ..
};

yourLib.usefulFunction2 = function(){
    ..
};

A: Yes, you can create an object as a namespace. There are several ways to do this, syntax-wise, but the end result is approximately the same. Your object name should be the thing that no one else will have used.
var MyLibrary = {

    myFunc: function() { /* stuff */ }

};

Just remember, it's object literal syntax, so you use label : value to put things inside it, and not var label = value;.
If you need to declare things first, use a wrapping function to enclose the environment and protect you from the global scope:
var MyLibrary = (function() {

    var foo = 'bar';

    return {
        myFunc: function() { /* stuff */ }
    };

})(); // execute this function right away to return your library object


Q: Cordova: command not found after installing globally I try to install Cordova in macOS Mojave. I run the following command to install globally. It is installed successfully npm i -g cordova
but when I check the version using cordova --version , It gives me the error "cordova: command not found".
and also when I try to get the location using which cordova, It returns nothing.

A: Refer this great write up: http://blog.webbb.be/command-not-found-node-npm/
This can happen when npm is installing to a location that is not the standard and is not in your path.

To check where npm is installing, run: npm root -g

It SHOULD say /usr/local/lib/node_modules, If it doesn't then follow this:
Set it to the correct PATH:

*

*run: npm config set prefix /usr/local

*Then reinstall your npm package(s) with -g:
npm install -g cordova etc
If this doesn't work then try adding the global path of cordova(where it got installed) to your $PATH variable.


Q: Regex to split the string into identical blocks I wanted to fetch the data an put it in the list from the below XML using regex in python as below
[['ip-address','1.1.1.1/16','protocol','ospf','ll',4],['ip-address','3.3.3.3/32','ip-addr','2.2.2.2','ip-addr','8.8.8.8','type',route]]
a=''' <att>
       <rt>
        <rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>
        <rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>
       <rt>
      </att>'''

My approach was to divide the above single string into multiple string and then search, example
  b=  '''<rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>'''

 c= '''<rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>'''

I used the following regex to create multiple string
regex = re.findall(r"<(rts)>.*<\ /rts)", a, re.S)

But it fetches all untill the end of string as below,
        <rts>
     <ip-address>1.1.1.1/16</ip-address>
     <bb>
      <cc>
       <protocol>ospf</protocol>
      </cc>
     </bb>
     <ee>
      <ff>
       <ll>4</ll>
      </ff>
     </ee>
    </rts>
    <rts>
     <ip-address>3.3.3.3/32</ip-address>
     <bb>
      <cc>
       <ip-addr>2.2.2.2</ip-addr>
       <ip-addr>8.8.8.8</ip-addr>
      </cc>
     </bb>
     <ee>
      <ff>
       <type>route</type>
      </ff>
     </ee>
    </rts>

Is there a way I could be able to divide the string as "b" and "c" shown above?

A: With lxml and xpath you can parse xml much more easily than by rolling your own regex parser.
Here's an example:
import lxml
import StringIO

a =''' <att>
       <rt>
        <rts>
         <ip-address>1.1.1.1/16</ip-address>
         <bb>
          <cc>
           <protocol>ospf</protocol>
          </cc>
         </bb>
         <ee>
          <ff>
           <ll>4</ll>
          </ff>
         </ee>
        </rts>
        <rts>
         <ip-address>3.3.3.3/32</ip-address>
         <bb>
          <cc>
           <ip-addr>2.2.2.2</ip-addr>
           <ip-addr>8.8.8.8</ip-addr>
          </cc>
         </bb>
         <ee>
          <ff>
           <type>route</type>
          </ff>
         </ee>
        </rts>
       </rt>
      </att>'''

f = StringIO.StringIO(a)
tree = lxml.etree.parse(f)

rts = tree.xpath('//rts')

ipa = rts[0].xpath(".//ip-address")[0]

print ipa.text

This prints the first ip-address of the first rts tag, i.e. 1.1.1.1/16.
Note:
I needed to fix your xml, there was a / missing on the last rt tag.


Q: different screen.colorDepth value for firefox and opera/chrome I m testing a javascript in which i wrote this
document.write("\n\n\n\n"+screen.colorDepth);
switch(screen.colorDepth)
{
case 24: document.bgColor = "skyblue" ;
         break;
case 32: document.bgColor = "yellow";
        break;
default: document.bgColor = "white";
        break;
}

but unfortunately Firefox 21.0 and IE9 is showing value 24 and thus background color is going skyblue
and opera( v12.01 Build 1532) and chrome(Version 27.0.1453.94 m) is showing 32 and thus the background is going yellow . I m using win 7 ultimate 32bit and my original color depth of screen is 32 bit. Can anyone plz explain why this is happening ?

A: I guess they are using different approaches interpreting the color precision. A 32-bit screen is in fact only 24-bit color (the 8 last bits is not part of the color space).
Mozilla defines it as:

Returns the color depth of the screen.

Chrome seem to read it directly from the system as-is, while FF and IE9 seem to correctly (based on that definition) identify the color precision (color depth) of the screen.
Please note that screen.colorDepth is not part of any standard and it's up to the implementers how it actually works.
The more correct way of checking color-precision in regards to color depth would therefor be:
case 16: document.bgColor = "..." ;
         break;
case 24:
case 32: document.bgColor = "..."; //32 = 24 bit color depth + 8 bits alpha
         break;


Q: Method that can be used to collect the variables of a function Suppose we have a function f[x, y, z] and we want to get all its variables Sequence[x,y,z], what method can we use then? The only one that I can come up with is like this:
f[x, y, z] /. func_[vars___] -> Sequence[vars]

But it is not very elegant from my point of view. Is there any more suitable method? Thanks!

A: For one thing Sequence is applied automatically to a raw sequence (such as vars) if no other head is found, therefore:
f[x, y, z] /. _[vars___] :> vars

Sequence[x, y, z]

This is similar to what I have been calling the "injector pattern" and as you can see from that thread it has value in cases where Sequence @@ f[x, y, z] would not avail you, specifically inside symbols that will hold Sequence objects.

It is hard to guess your application from the question but you can also define a function, perhaps with additional conditions or handling of multiple forms of input, such as:
varSeq[expr_] :=
 With[{vars = Variables @ expr}, Sequence @@ vars /; MatchQ[vars, {__Symbol}]]

varSeq[_@vars__Symbol] := vars

Now:
f[x, y, z] // varSeq

Sequence[x, y, z]

(x + y)^2 + 3 z^2 - y z + 7 // varSeq

Sequence[x, y, z]

Incidentally if you like terse coding you can also make use of SlotSequence, short form ##, as in:
## & @@ f[x, y, z]

which is equivalent to Sequence @@ f[x, y, z] in most cases.

A: Probably irrelevant but I thought you have some function defined in the Global` context and you want to get the list of its variables. If that is the case I came up with this messy solution.
Suppose you have defined a function like the following somewhere in a notebook and the definition for the symbol fun is available to the kernel as well as not Protected. I am defining the following example function using Module but one can also use Block.
Clear[f];
fun[x_, y_, z_] := Module[{val},
   val = RandomReal[1, 3];
   val . {x, y, z}
   ];

{x,y,z}

Then you can get the arguments of fun using the following
((DownValues[fun])[[1]] /.
RuleDelayed[HoldPattern[a___],b_] :> (Extract[a, 1, Hold] /. Hold[c_[vars___]] :> List@vars))

{x_, y_, z_}

If you want you can easily convert those pattern into Symbol using First /@%.
From the comments a more robust solution came out credit to Mr. Wizard.
Cases[ DownValues[fun], HoldPattern[fun][vars__] :> {vars}, -1 ] /.
Verbatim[Pattern][name_, _] :> name


Q: Swift - UIProgressView is not smooth with NSTimer So I am using an NSTimer to let the user know the app is working. The progress bar is set up to last 3 seconds, but when running, it displays in a 'ticking' motion and it is not smooth like it should be. Is there anyway I can make it more smooth - I'm sure just a calculation error on my part....
If anyone could take a look that would be great. Here is the code:
import UIKit

class LoadingScreen: UIViewController {

    var time : Float = 0.0
    var timer: NSTimer?

    @IBOutlet weak var progressView: UIProgressView!

    override func viewDidLoad() {
        super.viewDidLoad()

// Do stuff

timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)

}//close viewDidLoad

  func setProgress() {
        time += 0.1
        progressView.progress = time / 3
        if time >= 3 {
            timer!.invalidate()
        }
    }

}

A: For continues loader
timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(setProgress), userInfo: nil, repeats: true)

and
func setProgress() {
        time += 0.001
        downloadProgressBar.setProgress(time / 3, animated: true)
        if time >= 3 {
            self.time = 0.001
            downloadProgressBar.progress = 0
            let color = self.downloadProgressBar.progressTintColor
            self.downloadProgressBar.progressTintColor = self.downloadProgressBar.trackTintColor
            self.downloadProgressBar.trackTintColor = color
        }

A: Edit: A simple 3 second UIView animation (Recommended)
If your bar is just moving smoothly to indicate activity, possibly consider using a UIActivityIndicatorView or a custom UIView animation:
override func viewDidAppear(animated: Bool)
{
    super.viewDidAppear(animated)

    UIView.animateWithDuration(3, animations: { () -> Void in
        self.progressView.setProgress(1.0, animated: true)
    })
}

Make sure your progressView's progress is set to zero to begin with. This will result in a smooth 3 second animation of the progress.
Simple animated progress (Works but still jumps a bit)
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIProgressView_Class/#//apple_ref/occ/instm/UIProgressView/setProgress:animated:
func setProgress() {
    time += 0.1
    progressView.setProgress(time / 3, animated: true)
    if time >= 3 {
        timer!.invalidate()
    }
}

Option with smaller intervals. (Not recommended)
Set your timer to a smaller interval:
timer = NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector:Selector("setProgress"), userInfo: nil, repeats: true)

Then update your function
func setProgress() {
    time += 0.001
    progressView.setProgress(time / 3, animated: true)
    if time >= 3 {
        timer!.invalidate()
    }
}

A: It's hard to say exactly what the problem is. I would like to see the output if you put a print line in setProgress to print a timestamp. Is it actually firing every tenth of a second? My guess is that it is not.
Why not? Well, the timer schedules a run loop task in the main thread to execute the code in setProgress. This task cannot run until tasks in front of it in the queue do. So if there are long running tasks happening in your main thread, your timer will fire very imprecisely. My first suggestion is that this is perhaps what is happening.
Here is an example:

*

*You start a timer to do something every second.

*Immediately after, you start a long running main thread task (for example,      you try to write a ton of data to a file). This task will take five seconds to complete.

*Your timer wants to fire after one second, but your file-writing is
hogging the main thread for the next four seconds, so the timer can't fire
for another four seconds.

If this is the case, then to solve the problem you would either need to move that main thread work to a background thread, or else figure out a way to do it while returning to the run loop periodically. For example, during your long running main thread operation, you can periodically call runUntilDate on your run loop to let other run loop tasks execute.
Note that you couldn't just increment the progress bar fill periodically during the long running main thread task, because the progress bar will not actually animate its fill until you return to the run loop.

A: What about proper way for animating changes: animateWithDuration:animations: or CABasicAnimation. You can use this for creating smooth animations


Q: How to use variable and changing user defined functions in query I have defined some user defined function in sql server . for example :
select dbo.SumItems(1 , 2) will return 3
and
select dbo.MaxItems(5 , 3) will return 5
and some other functions may be more complicated.
also I keep variables and their formula expressions in a table:
IdVar Title Formula
----- ----- ---------------------
1     Sum   dbo.SumItems(@a , @b)
2     Max   dbo.maxItems(@a , @b)

I have my parameters in another table :
a   b
--  --
1   2
5   3

now i want to join this two tables and get the following result :
Parameter a   Parameter b  Variable Title  Result
-----------   -----------  --------------  ------
1             2            Sum             3
1             2            Max             2
5             3            Sum             8
5             3            Max             5

also I have asked my problem from another view here.

A: Posted something very similar to this yesterday.  As you know, you can only perform such function with dynamic sql.
Now, I don't have your functions, so you will have to supply those.
I've done something very similar in the past to calculate a series of ratios in one pass for numerous income/balance sheets
Below is one approach.  (However, I'm not digging the 2 parameters ... seems a little limited, but I'm sure you can expand as necessary)
Declare @Formula table (ID int,Title varchar(25),Formula varchar(max))
Insert Into @Formula values
 (1,'Sum'     ,'@a+@b')
,(2,'Multiply','@a*@b')

Declare @Parameter table (a varchar(50),b varchar(50))
Insert Into @Parameter values
(1,2),
(5,3)

Declare @SQL varchar(max)=''
;with cte as (
Select A.ID
      ,A.Title
      ,ParameterA = A
      ,ParameterB = B
      ,Expression = Replace(Replace(Formula,'@a',a),'@b',b)
 From  @Formula A
 Cross Join @Parameter B
)
Select  @SQL = @SQL+concat(',(',ID,',',ParameterA,',',ParameterB,',''',Title,''',(',Expression,'))') From cte
Select  @SQL = 'Select * From ('+Stuff(@SQL,1,1,'values')+') N(ID,ParameterA,ParameterB,Title,Value)'
Exec(@SQL)

-- Optional To Trap Results in a Table Variable
--Declare @Results table (ID int,ParameterA varchar(50),ParameterB varchar(50),Title varchar(50),Value float)
--Insert Into @Results Exec(@SQL)
--Select * from @Results

Returns
ID  ParameterA  ParameterB  Title      Value
1   1           2           Sum         3
2   1           2           Multiply    2
1   5           3           Sum         8
2   5           3           Multiply    15


Q: Formulário Ajax e PHP abrir lista dinâmica com consulta SQL Amigos, boa tarde!
Preciso editar um formulário que já estava pronto, incluindo algumas opções novas. Não conheço quase nada de PHP, e estou com muita dificuldade de fazer com que a combobox do formulário retorne uma consulta do SQL.
Esse formulário foi desenvolvido com PHP, AJAX e SQL.
Existem 3 arquivos para que os dados apareçam na página web.
-classificador_HelpCenter.php
-classificador_HelpCenter_ajax.php
-classificador_HelpCenter_sql.php
Esse formulário usa Bootstrap (O que também não entendo muito, infelizmente)
O formulário já tinha configurado, os campos (Usuário, Solicitante e Nome Solicitante), o campo que estou tentando incluir é "Atendimento".
Vou inserir o código dos arquivos AJAX e SQL, para que possam entender melhor e talvez consigam me ajudar.
-classificador_HelpCenter.php
<!DOCTYPE html>
<?PHP
    header('Content-Type: text/html; charset=ISO-8859-1');
    define( "RAIZ_augusta", "//57.228.131.75/" );
    require_once("//57.228.131.75/icc/funciones/funciones.php" );
    require_once("../../complemento/complemento.php");
    $ua = getBrowser();
    if (strpos($ua['name'],'Internet') === false){
        include_once("../../complemento/analyticstracking.php");
    }
    session_start();

    if(@array_key_exists("34", $_SESSION[ "modulos" ])){
?>

    <title>Augusta | Classificador Help Center</title>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=9; IE=8; IE=7; IE=EDGE'/>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>

        <link rel='stylesheet' href='<?php echo RAIZ ?>/css/bootstrap.css'>
        <link rel='stylesheet' href='<?php echo RAIZ ?>/css/font-awesome/css/font-awesome.min.css'>

    <?php imprimeMenuHeaderAugusta('faleAtendimento', 'Classif', @$_SESSION[ "bp" ]) ?>

<?php
    } else {
        echo "";
    }
?>

-classificador_HelpCenter_ajax.php
<?php
    header('Content-Type: text/html; charset=ISO-8859-1');
    include 'classificador_HelpCenter_sql.php';
    if(!isset($_SESSION)){session_start();}

    $seccion = $_POST["seccion"];
    @$Atendimento = $_POST['Atendimento'];
    @$Solicitante = $_POST['Solicitante'];
    @$subSolicitante = $_POST['subSolicitante'];

    if($seccion == "carregarForm"){ carregarForm();}
    if($seccion == "carregarSubSolicitante"){ carregarSubSolicitante($Solicitante);}
    if($seccion == "guardar"){ guardar($Atendimento, $Solicitante, $subSolicitante);}
    if($seccion == "carregarAtendimento"){ carregarAtendimento($Atendimento);}

function carregarForm(){

    $Solicitantes = obtiene_filtros('Solicitante', null);

    $out = '

                    <form class="form-horizontal">';
                        $out.='<fieldset>
                            <legend>Classificador Help Center</legend>';
                            if(true){ //NomeOperador
                                $out.='

                                    Usuário

                                        <input type="text" class="form-control" id="filtro_Nome" disabled value="'.$_SESSION['nomeGuerra'].'">

';
                            }
                            if(true){//Atendimento
                                $out.='

                                    Atendimento

                                        <select class="form-control" id="filtro_Atendimento" onchange="carregarAtendimento($Atendimento);"></select>

';
                            }
                            if(true){//Solicitante
                                $out.='

                                    Solicitante

                                        <select class="form-control" id="filtro_Solicitante" onchange="carregarSubSolicitante();">';
                                            foreach ($Solicitantes as $v){
                                                $out.='<option value="'.utf8_decode($v['valor']).'">'.utf8_decode($v['valor']).'</option>';
                                            }
                                        $out.='</select>

';
                            }
                            if(true){ //subSolicitante
                                $out.='

                                    Nome

                                        <select class="form-control" id="filtro_SubSolicitante"></select>

';
                            }
                            $out.='</fieldset>';
                        if(true){ //botões
                            $out.='<fieldset style="margin-top: 15px;" id="retorno">

 Cancelar

 Salvar

                            </fieldset>';
                        }
                    $out.='</form>

';

echo $out;
}
function carregarSubSolicitante($Solicitante){

    $filtro_duvida = obtiene_filtros('subSolicitante',utf8_decode($Solicitante));

    $out = 'Nome

        <select class="form-control" id="filtro_SubSolicitante">';
            foreach ($filtro_duvida as $v){
                $out .= "<option value='".utf8_decode($v['valor'])."'>".utf8_decode($v['valor'])."</option>";
            }
        $out.='</select>

';
echo $out;
}

function carregarAtendimento($Atendimento){

        $filtro = obtiene_Atendimento($Atendimento);

        $out = 'Atendimento

        <select class="form-control" id="filtro_Atendimento">';
            foreach ($filtro as $v){
                $out .= "<option value='".utf8_decode($v['valor'])."'>".utf8_decode($v['valor'])."</option>";
            }
        $out.='</select>

';
echo $out;
}
function guardar($Atendimento, $Solicitante, $subSolicitante){
        if(guardarResposta(utf8_decode($Atendimento),utf8_decode($Solicitante),utf8_decode($subSolicitante))){
            $out = '

                Dados salvos com sucesso.

                     Novo

';
        } else {
            $out = '

                Erro ao Salvar!
 Tente novamente em alguns segundos
 caso o erro persista informe seu lider

 Novo

 Salvar

            ';
        }

    echo $out;
}

?>

-classificador_HelpCenter_sql.php
<?php
    set_time_limit( 0 );
    date_default_timezone_set('America/Sao_Paulo');
    include '..\..\complemento\sql_login.php';
    if(!isset($_SESSION)){session_start();}

        function obtiene_Atendimento($Atendimento){
        $conexion = conexion();
        $link_augusta = sqlsrv_connect( $conexion[ "idt_augusta" ][ "server" ], $conexion[ "idt_augusta" ][ "info" ] );

        $sql= "SELECT T.Atendimento
            FROM classificadorHelpCenter_atendimento AS T";

        $resultado = sqlsrv_query( $link_augusta, $sql );
        while( $fila = sqlsrv_fetch_array( $resultado, SQLSRV_FETCH_ASSOC ) ) {
            $arreglo =  utf8_encode( $fila[ "Atendimento" ] );
        }

        sqlsrv_free_stmt( $resultado );
        sqlsrv_close( $link_augusta );
        return @$arreglo;

    }
    function obtiene_filtros ($filtro,$aux){
        $conexion = conexion();
        $link_augusta = sqlsrv_connect( $conexion[ "idt_augusta" ][ "server" ], $conexion[ "idt_augusta" ][ "info" ] );

        if($filtro=='Solicitante'){
            $sql = "SELECT A.SOLICITANTE AS valor
                FROM classificadorHelpCenter_solicitante AS A
                GROUP BY A.SOLICITANTE ORDER BY A.SOLICITANTE";
        }
        if($filtro=='subSolicitante'){
            $sql = "SELECT A.SUBSOLICITANTE AS valor
            FROM classificadorHelpCenter_solicitante AS A
            WHERE A.SOLICITANTE = '".$aux."'
            GROUP BY A.SUBSOLICITANTE
            ORDER BY A.SUBSOLICITANTE";
        }

        $resultado = sqlsrv_query( $link_augusta, $sql );
        while( $fila = sqlsrv_fetch_array( $resultado, SQLSRV_FETCH_ASSOC ) ) {
            $arreglo[] = array(
                "valor"     => utf8_encode( $fila[ "valor" ] ),
            );
        }

        sqlsrv_free_stmt( $resultado );
        sqlsrv_close( $link_augusta );
        return $arreglo;
    }
    function guardarResposta($Atendimento, $Solicitante, $SubSolicitante){
        $conexion = conexion();
        $link_augusta = sqlsrv_connect( $conexion[ "idt_augusta" ][ "server" ], $conexion[ "idt_augusta" ][ "info" ] );

        $sql="INSERT INTO fale_classificadorHelpCenter_registros (nome, bp, lider, Solicitante, Subsolicitante, data, Atendimento)
        VALUES( '".$_SESSION['nomeGuerra']."', '".$_SESSION['bp']."', '".$_SESSION['contrato_resumido']."', '".$Solicitante."', '".$SubSolicitante."', '".date('Y-m-d H:i:s')."' ,'".$Atendimento."')";

        $arreglo = sqlsrv_query( $link_augusta, $sql );
        sqlsrv_close( $link_augusta );
        return $arreglo;
    }

?>

Tudo que está relacionado a Atendimento, tentei usar a mesma configuração do campo Solicitante. O campo Atendimento aparece no formulário, porém quando clico, não trás o resultado da consulta sql que fiz.
Preciso fazer com que a lista seja exibida.
Desde já agradeço pela ajuda.

A: Olá, você deve observar o retorno da chamada a service classificador_HelpCenter_ajax
no console do navegador / abra a aba NetWork  procure em Name => classificador_HelpCenter_ajax  e clique nele do lado direito tem Preview e Response, você clicando neles vc deve ver o que está retornando para a página html no caso você tem que ver se está retornando Atendimento. Espero ter ajudado.


Q: How to split CSV rows then duplicate that row? I have a CSV file from which I need to generate a new file with new rows. I have some experience in Bash and Python.
Example:
Source

Country A,Place1;Place2;Place3,Other info
Country B,Place4;Place5;Place6,Other stuff
Country C,Place7;Place8;Place9,Other examples

Target

Place1,Country A,Other info
Place2,Country A,Other info
Place3,Country A,Other info
Place4,Country B,Other stuff
Place5,Country B,Other stuff
Place6,Country B,Other stuff

So I need to split the 2nd column by the ; delimiter and create a new line based on the rest of the information in the row.

A: Assuming its always the second column.
Change the columnNumber if its a different column (I'm counting this from 1 and not 0 for ease of use).
import csv
newData = []
columnNumber = 2
with open('data.csv') as csvfile:
    line = csv.reader(csvfile, delimiter = ',')
    for row in line:
        cStr = row[columnNumber-1].split(';')
        for i in range(0,len(cStr)):
            temp = []
            for j in range(0, len(row)):
                if(j==columnNumber-1):
                    temp.append(cStr[i])
                else:
                    temp.append(row[j])
            newData.append(temp)
with open('output.csv', 'w', newline="") as outFile:
    writer = csv.writer(outFile)
    writer.writerows(newData)

A: Here's a Python 3 solution.  Note use of newline='' per csv read/writer documentation:
import csv

with open('source.csv',newline='') as fin:
    with open('target.csv','w',newline='') as fout:
        r = csv.reader(fin)
        w = csv.writer(fout)

        # Read original three columns
        for country,places,other in r:

            # Write a row for each place
            for place in places.split(';'):
                w.writerow([place,country,other])

If still using Python 2, use the following open syntax instead:
with open('source.csv','rb') as fin:
    with open('target.csv','wb') as fout:

A: If you have a csv file then the simplest way is to open Excel, then navigate to File>Open and select "All Files" and navigate to the csv file you want to modify.  When you open this file, it should give you the option to state what character you want to use as the delimiter, and you can enter ";".
There should be a few more options that you just agree to, and then you will have an xls file with the fields split by the ";".
In order to get from this to the table you want, I would suggest creating a pivot table.  My answer is based on this being a one-off, whereas if you will have to repeat this function it would be better to write something in Excel VBA or Python.  Happy to advise further if you get stuck.

A: Using Miller (https://github.com/johnkerl/miller) is very simple. Using this command
mlr --nidx --fs "," nest --explode --values --across-records -f 2 then reorder -f 2 input.csv

you have
Place1,Country A,Other info
Place2,Country A,Other info
Place3,Country A,Other info
Place4,Country B,Other stuff
Place5,Country B,Other stuff
Place6,Country B,Other stuff
Place7,Country C,Other examples
Place8,Country C,Other examples
Place9,Country C,Other examples


Q: what is the best way to check session in codiginator everytime make a new request i know how to use session in codiginator but i am facing the problem with session management and little bit confuse ie how can i check every time a valid session in controller.
i do this by using
<?php

defined('BASEPATH') OR exit('No direct script access allowed');
class Dashboard extends MY_Controller {

function __construct() {
                        parent::__construct();
                        $this->load->helper('url');
                        $this->load->helper(array('form', 'url'));
                        $this->load->library('form_validation');
                        $this->load->library('session');
                        $this->load->model('User');
                        $this->load->model('Enquiry_model');
        }
    public function index()
            {
                    //$data['status']=$this->Blog_model->status();
                    $data['main_product']=$this->Enquiry_model->getMainProduct();
                    $session_data = $this->session->userdata('logged_in');
                    if(!$session_data)
                    {
                            $this->welcome();
                    }
                    else
                    {
                        $data['user_data'] = $session_data;
                        $this->load->view('admin1/index1',$data);
                    }

            }

}
?>

but facing the problem when i have two website and i use same table to check the user but the different database for both. the problem i am facing when i logedin to first website i automatically logged in to other one. how can i remove or solve this problem.


Q: Keystone scopes behavior is inconsistent between nova and cinder I've been trying to update our OpenStack installation to use new options enforce_new_defaults and enforce_scope since in Wallaby for nova old policies will be deprecated. Those option seem to be present in many components (nova, cinder, keystone, glance, …) so I thought it is good idea to enable them everywhere. I've started with nova and cinder and hit interesting problem.
I've created user test without default project and assigned it admin permissions in system scope and in one project. Both options mentioned before are set to true in nova and cinder. Policy files are absent (because I want to test defaults).
Doing basic test (https://docs.openstack.org/keystone/latest//admin/tokens-overview.html#authorization-scopes):

*

*openstack token issue gives me unscoped token

*openstack --os-system-scope=all token issue gives me system-scoped token

*openstack --project-name=NAX.Prod token issue gives me project-scoped token

So far so good. Now fun starts:

*

*openstack volume service list - FAIL: The service catalog is empty.

*openstack --os-system-scope=all volume service list - FAIL: public endpoint for volumev3 service not found

*openstack --os-project-name=NAX.Prod volume service list - OK

System-scoped request does not pass, because volumev3 service uses /v3/%(project_id)s in the endpoint URL (double checked docs) so it seems without authenticating to some project it won't work.
Looking in the generated policy, it seems to not support scopes for this request:
# List all services.
# GET  /os-services
#"volume_extension:services:index": "rule:admin_api"

Fine, now the nova:

*

*openstack compute service list - FAIL: The service catalog is empty.

*openstack --os-system-scope=all compute service list - OK

*openstack --os-project-name=NAX.Prod compute service list - FAIL: Policy doesn't allow os_compute_api:os-services:list to be performed.
The relevant policy:
# List all running Compute services in a region.
# GET  /os-services
# Intended scope(s): system
#"os_compute_api:os-services:list": "rule:system_reader_api"

So it does seem to work as expected.

That said, if you want to manage OpenStack to perform same operation for different components (list services) you have to use different scopes (different OS_CLOUD or CLI arguments, depending how you have set it up). Is this really expected? Do I miss anything?
Relevant versions:

*

*Keystone: 18.0.0

*Nova: 22.0.1

*Cinder: 17.0.0

*OpenStack Client: 5.4.0

*OpenStack SDK: 0.50.0


Q: Convert spaces to newlines in text file using Python I have a text file which looks like this:
15.9 17.2 18.6 10.5

I want to edit this file in Python so that it looks like this:
15.9
17.2
18.6
10.5

This means that I need to replace the space strings by newline strings and save the text.
I tried this but it doesn't work:
f = open("testfile.txt", "w")

for line in f:
    if ' ' in line:
        line2 = line.replace(' ' , '\n')
    print(line2)
for i in line2:
    f.write(line2(i))
f.close

The print for line2 is already working, but I don't get a new text file with  spaces replaced by newlines.
How can I fix the problem and produce the desired output?

A: with open("testfile.txt", "r") as r:
    with open("testfile_new.txt", "w") as w:
        w.write(r.read(.replace(' ' , '\n'))

A: Example:
with open("file1.txt", "r") as read_file:
    with open("file2.txt", "w") as write_file:
        write_file.write(read_file.read().replace(" ", '\n'))

Content of file1.txt:
15.9 17.2 18.6 10.5

Content of file2.txt:
15.9
17.2
18.6
10.5

NOTE:
Or you can use the split and join method instead of replace.
write_file.write("\n".join(read_file.read().split()))

A: try like this instead
f = open("testfile.txt", "r")
text=f.read()
f.close()
f=open("testfile.txt", "w+")
text2=''
if ' ' in text:
    text2 = text.replace(' ' , '\n')
    print(text2)
    f.write(text2)
f.close()

A: You can try using string replace:
string = string.replace('\n', '').replace('\r', '')

Firstly: f.close() is not there.
Secondly: try above code. It will replace spaces to new lines.

A: Use str.split with str.join
Ex:
with open("testfile.txt", "r") as infile:
    data = infile.read()

with open("testfile.txt", "w") as outfile:
    outfile.write("\n".join(data.split()))


Q: Return Link Addresses of Titles on Google SERP I'm trying to get all link addresses that are hyperlinked on titles for a Google Search results page. Also trying to append it to a CSV file which I think I've got pretty straight as of now.
from bs4 import BeautifulSoup
from urllib.request import Request, urlopen
import requests
import re
import csv

#f = open("web_search_terms.txt", "r")

terms = ["thanks","for","the help"]

terms = []
for line in f:
  stripped_line = line.strip()
  terms.append(stripped_line)

with open("web_urls.csv", "w") as f_out:
    writer = csv.writer(f_out)
    writer.writerow(["Search Term", "URL"])
    for t in terms:
        url = f"https://google.com/search?q={t}"
        print(f"Getting {url}")
        html_page = requests.get(url)
        soup = BeautifulSoup(html_page.content, "html")
        divs = soup.findAll("div", attrs={"class": "yuRUbf"})
        for item in divs:
            writer.writerow([t, item.get_text(strip=True)])

I'm not able to append the links to the "divs" list though, not sure how to get the hrefs within the class labelled "yuRUbf"
Any help would be super appreciated!
Thanks so much!

A: To get correct response from the Google server, set User-Agent HTTP header. For example:
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
}

url = "https://google.com/search"
terms = ["thanks", "for", "the help"]

for t in terms:
    params = {"q": t, "hl": "en"}
    print(f"Getting {t}")
    soup = BeautifulSoup(
        requests.get(url, params=params, headers=headers).content, "html.parser"
    )
    divs = soup.findAll("div", attrs={"class": "yuRUbf"})
    for div in divs:
        print(div.a["href"], div.a.text)

    print()

Prints:
Getting thanks
https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks Preklad slova „ thanks ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad
https://slovnik.aktuality.sk/preklad/anglicko-slovensky/?q=thanks%21 Preklad slova „ thanks! ” z angličtiny do slovenčiny - Slovnik.skhttps://slovnik.aktuality.sk › preklad
https://www.merriam-webster.com/dictionary/thanks Thanks | Definition of Thanks by Merriam-Websterhttps://www.merriam-webster.com › dictionary › thanks
https://dictionary.cambridge.org/dictionary/english/thanks THANKS | meaning in the Cambridge English Dictionaryhttps://dictionary.cambridge.org › dictionary › thanks
https://www.thanks.com/ Thanks: Thank Homehttps://www.thanks.com
https://www.dictionary.com/browse/thanks Thanks Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › thanks
https://www.collinsdictionary.com/dictionary/english/thank Thank definition and meaning | Collins English Dictionaryhttps://www.collinsdictionary.com › dictionary › thank
https://www.youtube.com/watch?v=FnpZQoAOUFw THANK YOU and THANKS - How to thank someone in Englishhttps://www.youtube.com › watch

Getting for
https://www.merriam-webster.com/dictionary/for For | Definition of For by Merriam-Websterhttps://www.merriam-webster.com › dictionary › for
https://www.dictionary.com/browse/for For Definition & Meaning | Dictionary.comhttps://www.dictionary.com › browse › for
https://dictionary.cambridge.org/dictionary/english/for Meaning of for in English - Cambridge Dictionaryhttps://dictionary.cambridge.org › dictionary › for
https://www.macmillandictionary.com/dictionary/british/for FOR (preposition, conjunction) definition and synonymshttps://www.macmillandictionary.com › british › for
https://www.collinsdictionary.com/dictionary/english/for For definition and meaning - English - Collins Dictionaryhttps://www.collinsdictionary.com › dictionary › for
https://www.thefreedictionary.com/for For - definition of for by The Free Dictionaryhttps://www.thefreedictionary.com › for
https://www.learnersdictionary.com/definition/for 1 for - Merriam-Webster's Learner's Dictionaryhttps://www.learnersdictionary.com › definition › for

Getting the help
https://www.imdb.com/title/tt1454029/ The Help (2011) - IMDbhttps://www.imdb.com › title
https://en.wikipedia.org/wiki/The_Help_(film) The Help (film) - Wikipediahttps://en.wikipedia.org › wiki › The_Help_(film)
https://www.vanityfair.com/hollywood/2018/09/viola-davis-the-help-regret Viola Davis Regrets Making The Help: “It Wasn't the Voiceshttps://www.vanityfair.com › Hollywood › viola davis
https://www.csfd.cz/film/277770-cernobily-svet/prehled/ Černobílý svět (2011) | ČSFD.czhttps://www.csfd.cz › film › prehled
https://www.rottentomatoes.com/m/the_help The Help - Rotten Tomatoeshttps://www.rottentomatoes.com › the_help
https://www.usatoday.com/story/entertainment/movies/2020/06/08/the-help-isnt-helpful-resource-racism-heres-why/5322569002/ 'The Help' isn't a helpful resource on racism. Here's why - USA ...https://www.usatoday.com › story › movies › 2020/06/08
https://www.amazon.com/Help-Emma-Stone/dp/B004A8ZWVK The Help : Emma Stone, Octavia Spencer, Jessica - Amazon ...https://www.amazon.com › Help-Emma-Stone
https://www.amazon.com/Help-Kathryn-Stockett/dp/0399155341 The Help: Stockett, Kathryn: 9780399155345 - Amazon.comhttps://www.amazon.com › Help-Kathryn-Stockett
https://www.martinus.sk/?uItem=258803 Kniha: The Help (Kathryn Stockett) - Anglický jazyk - Martinushttps://www.martinus.sk › ...


Q: Recommended Deadwind Cavern Legendary Deathclaw Level? What level is it advised for your character to be before entering Deadwind Cavern and fighting the Legendary Deathclaw?
I am level 24, my companion is Boone and I still get my butt kicked.

A: The trick with deathclaws is to have a lot of ammo and seek higher ground. For some reason they don't seem to be able to get to you if you are perched on top of rocks.
So my strategy was to load up on explosives, go trigger the deathclaws to chase me, when they scuffled with my companions I scurried up onto a rock and then rained down bombs on them until they died. You may have to repeat triggering them a few times to get them all as they sometimes forget about you and go back into their hidey hole. Be sure to save every time you kill a few of them and get back to your safe perch so you don't have to start over if they catch you before you get to safety.
Also, beware. There is a nasty surprise outside the cave (a bunch more deathclaws) and no convenient rock to jump up on. I just ran like hell for the nearby shack. They followed me in and killed me, but when it re-spawned me inside the cabin they were back outside and oblivious to my presence.

A: It's not only about your level, but also about the weapon/perks you are using. With the perks Better Criticals and Sniper using an Anti-Materiel Rifle with armor piercing ammo, you should have an easier time fighting this beast.
Consider also using chems and magazines to boost your stats, like Psycho to inflict more damage and/or Buffout to take a few more hits before dying.
Mines on the Legendary Deathclaw path are efficient to cripple its legs and delay its advance towards you. It will also lose its "pounce" attack, that deals more damage.
Good luck!

A: Stealth Boy and lots of C-4. There's a reason it's the most expensive explosive in the game by far... Also, you may want to leave your companions outside for this one. They tend to get trigger-happy and ruin a good ambush.

A: I killed the beast at level 9. I stumbled into the cave on my way to Novac for the first time and promptly ran. They followed but to the right of the exit upon leaving is a ledge you can climb onto where they cannot reach you. I just kept sniping it with the Cowboy Repeater until it fell.

A: I did at Level 22, and my perks were Centre of Mass, Maths Wrath, Grim Reaper Sprint and Action Girl.  I used an Anti-Materiel Rifle with Incendiary Rounds.  The Explosives are no good in the cavern because up close you damage yourself.

A: If your gun level is high you can use an assault carbine and kill the Legendary Deathclaw. Keep in mind that you need to have Ed-E upgraded and Boone as well.


Q: Programming Google CardDAV in Python I want to obtain my Google contacts through the CardDAV protocol using preferably Python (open to other languages).
I've come across the pycarddav library, but it only works with SabreDAV/DAVical servers, not Google for example.
How one would go about programming an interface to the Google contacts CardDAV using Python (or other language)?

A: Google has just today announced to make CalDAV and CardDAV available for everyone. Google's CardDAV Documentation (also just released today) is probably a good place to start.


Q: CMake: Replace a literal citation mark with an escaped one I have a string containing something like this:
Hello "there" happy face!

and I want to do a string(REPLACE ...) in CMake so that it becomes:
Hello \"there\" happy face!

How do I do this?
string(REPLACE "\"" "\\"" TARGET "${SOURCE}") does not work

A: I came up with the answer to this question while writing it...
To get a literal \ in the replace target we need to escape it not just once but twice: \\\\
Then to get a literal " we need to escape that as well \".
So to replace a literal \" with an escaped one, we need: \\\\\".
That is: string(REPLACE "\"" "\\\\\"" TARGET "${SOURCE}")


Q: Visualforce page cannot be accessed from guest user? I am trying to access a Visualforce page in a community from a guest user, and I cannot see it. I am trying just with a simple hello world page, to remove the ipothesis of object-related issues.
I assigned the visualforce page to the profile but still, it won't load at all, just a blank page. Any idea?
When i open the console i see only these 2 errors :
DevTools failed to load source map: Could not load content for preview.salesforce-communities.com/auraFW/javascript/1643424164816/aura_prod.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

DevTools failed to load source map: Could not load content for /ui-sfdc-javascript-impl/source/RecordGVP.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

This is what they should see :
This is what they see :
I added the visualfoce page in the profile that is listed here "test3 profile":

A: I was finally able to fix this issue. If you are using some custom object, giving read permission to it and the fields was not enough for me because the object had private sharing model.
I had to create a sharing rule for this object and the guest user profile.
Then to be able to access the visualforce page, i just had to do the same things but in production. Somehow the sandbox didn't let me access the visualforce page as guest.
This finally solved the issue.