text:
Q: Azure- static repository needs reloading I have a static repository with stores a large XML file structure in memory and is loaded only once in the MVC application. The application is hosted on Azure (Paas) with 2 instances.
We have a design tool which is used to add more stuff or remove stuff from this repository. The challenge we find is that once stuff gets added we need to reload the repository by tearing down the repository and re-creating it. This works but leaves a problem that the static repository has been refreshed only on server A and not on server B.
If a request goes to server B, the user doesnt see that change as it has not been updated.
On;y an IIS reset on both instances fixes the problem. I have tried using Session state to store the repository but as we use as custom Session provider which stores the values in a  database table the session_start event is called on every page request causing performance problems.
Does anyone out there have a more elegant solution to updating the repository on both servers and using any modern techniques.

A: Have you considered using an in-role cache to store the repository (of course, persist it as well as you are doing already)?
You can either use memory from your existing web role, or create a dedicated cache role. The cache will span all of your instances, so you'd be accessing the same data from each instance.
Taking it one step further: If you're concerned about data loss during a role instance reboot (which would mean some of your data would no longer be in the cache when the instance goes down), you can enable High Availability on the cache namespace. At this point, data is replicated between instances, which lets you survive an instance restart.
You'll find the co-located (or dedicated) cache setting in the role properties:


text:
Q: intuition about cubic splines vs quadratic splines (degree 3 vs degree 2). my intuition about quadratic(degree 2) splines is that by the help of its three variables (in each sub-interval) you can make a piecewise differentiable function on the whole interval.
in the process of finding a degree 2 spline generally we need to exactly specify the derivative of ONE point and then we find a unique spline .
But since we usually need to specify the derivative of both end points then generally we cannot do this with a degree 2 spline.
so we raise the spline power to 3 . now we have 4 variables for each sub-interval .
now my intuition suggests that with this new variable we simply plug in both end point derivative conditions and we get a unique answer .
BUT instead, by adding the new variable we are ALSO able to make the second derivative continuous .
Question is
how adding one variable can handle both the endpoints derivative condition and  the second derivative continuity condition ?

A: Let's count the conditions: $N+1$ points for $N$ intervals. Resulting in $4N$ coefficients of $N$ cubic polynomials. On the side of the equations we get

*

*$2N$ prescribed function values

*$N-1$ continuity conditions for the first derivative

*$N-1$ continuity conditions for the second derivative

*the third derivative is piecewise constant, so there must be jumps, no equations.

Which still leaves us with a difference of $2$ degrees of freedom. One usually imposes conditions on the first and last point, for instance a zero second derivative

redpajama_set_name: RedPajamaStackExchange


text:
Q: Syncing radiobuttons/checkboxes I have simple radio buttons. One section has parent level items and the other child items. If the user selects the parent item and if the parent has only one child item then the child item should automatically be selected.
This sounds simple but I don't think I'm thinking this right.
Right now I have hard-coded my function to work on the first parent item like so:-
test1 : ko.observable(),
test2 : ko.observable(),
syncSelections: function(){
    this.test2("banana");
}

where "banana" is the value of the child item. My hard-coded fiddle.


text:
Q: How to prevent a trigger to be triggered by another trigger? I have two tiggers on table1:

*

*trigger #1 after update it updates the last modified date column in table1

*trigger #2 after update if col1 is 0 it creates a log record in table2
So the problem is that when I set col1 to 0 trigger #2 creates the record properly in table2, but as trigger #1 modifies the record again, trigger #2 creates another log record in table2.
What I want is to prevent trigger #2 to be triggered when trigger #1 modifies any record.

A: You may in the first trigger issue a disable trigger before the update (under certain circumstances, update the value, then renable the trigger.
In the first trigger:
 if (cond1)
           disable trigger starttrigger2 on table1

    update table1

    enable trigger starttrigger2 on table1


text:
Q: In SVG how do I reuse text elements positioned in a group like shapes in defs? I am trying to accomplish a precise layered effect for text in SVG. My current solution below just copies and pastes the group element with the text elements inside correcting the x and y coordinates for each. I saw from another solution def and reuse and transform for shapes.
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" preserveAspectRatio="xMinYMin meet"  width="100%" height="100%" viewBox="0 0 960 640" style="background-color:#def">
<g style="font-family: Arial Black; font-weight: bold;" fill="rgba(244, 164, 96, 0.45)">
    <text text-anchor="middle" x="480" y="610" font-size="160px">♥</text>
    <text x="95" y="265" font-size="160px">PASSION</text>
    <text x="395" y="345" font-size="80px">FOR</text>
    <text x="135" y="485" font-size="160px">PEOPLE</text>
</g>
<g style="font-family: Arial Black; font-weight: bold;" fill="#def">
    <text x="439" y="601" font-size="160px">♥</text>
    <text x="99" y="261" font-size="160px">PASSION</text>
    <text x="399" y="341" font-size="80px">FOR</text>
    <text x="139" y="481" font-size="160px">PEOPLE</text>
</g>
<g style="font-family: Arial Black; font-weight: bold;" fill="orange">
    <text x="440" y="600" font-size="160px">♥</text>
    <text x="100" y="260" font-size="160px">PASSION</text>
    <text x="400" y="340" font-size="80px">FOR</text>
    <text x="140" y="480" font-size="160px">PEOPLE</text>
</g>

A: To achieve the effect you want, define the shape within a defs section and then refer to it from a use element.
So the equivalent of your sample document is:
<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     version="1.1"
     preserveAspectRatio="xMinYMin meet"
     width="100%" height="100%"
     viewBox="0 0 960 640"
     style="background-color:#def">
<defs>
  <g id="passion" style="font-family: Arial Black; font-weight: bold;">
    <text x="440" y="600" font-size="160px">♥</text>
    <text x="100" y="260" font-size="160px">PASSION</text>
    <text x="400" y="340" font-size="80px">FOR</text>
    <text x="140" y="480" font-size="160px">PEOPLE</text>
  </g>
</defs>

<use xlink:href="#passion" transform="translate(-5,5)" fill="rgba(244, 164, 96, 0.45)" />
<use xlink:href="#passion" transform="translate(-1,1)" fill="#def" />
<use xlink:href="#passion" fill="orange" />
</svg>

Don't forget to define the xlink namespace in your root svg element. Otherwise you'll get an error.


text:
Q: Switching circuit I am making a switching circuit with two input sources A and B of 5 volts each and one or more outputs C1, C2, C3 etc.
Source A is constant and source B is variable, has two states on and of.
Source B must change the state of output C1, if source B is on output C1 is off, if source B in off, output C1 is on.
Outputs C2, C3 etc. are used as grounding if necessary.
The circuit must not contain transistors, diodes, relays or vacuum tubes.
Edit:
I used this circuit simulator ( https://www.falstad.com/circuit/  ) to simulate my circuit:
$ 1 0.000005 10.20027730826997 50 5 50
r 192 192 288 192 0 50
w 288 192 288 272 0
s 288 272 288 352 0 1 false
R 288 352 288 416 0 0 40 6 0 0 0.5
w 192 192 192 256 0
g 96 256 32 256 0
R 64 192 -16 192 0 0 40 5 0 0 0.5
w 192 192 192 96 0
r 192 96 192 32 0 200
r 96 256 192 256 0 200
g 192 32 192 -16 0
w 64 192 192 192 0
o 11 64 0 4099 5 0.1 0 2 11 3

( Import the code above to see the circuit )

What I did so far, the top grounding is output C1, the left input source is A, the bottom input is B, and the second grounding is C2.
If you look at the scope linked to the wire next to source A, the effect is achieved but I need that to work in output C1 ( top grounding )

A: If your constraints are

The circuit must not contain transistors, diodes, relays or vacuum tubes.

And that the voltage levels for "off" and "on" are equal for the two outputs C1  Then what you try to achieve is not possible.
I have assumed that no transistors are allowed even in other configurations such as flip-flops, logic gates, opAmps. And that the switch is a signal not originating from a physical switch(in that case get a DPDT switch and you should be good).
If logic gates are allowed, try playing around with them and I think you will figure it out quite quickly ;)
PS the only thing you need as an input is input B since the input of A is constant.


text:
Q: Allegro 5 game: How do I set a resolution that is appropriate for the aspect ratio of the screen? Using Allegro 5, how do initialize a game in fullscreen mode so that it respects the format of the screen (widescreen 16:9 vs normal 3:4)
al_create_display (w, h)

Let's you select any ratio you want. For example you can set 640x480, regardless of the screen size. But it will look weird on a widescreen monitor.
How do you know which ratio to use?

A: Hm, I can answer this as well - use al_get_monitor_info().
al_get_monitor_info(0, &info);
w = info.x2 - info.x1; /* Assume this is 1366 */
h = info.y2 - info.y1; /* Assume this is 768 */
al_create_display(w, h);

Now you can either render everything in a 640x480 rectangle centered within 1366x768 to make it appear pixel-perfect, or alternatively scale your graphics up by 768/480 and keep two black bars to the left and right. If you use OpenGL for rendering, both are very easy to do by simply altering the projection matrix.


text:
Q: SASS how to round floating point result of division 1/3 to 33.33334? In SASS by dividing 1/3 result is 33.33333, and browser sum-up three elements of this size to 99.984. What i need is exactly number 100, and this can be achieved by stacking three elements of size 33.33334. How can I force SASS to to round up the last number of division?
demo: http://sassmeister.com/gist/577dec6f9b85b70c3621

A: Ok, solution was to use external function written by Terkel.
His decimal-rounding functions: https://gist.github.com/terkel/4373420
Usage
.tile {
  &-1-3 {
    width: decimal-ceil(100/3, 5);
    // this should result as 33.33334%;
  }
  &-2-3 {
    width: 2/3 * 100%;
  }
  &-1-1 {
    width: 3/3 * 100%;
  }
}

A: You have to roll your own rounding method using multiplication, division, and ceil().
.tile {
  &-1-3 {
    $num: 1 / 3; // 0.33333
    // the number we multiply by should have the same number of
    // zeros as there are decimal places you want to keep + the
    // number of digits there will be on the left side of the decimal
    $num: $num * 10000000; // 3333333.33333
    // ceil to round up
    $num: ceil($num); // 3333334
    // divide by that amount again
    $num: $num / 10000000; // 33.33334
    width: $num * 100%; // 33333.34%
  }
}


text:
Q: Which is the best way to fetch real time data based on logged in user? My project is built in .net MVC with MS SQL Server. I am fetching live rates in my project, these rates are updated every milliseconds,. My problem is that I need to show all these rates on browser to logged in users depending on their settings.
Any help would be appreciated.


text:
Q: scaling and encoding with same technique at prediction i used robustscaling and labelencoding for numerical and categorical column respectively at the time of training.
num_features = x_df[numeric_type]
scaler = RobustScaler()
x_df[numeric_type] = scaler.fit_transform(num_features.values)

label_encoder = LabelEncoder()
x_df[categorical_type[i]] = label_encoder.fit_transform(x_df[categorical_type[i]])

and it works very fine.
and i trained my model also but when i try to give new values for prediction so i have to give value in the encoded aur scaled form
eg:
at training :
apple -> 1
at prediction: if i want to insert apple as a value so i want to type apple but this says you have to give 1
so any solution to encode with same technique as used in training with the sequence of variable also. means variable will user defined so i dont have idea of sequence of variable what user decided for training and prediction.
thanks in advance


text:
Q: Is there any built in function to get the list of nodes (point node) within a certain diameter range in anylogic? When a person agent is absorbing one node, I am trying to find the list/array of other nodes (point node) around him within a certain diameter range (let's say 10feet). Is there any built-in function to sort those nodes around the agent? I was trying "agentInRange", "getNearestAgent" but those aren't actually the right ones for my need as these functions return a list of person agent within the range not the list of nodes around him. How I can get the list of nodes (point node) around an agent? Thanks.

A: Not that I know of.
But you can easily put all nodes in your model into a collection, then let your agents loop across that collection to check. Something like this, will need to be adjusted to your needs and conditions
for (PointNode currentNode : col_AllNodes) {
    if (currentNode.getX() ...) { // check your condition
        return true;
    }
}

You can easily put all nodes into a collection by selecting them all, right-click and then  selected "create collection" as below:


text:
Q: ImageMagick for Windows, how to remove noise and horizontal and vertical lines I have the following scanned image(this is a part of the image):

In order to improve the OCR process, I'd like to remove horizontal and vertical lines from the image and also the background noise.
How to do this with ImageMagick for Windows ?


text:
Q: Python writing to file per character instead of per string Suppose I have K and V. K contains a tuple
('String1', 'String2')

while V is a floating-point number
0.00324

What I'm trying to do is to write both into a text file like this:
('String1', 'String2') 0.00324

or
String1 String2 0.00324

My code is this:
for k,v in bigrams_frequency.items():
    number_unigrams = vocabulary.count(k[0])
    if number_unigrams == 0:
        continue;
    v = v / number_unigrams
    print(k,v)
    f2.write('\n'.join('%s %s' % (k,v)))

However, when I open the text file, the output looks like this:
(
'
S
t
r
i
n
g
1
.
.
.

What could be causing Python to print like this? How do I fix this?

A: As discussed in the comments here is the code;
K=("string1","string2")
V=0.00324
file = open("test.txt","a")
file.write("{} {}".format(K,V))
file.close()

and it produces this output the file which you specified as a desired output in your question;
('string1', 'string2') 0.00324

you can also use a with statement when writing to files because a with statement automatically closes the file so you dont need to explicitly close it so for your example it will be;
with open("test","a") as file:
    file.write("{} {}".format(K,V))

just dont forget to indent where you need the file because as soon as it isnt indented anymore the file will close

A: you have a wrong understanding of str.join(xx) function. This function "return a string which is concatenation of the string in the iterable xx". You can use str.format() instead.

A: The problem lies here - f2.write('\n'.join('%s %s' % (k,v))).
The join method expects an iterable (like a list) in the parameters. When you give it the string 'String1 String2 Float', it 'joins' every two letters with a new line.
It seems all that you want to do is write every entry in a new line (not every letter!), so replace the line with something like f2.write('{} {}\n'.format(k, v))
If you haven't come across format yet, read up about it here.

A: You can do:
for k,v in bigrams_frequency.items():
    # Other code
    f2.write('{}{}\n'.format(join(k),v) )

And, it will be just fine.


text:
Q: App Engine "Free Trial" vs "Free Quota" I am confused...  Probably because I am not very smart.
As I understand it:
1. Free Trial gives certain allowance(300 USD) to be used up in 60 days.
2. Free Quota gives daily allowance of free usage to (all?) app engine resources.
Did I understand these two things correctly?  What is the relationship between these?  Is free quota still being offered?  Are there dependencies between these two(if I sign up for free trial, would I lose free quota after the trial ends in 60 days)?

A: Yes, you got them right. They aren't really related.
The free quotas are still offered. They don't expire and they apply regardless if the app is in the free trial or not. They may get revised now and then, though. From Billable limits and safety limits:

*

*Free quotas: Every application gets an amount of each resource for free. Free quotas can only be exceeded by paid applications, up to the
  application's spending limit or the safety limit, whichever applies
  first.

The free trial has a limited lifespan and simply covers the billed costs of the paid apps (during that limited lifetime) up to that 300 USD amount.


text:
Q: Show current Date into datepicker I have a datepicker which I want to show the current date whenever the page loads.
How can i modify the below code:
<div<?php echo CRBSHelper::createCSSClassAttribute($class); ?>>
<label class="crbs-form-field-label"><?php esc_html_e('Pickup date','car-rental-booking-system'); ?></label>
<input type="text" name="<?php CRBSHelper::getFormName('pickup_date'); ?>" class="crbs-datepicker" value="<?php echo CRBSRequest::get('pickup_date'); ?>"/>
</div>


text:
Q: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away Server details:
RAM: 16GB
HDD: 1000GB
OS: Linux 2.6.32-220.7.1.el6.x86_64
Processor: 6 Core

Please see the link below for my # top preview:

I can often see the error mentioned in title in my plesk panel and my /etc/my.cnf configuration are as below:
bind-address=127.0.0.1
local-infile=0
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql

max_connections=20000
max_user_connections=20000
key_buffer_size=512M
join_buffer_size=4M
read_buffer_size=4M
read_rnd_buffer_size=512M
sort_buffer_size=8M
wait_timeout=300
interactive_timeout=300
connect_timeout=300
tmp_table_size=8M
thread_concurrency=12
concurrent_insert=2
query_cache_limit=64M
query_cache_size=128M
query_cache_type=2
transaction_alloc_block_size=8192
max_allowed_packet=512M

[mysqldump]
quick
max_allowed_packet=512M

[myisamchk]
key_buffer_size=128M
sort_buffer_size=128M
read_buffer_size=32M
write_buffer_size=32M

[mysqlhotcopy]
interactive-timeout

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
open_files_limit=8192

As my server httpd conf is set to /etc/httpd/conf.d/swtune.conf and the configuration is as below: at prefork.c:
<IfModule prefork.c>
StartServers       8
MinSpareServers   10
MaxSpareServers   20
ServerLimit     1536
MaxClients      1536
MaxRequestsPerChild  4000
</IfModule>

If I run grep -i maxclient /var/log/httpd/error_log then I can see everyday this error:
[root@u16170254 ~]# grep -i maxclient /var/log/httpd/error_log
[Sun Apr 15 07:26:03 2012] [error] server reached MaxClients setting, consider raising the MaxClients setting
[Mon Apr 16 06:09:22 2012] [error] server reached MaxClients setting, consider raising the MaxClients setting

I tried to explain everything that I changed to keep my server okay, but maximum time my server is down. Please help me which parameter can I change to keep my server okay and my sites can load fast. It is taking too much time to load my sites.

A: Wow.
With a MaxClients setting of 1536 and each Apache child using around 69MB of RAM, you need just over 100GB of RAM to avoid swapping out "hot" parts of Apache's memory.  May I suggest you lower that value until it fits inside your available RAM?  Swapping like that will make your server horrendously slow.
Since you are running MySQL on the same server, I would go for about half of your available RAM for each service, so MaxClients 115 would be appropriate for you.  Maybe a little lower if you want to leave a little breathing room around MySQL.
Now, on to MySQL, which is likely the actual cause of your server going slow.  MySQL is using a lot of CPU and very little RAM.  Three things to do:

*

*Turn on the mysql slow query log and set the long_query_time to something high like 10 or 20 seconds.  Slowly lower that setting until you start catching slow queries.  Once you know which queries are causing the problem, tune them by adding appropriate indexes or modifying the query.  Tuning queries is a major topic and there are several good books on it.

*Run mysqltuner.pl and follow its recommendations. ( wget mysqltuner.pl )

*Install a server performance monitoring tool such as Cacti, Munin or Zabbix (there are other options) and add the "Better Cacti Templates" or "Appaloosa Templates".

Going with the "half for each service" idea above, mysqltuner.pl will tell you the maximum amount of RAM that MySQL can use but you are unlikely to ever see this as it relies on per-connection RAM allocation and you will never see all 20,000 connections you allow.  Instead, watching what MySQL actually uses and making it use about 2/3rds - 3/4ths of the remaining RAM is a sensible value.
You should probably lower your query_cache and query_cache_limit and raise either key_buffer_size or innodb_buffer_pool depending on which engine you use.  mysqltuner.pl will have better recommendations than I do.

The error message you used as the title for this question is related to the wait_timeout setting of MySQL.  Some process has opened a connection to MySQL and then waited at least 300 seconds between commands.  If this was a web request, raising this value is not the right solution.  300 seconds is far longer than people will wait around for a web request to complete.  Fix whatever is causing the load average to be so high (probably the other slow queries and the swapping) and the requests will be faster.


text:
Q: Sort a dictionary key without in built functions I'm trying to sort the given sentence according to length  in a sentence and store the length as key and the word as value. I want to sort this dictionary in a increasing order without using in-built functions.
The code I've tried:
    def string_leng(user_string):
    leng_dict = {}
    user_string = user_string.split(" ")
    for word in user_string:
        if len(word) in leng_dict:
            leng_dict[len(word)].append(word)
        else:
            leng_dict[len(word)] = [word]
    print(leng_dict)
    return leng_dict

def main():
    input_string = input("Enter sentence")
    string_leng(input_string)

if __name__ == "__main__":
    main()

The output is as follows:
Enter sentencethis is a test test needs a check
{4: ['this', 'test', 'test'], 2: ['is'], 1: ['a', 'a'], 5: ['needs', 'check']}

The output I'm looking for is :
{5: ['needs', 'check'] , 4: ['this', 'test', 'test'], 2: ['is'], 1: ['a', 'a']}

A: Firstly a dictionary needs have unique key values so your "looking to split each words" output, i.e.:
{5: ['needs'] , 5: ['check'] , 4: ['this'] , 4: ['test'], 4: ['test'], 2: ['is'], 1: ['a'], 1:['a']}

is not possible.
Regarding your initial desired output, in python3.6+ this is achievable with a slight modification to your current solution since dictionaries maintain insertion order:
def string_leng(user_string):
    leng_dict = {}
    user_string = user_string.split(" ")
    for word in user_string:
        if len(word) in leng_dict:
            leng_dict[len(word)].append(word)
        else:
            leng_dict[len(word)] = [word]
    res = {}
    for key in sorted(leng_dict.keys(), reverse=True):
      res[key] = leng_dict[key]
    return res
    # or equivalently using a dictionary comprehension
    # {k : leng_dict[k] for k in sorted(list(leng_dict.keys()), reverse=True)}

def main():
    input_string = input("Enter sentence: ")
    print(string_leng(input_string))

if __name__ == "__main__":
    main()

Example Usage:
Enter sentence: this is a test test needs a check
{5: ['needs', 'check'], 4: ['this', 'test', 'test'], 2: ['is'], 1: ['a', 'a']}

Alternate version that does not use the builtin sorted or reverse functions
Feel free to replace the quick_sort or reverse functions with different implementations:
def quick_sort(a):
    left = []
    pivot_list = []
    right = []
    if len(a) > 1:
        pivot = a[0]
        for i in a:
            if i < pivot:
                left.append(i)
            elif i > pivot:
                right.append(i)
            else:
                pivot_list.append(i)
        left = quick_sort(left)
        right = quick_sort(right)
        return left + pivot_list + right
    return a

def reverse(a):
    list_length = len(a)
    for i in range(list_length // 2):
        a[i], a[list_length - 1 - i] = a[list_length - 1 - i], a[i]
    return a

def string_leng(user_string):
    leng_dict = {}
    user_string = user_string.split(" ")
    for word in user_string:
        if len(word) in leng_dict:
            leng_dict[len(word)].append(word)
        else:
            leng_dict[len(word)] = [word]
    res = {}
    for key in reverse(quick_sort(list(leng_dict.keys()))):
        res[key] = leng_dict[key]
    return res
    # or equivalently using a dictionary comprehension
    # return {k : leng_dict[k] for k in reverse(quick_sort(list(leng_dict.keys())))}

def main():
    input_string = input("Enter sentence: ")
    print(string_leng(input_string))

if __name__ == "__main__":
    main()


text:
Q: Does Saved Document Library Template become available to all subsites? I have a test Site Collection.  I've added a document library to the root site and added content types to it.  When I save this Document Library as a template under Library Settings, this "App" becomes available to a subsite I created.
Will this work in a real environment?  If Permissions on the root site and a subsite are different, would this App still be available?
Thanks!

A: To answer your final question - the app (Document Library template) would still be available on the subsite.  Whether or not users can use the template you have created would be determined by their user permissions.
I believe the individual permission is 'manage lists', see this link for more info.  For further reading this link is also of use.  PLease note that there are multiple OOTB groups that have the 'manage lists' permission.  (A group is assigned a collection of permissions, which behave cumulatively).


text:
Q: Mysql CASE and UPDATE I'm trying to do this query which updates only the first column that is empty. Here is a query so far:
UPDATE `names` SET
`name_1` = CASE WHEN `name_1` = '' then 'Jimmy' else `name_1` end,
`name_2` = CASE WHEN `name_1` != '' and `name_2` = '' then 'Jimmy' else `name_2` end

It updates all of columns with 'Jimmy'. I think that that's because the SET will update it then move on to the next SET and will update that etc...Am I right on what's causing this? If so how could I fix this? If not how should I rewrite this?

A: I think if you swap the order, it will work properly.
Try this:
UPDATE `names` SET
`name_2` = CASE WHEN `name_1` != '' and `name_2` = '' then 'Jimmy' else `name_2` end,
`name_1` = CASE WHEN `name_1` = '' then 'Jimmy' else `name_1` end

A: I'm wondering if null values might be causing you problems.  You could use the IFNULL function to convert them to empty strings (in case you have empty strings and NULLs).  Try this:
UPDATE `names` SET
    `name_1` = CASE WHEN IFNULL(`name_1`, '') = '' then 'Jimmy' else `name_1` end,
    `name_2` = CASE WHEN IFNULL(`name_1`, '') != '' and IFNULL(`name_2`, '') = '' then 'Jimmy' else `name_2` end

or if you have all nulls:
UPDATE `names` SET
    `name_1` = CASE WHEN `name_1` IS NULL then 'Jimmy' else `name_1` end,
    `name_2` = CASE WHEN `name_1` IS NOT NULL and `name_2` IS NULL then 'Jimmy' else `name_2` end


text:
Q: Is there a way to check if the AccountName exists from Azure Storage account? I was playing around with Storage accounts from Azure and I saw that invalid AccountName (from connectionString) doesn't throw an error that the AccountName is invalid, instead it times out after 20 seconds. I use a connection string to connect:
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
I saw some resources that having blobServiceClient.GetProperties(); might throw an error and by this way gain a knowledge that the AccountName is invalid but as I said, it times me out and having to wait 20 seconds isn't an option for my app before returning a message that the AccountName is invalid.
The error I get is Retry failed after 6 tries.
Why I'm doing this is because my app uses a few storage accounts so for each of them the user specifies which account to use. I'd like to handle the scenario where the user will type a storage account (name) which is not present at all.
Any ideas how can I check whether the given AccountName exists in my Storage account or not, from .NET?

A:
Any ideas how can I check whether the given AccountName exists in my
Storage account or not, from .NET?

You can use Microsoft.Azure.Management.Storage Namespace to perform management related operations on a storage account in particular StorageAccountsOperationsExtensions.GetPropertiesAsync(IStorageAccountsOperations, String, String, Nullable<StorageAccountExpand>, CancellationToken) method to see if the storage account exists in your Azure Subscription or not.
One of the problem you're facing is that it takes a long time to get the properties of your account using BlobServiceClient.GetProperties() method. You can cut down that time considerably by reducing the amount of retires that are performed by the SDK. By default the SDK retries a retryable operation 5 times (a total of 6 times). However you can configure the retry policy to not retry the operation. For example, please see the code below:
BlobClientOptions clientOptions = new BlobClientOptions()
{
    Retry =
    {
        MaxRetries = 0
    }
};
BlobServiceClient serviceClient = new BlobServiceClient(connectionString, clientOptions);
var properties = await serviceClient.GetPropertiesAsync();

The code above will only try to get the properties once (no retries). You will have to capture any exception that GetPropertiesAsync method throws and determine if the storage account does not exist, the storage account key is invalid or the code failed because of some other reasons.


text:
Q: PHP MySQL - An attempt at recursive functions I'm trying out my first recursive function (at least I think I am!) and it only half works. First, the code:
function check_title($i,$title) {
    $q=mysql_query("SELECT Title FROM posts WHERE Title = '$title'");
    $num=mysql_num_rows($q);
    if($num==0) {
            return $title;
    }else {
            $title=$title.' ('.$i++.')';
            check_title($i,$title);
    }
}

What I'm doing is taking a string (title) and checking if that title exists in the db already. If it does, I want to append a number to the newer of the duplicates (e.g. 'I Am A Title' becomes 'I Am A Title-2'). I then need to run the function again to check this new version of my title, and increase the appended value as required ('I Am A Title-3'). Once no duplication is discovered, return the Title in its acceptable form.
It works when no duplication is found (the easy bit), but fails when duplication is found. Instead of appending a number, the entire title variable is emptied.
Any help would by greatly appreciated!

A: As Mchl stated, the empty title is due to a lack of return in the else branch.
However, there is a problem with the function as it does not do what you intend. Currently, your function is building $title as 'Title-1-2-3-4-etc' the way you currently append the number to the title and check again. Instead of passing a modified title on the recursed call you should just pass the base title. Then, for the query, modify the title.
function check_title($title, $i = 0) {
    $qtitle = $title . ($i == 0 ? '' : "-$i");
    $q=mysql_query("SELECT Title FROM posts WHERE Title = '$qtitle'");
    $num=mysql_num_rows($q);
    if($num==0) {
        return $title . ($i == 0 ? '' : "-$i");
    }else {
        return check_title(++$i,$title);
    }
}

PS, I also changed the order of parameters that way your initial call doesn't need to specify 0.
$title = check_title($title);

PPS, I should mention this is a solution to do it via recursion. However, a recursive solution is not the proper solution here as it needlessly makes return trips to the DB. Instead, you should use an sql query that selects all titles LIKE "$title%" Order by title asc. Then, iterate through each result and do a regex comparison with the title to see if it matches a pattern <title>|<title>-<#>. If it does you increment a duplicate counter. At the end you spit out the title with an appended counter value. I'll leave that solution as an exercise for the original poster.

A: *

*You lack a return in else branch.

*Recursion is not the best idea for this application. Hint: do a query like this SELECT MAX(Title) FROM posts WHERE Title LIKE '$title%');

A: Use a loop instead...
$record_exists = true;
$title_base = "I Am A Title";
$title = $title_base;
$i = 0;
while($record_exists) {
    $q=mysql_query("SELECT Title FROM posts WHERE Title = '$title'");
    $num=mysql_num_rows($q);
    if($num==0) {
        $record_exists = false;
        // Exit the loop.
    }
    else {
        $i++;
        $title = $title_base . "-" . $i;
    }
}

echo $title; // last existing title

However, optimally you'd do more work with a single SQL query and iterate the result, saving a lot of trips to and from the database.
And just for fun...
$title_base = "I Am A Title";
$title = $title_base;
for ($i=1, $num=1; $num != 0; $i++)
{
    $q=mysql_query("SELECT Title FROM posts WHERE Title = '$title'");
    $num=mysql_num_rows($q);
    $title = $title_base . "-" . $i;
}

echo $title; // next title in sequence (doesn't yet exist in the db)

A: Your recursive function is fine except for 2 things:

*

*The original title isn't maintained between recursive calls. Hence each time $title = $title . ' (' . $i++ . ')' runs, another parenthesis is appended to the title, like "abc", "abc (1)", "abc (1) (2)" and so on.

*You are returning $title when no more matches are found but no title is returned in the ELSE. It is important to do so. When the execution reaches the IF, it returns the title but the returned title is not assigned anywhere and hence is lost.
Here is the revised code:
$orgTitle = 'I am a title';
function check_title($i, $title = '') {
    global $orgTitle;
    $q = mysql_query("SELECT Title FROM posts WHERE Title = '$title'");
    $num = mysql_num_rows($q);
    if ($num == 0) {
        return $title;
    } else {
        $title = $orgTitle . ' (' . ++$i .')';
        return check_title($i, $title);
    }
}
echo check_title(0, $orgTitle);

Note the addition of new variable $orgTitle. I've replaced it in the assignment statement inside the ELSE. This does the fix for point 1 above.
Also note the return added before check_title call in the ELSE. This solves point 2.
Hope it makes sense!
Add-on: Recursions are confusing, logically complex and tricky to debug. Also, recursive calls consume more memory (not in case of simple operations like your example) because the compiler/interpreter had to maintain the state variables for all steps in a recursion.

A: In order to minimise MySql interactions I'd recommend something similar to the following.
function checkTitle($title)
{
    /*Return all iterations of the title*/
    $res = mysql_query("SELECT COUNT(title) AS titleCount FROM posts
                    WHERE SUBSTR(title, 1,". strlen($title) .") = '$title' ");
    /*Return the incremented title*/
    return $title. (mysql_result($res, 0, "titleCount")  + 1);

}

Example:
mysql> select title from posts;
+----------+
| title    |
+----------+
| firefox1 |
| firefox2 |
| shoe     |
| firefox3 |
+----------+
4 rows in set (0.00 sec)

mysql> SELECT COUNT(title) AS titleCount FROM posts WHERE SUBSTR(title, 1,7) = 'firefox' ;
+------------+
| titleCount |
+------------+
|          3 |
+------------+
1 row in set (0.00 sec)
mysql>

---- Follow up test
Test table structure.
mysql>SHOW COLUMNS FROM posts;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| title | varchar(12) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

/*Test code and output*/
function checkTitle($title)
{
    /*Return all iterations of the title*/
    $res = mysql_query("SELECT COUNT(title) AS titleCount FROM posts
                    WHERE SUBSTR(title, 1,". strlen($title) .") = '$title' ");
    /*Return the incremented title*/
    return $title. (mysql_result($res, 0, "titleCount")  + 1);

}
mysql_connect("localhost","root", "password");
mysql_select_db("test");
echo checkTitle("firefox");

Output: firefox4


text:
Q: How do i return 0 as decimal value as default if there are not data in linq query? workedHours = db.WorkedHours.
                 Where(wh => wh.EmployeeId == ID).
                 Sum(h => h.DayHours)

this part of the query may or may not have data and
db.WorkedHours.Where(wh => wh.EmployeeId == ID)

I am trying to Sum.How do I return 0 in case there are no data to do sum?

A: var sum = db.WorkedHours
    .Where(wh => wh.EmployeeId == ID)
    .Select(h => h.DayHours)
    .DefaultIfEmpty(0)
    .Sum();


text:
Q: What can be the query for this statement in Elasticsearch I am trying to have this query in elasticsearch
statement:
(ip=xx.xx.xx.xx and status="running") or (ip=xx.xx.xx.xx and status="running")

can anyone tell me how can i write this in elasticsearch query.

A: Read about Bool Queries
Try this query:
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "ip": {
                    "value": "xx.xx.xx.xx"
                  }
                }
              },
              {
                "term": {
                  "status": {
                    "value": "running"
                  }
                }
              }
            ]
          }
        },
         {
          "bool": {
            "must": [
              {
                "term": {
                  "ip": {
                    "value": "bb.bb.bb.bb"
                  }
                }
              },
              {
                "term": {
                  "status": {
                    "value": "running"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}


text:
Q: ID repetido com facelets O problema é que em um projeto que utilizo facelets está me dizendo que existe um componente com o ID repetido. Embora eu tenha varrido o código atrás de encontrar o tal ID repetido, não o encontrei, por isso acredito que o erro esteja relacionado ao uso incorreto do facelets. Gostaria de saber de vocês como posso resolver. Segue os códigos abaixo:
Código do template:
<!DOCTYPE html>

    <h:head>
        <f:facet name="first">
            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1" />
        </f:facet>

        <title>AudSped</title>

        <h:outputStylesheet library="bluegestao" name="styles/custom.css" />
        <h:outputStylesheet library="bluegestao" name="styles/layout.css" />
        <h:outputStylesheet library="bluegestao" name="styles/components.css" />

        <h:outputScript target="body" library="primefaces" name="jquery/jquery.js" />
        <h:outputScript target="body" library="bluegestao" name="javascripts/app.js" />
    </h:head>

    <h:body>

            <h:graphicImage library="bluegestao" name="images/logo.png" />

                <h:form>

                </h:form>

            <ui:insert id="conteudo" name="content" />

    </h:body>

Página de Manutenção de Registros:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html>

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:f="http://xmlns.jcp.org/jsf/core"
                xmlns:h="http://xmlns.jcp.org/jsf/html"
                xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
                xmlns:p="http://primefaces.org/ui"
                template="/WEB-INF/templates/Layout.xhtml">

    <ui:define name="content">
        <h:form>

Manutenção de Registros

        </h:form>
        <ui:include src="#{manutencaoRegistrosBean.bloco}/#{manutencaoRegistrosBean.registro}/List.xhtml"/>
    </ui:define>

</ui:composition>

Código da página chamada:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
                xmlns:f="http://xmlns.jcp.org/jsf/core"
                xmlns:h="http://xmlns.jcp.org/jsf/html"
                xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
                xmlns:p="http://primefaces.org/ui"
                template="/WEB-INF/templates/Layout.xhtml">

Registro 0000

        <h:form id="Reg0000ListForm">

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_id}"/>
                        </f:facet>
                        <h:outputText value="#{item.id}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_idPai}"/>
                        </f:facet>
                        <h:outputText value="#{item.idPai}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_linha}"/>
                        </f:facet>
                        <h:outputText value="#{item.linha}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_hash}"/>
                        </f:facet>
                        <h:outputText value="#{item.hash}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_reg}"/>
                        </f:facet>
                        <h:outputText value="#{item.reg}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_codVer}"/>
                        </f:facet>
                        <h:outputText value="#{item.codVer}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_codFin}"/>
                        </f:facet>
                        <h:outputText value="#{item.codFin}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_dtIni}"/>
                        </f:facet>
                        <h:outputText value="#{item.dtIni}">
                            <f:convertDateTime pattern="dd/MM/yyyy" />
                        </h:outputText>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_dtFin}"/>
                        </f:facet>
                        <h:outputText value="#{item.dtFin}">
                            <f:convertDateTime pattern="dd/MM/yyyy" />
                        </h:outputText>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_nome}"/>
                        </f:facet>
                        <h:outputText value="#{item.nome}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_cnpj}"/>
                        </f:facet>
                        <h:outputText value="#{item.cnpj}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_cpf}"/>
                        </f:facet>
                        <h:outputText value="#{item.cpf}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_uf}"/>
                        </f:facet>
                        <h:outputText value="#{item.uf}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_ie}"/>
                        </f:facet>
                        <h:outputText value="#{item.ie}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_codMun}"/>
                        </f:facet>
                        <h:outputText value="#{item.codMun}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_im}"/>
                        </f:facet>
                        <h:outputText value="#{item.im}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_suframa}"/>
                        </f:facet>
                        <h:outputText value="#{item.suframa}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_indPerfil}"/>
                        </f:facet>
                        <h:outputText value="#{item.indPerfil}"/>

                        <f:facet name="header">
                            <h:outputText value="#{bundle.ListReg0000Title_indAtiv}"/>
                        </f:facet>
                        <h:outputText value="#{item.indAtiv}"/>

                    <f:facet name="footer">

                    </f:facet>

        </h:form>
        <ui:include src="Create.xhtml"/>
        <ui:include src="Edit.xhtml"/>
        <ui:include src="View.xhtml"/>

</ui:composition>

O erro acontece quando requisito a página página de manutenção de registros que deveria incluir a outra (List.xhtml) mas me mostra o seguinte erro:

08:48:59,560 FATAL [javax.enterprise.resource.webcontainer.jsf.context] (default task-52) JSF1073: java.lang.IllegalStateException obtido durante o processamento de RENDER_RESPONSE 6: UIComponent-ClientId=, Message=A ID de componente growl já foi encontrada na visualização.
08:48:59,560 FATAL [javax.enterprise.resource.webcontainer.jsf.context] (default task-52) A ID de componente growl já foi encontrada na visualização.: java.lang.IllegalStateException: A ID de componente growl já foi encontrada na visualização.

A: Primeiramente, seu growl deve estar dentro de um <h:form>
Sugestão é que você coloque um growl específico para cada página
Você está repetindo o componente growl que está no seu template:

Isso significa que você está repetindo o growl em todas as suas páginas que utilizam o template.
Quando for colocar uma página dentro de outra que já contém o template, você não deve chamar template na ui:composition dessa sub-página, apenas na página principal.


text:
Q: smb.conf csc policy parameters I am administering a standalone user-authenticated Samba 4.3.11 server on Ubuntu 16.04, which is accessed by Windows 7 Pro and 10 Pro clients configured to cache offline files.
The question is, what is the difference between the following parameters for smb.conf:
(a) csc policy = manual [the default]
(b) csc policy = documents
(c) csc policy = programs
I haven't found anything distinguishing these parameters in two hours on Google.  The smb.conf man page is cryptic, referencing Windows Server policies that no amount of research discerns corresponding concepts.  The impression I have gleaned is that "manual" permits user-initiated (i.e., not automatic) file sync and that one or the other of "documents" or "programs" permits automatic file sync.
The Windows clients' Group Policy has been configured to sync at logon, logoff, and specified intervals but this does not occur, at least not obviously.  Users can manually initiate syncs, however, consistent with my impression of the default setting.
Any thoughts on the distinctions among these parameters would be most welcome.

A: There is not much documentation on this topic at all. I also noticed that clients sometimes ignore this policy.
One thing I noticed in the past: if you use roaming profiles you have to disable csc policy on that share or weird things will happen (profiles do not sync, strange error messages on the client during profile sync)
AFAICT these parameters just tell the client what to do and won't change the server's behaviour in any way other then telling the client what csc policy is set for this share.
There are four valid values for csc policy. I will try to describe what I understood these parameters do:
disabled
Disable client-side caching of resources on this share.
manual
Allow the client to decide settings for client-side caching of resources on this share.
documents and programs
Optimize the client-side caching for the use with documents or for the use of programs from this share.

A: Warning: Offline Files and multiple users receiving "Access is denied" during sync.
(at least for Windows 10) if folder redirection is enabled then that Offline Files sync for that location will be enabled.
imagine that you have set the \\computer\Users share server side to tell clients that it is to be cached [csc policy = documents] AND also have folder redirection enabled with Offline Files. ie;
\\computer\Users
AND
\\computer\Users\userA
\\computer\Users\userB
\\computer\Users\userC
if userA, userB or userC is logged in, Windows will cache the current respective user and  the ENTIRE \\computer\Users\ location :- and most likely fail, as the current logged in user may not have access to all other sub folders of the parent \\computer\Users
https://social.technet.microsoft.com/Forums/windowsserver/en-US/322c9a4d-30bc-482a-8719-91b90fdcd757/offline-files-multiple-users?forum=winserverGP


text:
Q: Type mismatch when populating an Array Could anyone tell me why this line is throwing up a "Type Mismatch" Error?
 Dim Req_Info() As Variant
Req_Info = xlWB.Worksheets("Sorted").Range("B1", xlWB.Worksheets("Sorted").Range("A1").End(xlDown))

It had been working perfectly at one point?

A: To Answer my own question, the solution was to replace
Dim Req_Info() As Variant

With
Dim Req_Info As Variant

Would anyone be able to explain why this is?


text:
Q: AdaptiveChars v1.2 Schema Updates I see AdaptiveCards v1.2.0 was released a few days ago. It is described as having implemented the "wrap" property for ChoiceSet; however, I don't see this property in the schema of the downloaded package. Can we get confirmation that this was in-fact implemented in 1.2 and working? I've not been able to test this out due to other commitments, but am working with a customer who is needing this property.
This is item #14 on the below 1.2 release:
https://github.com/microsoft/AdaptiveCards/releases/tag/v1.2.0
In the 1.2.0 source, here is the schema for ChoiceSet from schemas/adaptive-card.json:
        "Input.ChoiceSet": {
            "additionalProperties": true,
            "type": "object",
            "description": "Allows a user to input a Choice.",
            "allOf": [
                {
                    "$ref": "#/definitions/CardElement"
                }
            ],
            "properties": {
                "choices": {
                    "type": "array",
                    "description": "`Choice` options.",
                    "items": {
                        "$ref": "#/definitions/Input.Choice"
                    }
                },
                "id": {
                    "type": "string",
                    "description": "Unique identifier for the value. Used to identify collected input when the Submit action is performed."
                },
                "isMultiSelect": {
                    "type": "boolean",
                    "description": "Allow multiple choices to be selected.",
                    "default": false
                },
                "style": {
                    "$ref": "#/definitions/ChoiceInputStyle"
                },
                "type": {
                    "description": "Must be `\"Input.ChoiceSet\"`.",
                    "enum": [
                        "Input.ChoiceSet"
                    ],
                    "type": "string"
                },
                "value": {
                    "type": "string",
                    "description": "The initial choice (or set of choices) that should be selected. For multi-select, specify a comma-separated string of values."
                }
            },
            "required": [
                "type",
                "id",
                "choices"
            ]
        },

I don't see the "wrap" property listed here.

A: Microsoft Teams does not currently support Adaptive Cards 1.2.

A: thanks for asking about this. This is Andrew from the Adaptive Cards team.
The schema file you were looking at back at the beginning of June seems to be the old 1.1 schema. It's possible we didn't have the 1.2 schema published yet at that time.
Here's the new 1.2 schema, which indeed does have wrap on Input.ChoiceSet: https://adaptivecards.io/schemas/1.2.0/adaptive-card.json
Also, on our docs, you can see the wrap property: https://adaptivecards.io/explorer/Input.ChoiceSet.html
Let us know if you have any further questions!


text:
Q: Convert a hex string to base64 in Julia I am trying to convert a hex string to base64 in Julia. I looked at Codecs.jl but I am not sure if that will help me.
The hex string I want to convert is 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d.
Not really sure where to start here so any suggestions are welcomed.

A: For this you want to use Base64 from the standard library. First use hex2bytes to convert your string to a byte array, then base64encode to convert it back to a  string:
using Base64
function base16to64(st::AbstractString)
    bytes = hex2bytes(st)
    return base64encode(bytes)
end


text: Q: How to deploy REST with basic authentication in Solr 6.6.1 I have deployed Apache Solr 6.6.1 with basic authentication by following their reference guide. At the end they have discussed how to use curl with security. For my case, I am using REST API to query SOLR. How can I request solr via REST API with basic authentication enabled ?


text:
Q: Simulate Vehicle tracking in omnet++ I want to simulate vehicle tracking in wireless sensor network using OMNeT++.
I have created WSN. But i don't know how to add vehicle object and move that object in that network. I need some ideas or source code.

A: Although this can be achieved using Veins, you might find some functionality missing that is relevant to sensor networks (e.g., battery consumption).
Recent versions of the INET Framework contain parts of Veins that allow you to move nodes according to vehicles' movement. See the documentation of the TraCIMobility class for more information.

A: You can use SUMO for vehicle mobility simulation, and connect it with OMNeT through Veins framework.


text:
Q: Which layers are frozen using Tensorflow 2 Object detection API? How can I understand which layers are frozen fine-tuning a detection model from Tensorflow Model Zoo 2?
I have already set with success the Path for fine_tune_checkpoint and fine_tune_checkpoint_type: detection and in the file proto I have already read that "detection" means
// 2. "detection": Restores the entire feature extractor.
The only parts of the full detection model that are not restored are the box and class prediction heads.
This option is typically used when you want to use a pre-trained detection model
and train on a new dataset or task which requires different box and class prediction heads.

I didn't really understand what does that means. Restored means Frozen in this context?

A: As I understand it, currently the Tensorflow 2 Object detection does not freeze any layers when training from a fine tune checkpoint. There is a issue reported here to support specifying which layers to freeze in the pipeline config. If you look at the training step function, you can see that all trainable variables are used when applying gradients during training.
Restored here means that the model weights are copied from the checkpoint to be used as a starting point for training. Frozen would mean that the weights are not changed (i.e. no gradient is applied) during training.


text:
Q: sass @use directive and mobile first approach Recently I migrated a project to dartsass directive @use instead of @import.
I understood the main goal of @use directive but I think I missing something.
@use rule must come before any other rules... so I can't add a sass file at the end of main style.scss
In this way I can't apply the mobile first approach... Normally I write all mobile rules in main file and then, at the end of it, include the media query rules.
With @use directive I can't achive this. So for media-query scss I need to use @import in mainstyle.scss
Any suggestion?

A: Ok, I think that the only way is to transform the main file with css rules in another included file with @use directive and leave the main file as "container" of all components.

A: You can still use @import. Though it says it's going to be depricated, it is still perfectly fine to use it.But you might generally concidere to switch to a more modular file structure, when it comes to your Sass projects. For example:
/root
  _desktop.scss
  _mobile.scss
  main.scss

// main.scss
@use (@import) "desktop";
@use (@import) "mobile";


text:
Q: Three.js intersection raycaster I have created some geometry and some functions to move and detect it.
 It works perfect but now I have inserted it into a javascript UI library http://dhtmlx.com/ and doesn't work well. The problem is this: for example using raycaster, it find intersection with geometry also when geometry isn't under the mouse. It looks like all geometries are moved up from original position  and draw is a fake.
I made an example in this url : http://www.felpone.netsons.org/web-threejs%20-%20Copia/contact_manager/prova2.html. You can see the complete code in the console.
As you can see in the live example you can drag the cube also if you click above it.

A: I think its because mouse coordinates are document coordinates, and not the coordinates in your canvas.
In my applications I determine the correct coordinates for rays like this:
var mouseX = event.clientX - myCanvas.offsetLeft;
var mouseY = event.clientY - myCanvas.offsetTop;

var mouseXForRay = (mouseX / this.canvas.width) * 2 - 1;
var mouseYForRay = -(mouseY / this.canvas.height) * 2 + 1;


text:
Q: GMAIL SMTP ERROR: Failed to connect to server I am sending emails using Gmail SMTP in PHP. I also enabled OPENSSL in php.ini. But I am getting this error.

SMTP -> ERROR: Failed to connect to server: A connection attempt
  failed because the connected party did not properly respond after a
  period of time, or established connection failed because connected
  host has failed to respond. (10060) The following From address
  failed: mhtkumar46@gmail.com : Called Mail() without being connected
  Send mail fail.

Here is my code.
<?php
error_reporting(E_ALL);
require("PHPMailer_5.2.4/class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->SMTPDebug  = 2;
$mail->Debugoutput = 'html';
$mail->From = "mhtkumar46@gmail.com";
$mail->FromName = "Mohit";
$mail->Host = "smtp.gmail.com"; // specif smtp server
$mail->SMTPSecure= "tls"; // Used instead of TLS when only POP mail is selected
$mail->Port = 587; // Used instead of 587 when only POP mail is selected
$mail->SMTPAuth = true;
$mail->Username = "mhtkumar46@gmail.com"; // SMTP username
$mail->Password = "*******"; // SMTP password
$mail->AddAddress("mohitkumarsingla60@gmail.com", "Singla"); //replace myname and mypassword to yours
$mail->AddReplyTo("mhtkumar46@gmail.com", "Mohit");
$mail->WordWrap = 50; // set word wrap
//$mail->AddAttachment("c:\\temp\\js-bak.sql"); // add attachments
//$mail->AddAttachment("c:/temp/11-10-00.zip");

$mail->IsHTML(true); // set email format to HTML
$mail->Subject = 'test';
$mail->Body = 'test';

if($mail->Send()) {echo "Send mail successfully";}
else {echo "Send mail fail";}
?>

I am unable to find the solution. Please help me.


text:
Q: Can I use the same instance in two different entities in VHDL code? I want to use "inst_A" of an entity "A" used in the architecture of entity "B" in the architecture of another entity "C". I want it to be the same instance.
Like, I have used an instance called "s1" of an array of std_ulogic_vectors whose indexes are also std_ulogic_vectors. I am storing data in one entity and i want to read the data in another entity

A: For synthesis, no. Each instance is unique; if you need to share data between two places, you must connect signals between these two places. It's not clear exactly why you have ended up wanting this; it sounds like you might want to re-think the structure of your design a bit, but without giving us any real information, I can only speculate.
In simulation, you can use aliases to access signals in the design hierarchy. Look up the alias keyword. I won't detail it here because I'm guessing that you are not after a simulation-only solution.


text:
Q: How to get value of node in XML with namespace and not throw exception if node is not found? I'm using LinqToXml to get the value of notes with the name GUID. So XML can look like this:
<xml>
   <node1>
      <GUID>123948390</GUID>
   </node1>
<xml>

It may also be nested into more nodes. There is only one GUID per possible XML string.
What I am trying to do is parse the XML to collect the GUID element. The XML I am parsing may or may not contain a GUID element. If it does not contain an GUID element I want it to return an empty string.
What I tried is:
 doc.Elements().Where(e => e.Name.LocalName == "GUID").Single().Value;

where doc is an XDocument, but this does not find the value and throws an exception if nothing is found. How can I get the value of the GUID element and make sure no exceptions are thrown if nothing is found?
/edit
  var doc = XDocument.Parse(xmlString);
            this.RequestId =  (string)doc.Descendants("GUID").SingleOrDefault() ??
                     String.Empty;

always returns an empty string. Even if there is a GUID.
xmlString looks as follows: <?xml version=\"1.0\" encoding=\"utf-8\"?><MethodName xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\><GUID>blabla</GUID></MethodName>.

A: You should use Descendants if you want to search over all document. You can cast element to string to get its value without having NullReferenceException if there is no such element in document:
var guid = (string)doc.Descendants("GUID").SingleOrDefault() ?? String.Empty;

Or
var guid = doc.Descendants("GUID")
              .Select(g => (string)g)
              .SingleOrDefault(String.Empty);

Or with XPath
var guid = (string)doc.XPathSelectElement("//GUID") ?? String.Empty;

NOTE: If you have default xml namespace defined in your real xml document, then you should provide namespace to get element name:
var ns = doc.Root.GetDefaultNamespace();
var guid = (string)doc.Descendants(ns + "GUID").SingleOrDefault() ?? "";

A: If your element is not found it will be returning null. Single does not allow null's.
Use SingleOrDefault to return a null and then test that null condition...
var element = doc.Elements()
    .Where(e => e.Name.LocalName == "GUID")
    .SingleOrDefault();

if(element != null) {
    return element.Value;
}


text:
Q: Days Unavailable I need a simple SQL to accomplish the below:
Problem:
When a petrol bunk runs out of fuel, the admin makes note of the DateTime (RunOutDate) when it ran out of fuel and notes also the DateTime (ResupplyDate) when the fuel supply was back on.
I need to create a report on how many days the bunk ran out of fuel.
eg.
1/1/1 10:10 to 1/1/1 10:50 should be counted as 1
1/1/1 10:10 to 2/1/1 07:20 should be counted as 2
1/1/1 23:55 to 2/1/1 00:10 should be counted as 2
I can not bank using hours using DateDiff as 24 hours could have spanned across 2 days.
TIA

A: DATEDIFF(d, RunOutDate, ResupplyDate) + 1

Remember that DATEDIFF always counts the number of BOUNDARIES that you cross. For days (first argument d), it counts the number of times the clock passed midnight. So to count the number of days covered you just add 1.

A: DATEDIFF using day, then add 1.
DATEDIFF uses the midnight to count days so you'll get 0, 1, 1 for each example above. Then add 1.
DATEDIFF(day, '16 Dec 2008 10:10', '16 Dec 2008 10:50') + 1


text:
Q: got positional argument error when using decorator in python I have defined a decorator function in python, but I get positional argument error when using it. This is my code:
def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))

Returned error is:
Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.

A: As the error says, your wrapper function doesn't accept any arguments. It needs to accept the same args as the function it is wrapping.
def wrapper(arg):
    return func(arg).upper()

A: wrapper wraps the function, meaning it will 'act in its place'.
Therefore, if you call print_name("zeinab"), the wrapper will be called instead with wrapper("zeinab").
wrapper doesn't accept the "zeinab" argument, because you didn't give it any parameters.
def my_upper_case(func):

    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))


text:
Q: How to test all sample combinations for significant differences? I'm analyzing a dataset of 9 plots in R and want to compare them with each other. My responding variables are not normally distributed.
Now my question:
There are 9+8+7+...+2+1=45 pair-combinations to be tested. Can R do this automatically? If yes, how?
My wish-output would be a box-whisker plot with my 9 plots on the x-axis, the responding variable on the y-axis and lowercase letters above the plots to indicate significant differences.
Thanks in advance!

A: This should get you started:
#some data
x <- rlnorm(100, mean=1:4)
DF <- data.frame(x=x, g=c("a", "b", "c", "d"), stringsAsFactors=FALSE)

#pairwise Mann-Whitney-U-test
pairwise.wilcox.test(DF$x, DF$g, p.adjust.method = "bonferroni")

#   Pairwise comparisons using Wilcoxon rank sum test
#
#data:  DF$x and DF$g
#
#  a       b       c
#b 0.0016  -       -
#c 6.3e-09 0.0020  -
#d 1.9e-13 2.0e-08 0.1823
#
#P value adjustment method: bonferroni


text:
Q: How do I update the limit lines in IOS Charts, danielgindi/Charts So I have added a couple of limit lines.
func addLimitLines() {
    let stopLoss = ChartLimitLine(limit: Double(1.70) , label: "stop loss")
    stopLoss.lineWidth = 0.5
    stopLoss.lineColor = .blue
    stopLoss.lineDashLengths = [8.0]
    chartView.rightAxis.addLimitLine(stopLoss)

    let takeProfit = ChartLimitLine(limit: Double(1.68), label: "take profit")
    takeProfit.lineWidth = 0.5
    takeProfit.lineColor = .blue
    takeProfit.lineDashLengths = [8.0]
    chartView.rightAxis.addLimitLine(takeProfit)
    chartView.reloadInputViews()
}

@IBAction func stopLossChange(_ sender: UISlider) {
   //slider action for updating the stoploss limitline
}

@IBAction func takeProfitChange(_ sender: UISlider) {
   //slider action for updating the takeprofit limitline
}

Now I want to update the limitline values whenever I move the sliders.

A: Although in Android version of Charts we have invalidate() that refreshes the chartView but in iOS i don't see its available. In iOS i use to update data with animate methods and i believe you can also achieve this as follows,
@IBAction func stopLossChange(_ sender: UISlider) {
    self.updateLineLimit(Double(sender.value), label: "stop loss")
}

@IBAction func takeProfitChange(_ sender: UISlider) {
    self.updateLineLimit(Double(sender.value), label: "take profit")
}

private func updateLineLimit(_ value: Double, label: String) {
    if let line = chartView.rightAxis.limitLines.filter({ $0.label == label }).first {
        line.limit = value
        chartView.animate(yAxisDuration: 0.00001)
    }
}


text:
Q: Displaying a custom post type title within another loop I have a Custom Post Type set up called Venues. I'm also using a plugin called Event Organiser, and I want to display the title and link to the venue within one of the Event Organiser templates.
The code is:
<?php if( $eo_event_loop->have_posts() ): ?>

<ul <?php echo $id; ?> class="<?php echo esc_attr($classes);?>" >

    <?php while( $eo_event_loop->have_posts() ): $eo_event_loop->the_post(); ?>

        <?php
            //Generate HTML classes for this event
            $eo_event_classes = eo_get_event_classes();

            //For non-all-day events, include time format
            $format = ( eo_is_all_day() ? $date_format : $date_format.' '.$time_format );
        ?>

        <li class="<?php echo esc_attr(implode(' ',$eo_event_classes)); ?>" >
            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php the_title(); ?> at VENUE NAME HERE <?php echo __('on','eventorganiser') . ' '.eo_get_the_start($format); ?>

    <?php endwhile; ?>

Where VENUE NAME HERE is, I want the title and link to my custom post type. Might be just something really simple I'm missing, but any help much appreciated.

A: I used Advanced Custom Fields plugin and used 'Relationship' field so that I could choose a Venue for each event. Then used this code to bring through the Venue link:
<?php $venue = get_field('location_venue'); ?>
<?php foreach( $venue as $venue ): ?>
<a href="<?php echo get_permalink( $venue->ID ); ?>"><?php echo get_the_title( $venue->ID ); ?>
<?php endforeach; ?>

More info available here:
http://www.advancedcustomfields.com/resources/tutorials/querying-relationship-fields/


text:
Q: Android Get External UI Component Handles Is there a method/work around for a process to receive external UI component handles in the Android platform?
The reason why I am doing this is to benchmark applications, so I would like to read and log application states (UI component numbers, texts, positions, layout so forth) via a service. This will only be for testing purposes, so requiring root privileges or something like that is okay.
In the windows world, I would use win32 APIs or some other API to access UI components. Of course, to my understanding, Android is designed not to allow this, in this case a work around, hack, tweak (again this is only for testing purposes) or direction of the proper method complying to the Android philosophy to implement this functionally will be welcomed.
Thank you very much.

A: Yes there is one UI component called droid Draw.


text:
Q: Automatically storing terraform AWS IAM access key output into paramstore or secrets Does Terraform have some native functionality to take aws_iam_access_key access key and secret access key output and place this in something like AWS paramstore or AWS secrets?
I'm looking to reduce any number of manual steps in the terraform creation of an AWS IAM user, so that the access and secret key are safely stored.
Reference:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_access_key

A: Yes, you just need to pass those values to a new SecretsManager Secret resource (just like you would do to create anything else in Terraform). If you want to store multiple values in a JSON Secret then you could use the jsonencode function.
resource "aws_iam_access_key" "lb" {
  user    = aws_iam_user.lb.name
  pgp_key = "keybase:some_person_that_exists"
}

resource "aws_secretsmanager_secret" "example" {
  name = "example"
}

resource "aws_secretsmanager_secret_version" "example" {
  secret_id     = aws_secretsmanager_secret.example.id
  secret_string = jsonencode({id: aws_iam_access_key.lb.id, key: aws_iam_access_key.lb.secret})
}


text:
Q: Azure Point-to-Site VPN - cannot connect to virtual machines in peered VNets I have the following in Azure:

*

*HubVNet with VPN Gateway (Point to Site VPN)

*Spoke01VNet with one virtual machine

*HubVNet and Spoke01VNet are peered with gateway transit enabled

*Spoke01VNet is allowing forwarded traffic from HubVNet

I connect to VPN Gateway from my workstation successfully.  I have a virtual machine on HubVNet (same as VPN Gateway) and I can successfully RDP to that server (I use it as a jumpbox right now) and can successfully RDP to server in Spoke01VNet from that jumpbox server.
I would like to RDP to server in Spoke01VNet from my workstation but cannot connect.  I thought by peering the VNets would allow this to happen when I connected via VPN but not so.  Can anyone provide me some assistance on how to do this, if it's possible with a Point-to-Site VPN?  Thank you in advance for all your help!!

A: You could check if you have correctly configured your Hub-spoke network topology in Azure. Read here for more details.

*

*Configure the peering connection in the hub to allow gateway transit.

*Configure the peering connection in each spoke to use remote gateways.

*Configure all peering connections to allow forwarded traffic.

Once the VNet peering is connected, you could re-download your VPN client package to re-connect the VPN connection on your local machine. This might make the update network effect.


text:
Q: Using function pointers to uniquely identify types I need to assign unique values to types for run-time equality comparison. Using function pointers as values does the job:
#include <cassert>

struct type_id {
  using value_type = void(*)();

  template<class T>
  static void get() { }
};

// some types
struct A {};
struct B {};

int main() {
    type_id::value_type a = &type_id::get<A>;
    type_id::value_type b = &type_id::get<B>;

    assert(a != b);

    return 0;
}

My question is the following: what are the restriction (if any) I should be aware of? I am especially curious about uniqueness across multiple translation units, and performance.


text:
Q: Background-images on my new project, switching between mac and pc home/at school I am creating a website for a school project, and I am using different background images on each site. I am also fairly new to html/css/Js. In school, I use my Macbook Pro, and at home, I use my windows desktop. My problem is this, when working at school, I download the images to my OneDrive folder, and insert them in my Visual Studio Code index.html with something like this:
/Users/edward/Library/CloudStorage/OneDrive-KristeligGymnasium/Kristelig Gymnasium VG2/Informasjonsteknologi 1/HTML/Datakomponenter - nettsideoppgave/Resources/Pictures/serverrom.jpeg
But on my windows desktop at home, the file path is different even though it is the same picture:
E:\Onedrive - Kristelig Gymnasium\Kristelig Gymnasium VG2\Informasjonsteknologi 1\HTML\Datakomponenter - nettsideoppgave\Resources\Pictures\motherboardbackground.jpeg
I don't even know if that is the problem itself, but for the explanation, when I run the website at home, the pictures don't work because windows don't understand the path, hence there is no background image. I want to be able to send my folder to my teacher so that he can see my full, and working website.
Thanks for the help :)
I don't really understand what to do differently, as I am new.
HTML
<!DOCTYPE html>
<html lang="no">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Datamaskiner og informasjonsteknologi | Nettsideoppgave</title>
    <link href="Resources/css/main.css" type="text/css" rel="stylesheet">
    <link href="Resources/css/sidemenu.css" type="text/css" rel="stylesheet">
    <script src="Resources/js/functions.js"></script>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Oswald&family=Raleway:wght@300&display=swap" rel="stylesheet">
</head>
    <body id="home">
    </body>
</html>

CSS
body {
    background-color:rgba(255, 255, 255, 0.3)
}

body#home {
    background: url("Resources\Pictures\motherboardbackground.jpeg") no-repeat center center fixed;
    background-size: cover;
    background-repeat: no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    overflow-y: auto;
    background-color: grey;
}

A: Beside the fact to use a local server as comments saying, there are 2 things in your questions.
First you are giving files full path from mac and windows. But seems your 2 full path don't refer same image.
At the end of first one:
serverrom.jpeg
At the end of second one:
motherboardbackground.jpeg
I don't think Windows change serverrom for motherboardbackground!
if you want to stay with your cloud, you can detect on which platform you are and add the right pre-url to the file name:
you have:
/Users/edward/Library/CloudStorage/OneDrive-KristeligGymnasium/Kristelig Gymnasium VG2/Informasjonsteknologi 1/HTML/Datakomponenter - nettsideoppgave/Resources/Pictures/serverrom.jpeg
and:
E:\Onedrive - Kristelig Gymnasium\Kristelig Gymnasium VG2\Informasjonsteknologi 1\HTML\Datakomponenter - nettsideoppgave\Resources\Pictures\motherboardbackground.jpeg
Beside the name in your example which I think is a mistake, the last part is same but you'll have to invert / to \ for windows:
/Kristelig Gymnasium VG2/Informasjonsteknologi 1/HTML/Datakomponenter - nettsideoppgave/Resources/Pictures/serverrom.jpeg
First part is platform dependent:
Mac: /Users/edward/Library/CloudStorage/OneDrive-KristeligGymnasium
Windows: E:\Onedrive - Kristelig Gymnasium
is same


text:
Q: How to force files saved to the system's Downloads folder to be stored on an external drive? I tried using symbolic links but they make me lose the default's Downloads icon which I don't want.
Is there a way I can just made files saved or downloaded to the system's Downloads folder be automatically moved and stored to an external drive?

A: You could do it with a Automator Folder Action workflow:

*

*Automator > New > Folder Action

*

*Set: Folder Action receives files and folders added to Choose folder to: Downloads

*Add the following Actions:

*Get Folders Contents

*

*[ ] Repeat for each subfolder found - Leave unchecked.

*Filter Finder Items

*

*Find files where:

*

*None of the following are true

*Name ends with .download

*

*This is to avoid moving a file Safari is currently downloading.

*Kind is folder

*

*This is to avoid moving just the contents of the folder.

*Kind is other alias

*Move Finder Items

*

*To: Downloads [ ] Replacing existing files

*

*Obviously in this instance Downloads is the one on the external drive.

*You can choose to check or not: Replacing existing files

*New Alias

*

*In: Downloads

*

*Obviously in this instance Downloads is the one in your Home folder.If you do not want an alias created for each moved file, then omit this action.

*Save the Automator Folder Action workflow, e.g.; Move to External Downloads
To stop and or remove a Folder Action: In Finder, you can select the target folder and right-click on it and select Folder Action Setup... from the Services menu section of the Context menu.


text:
Q: Capture incoming XML from API post in VB.net I'm trying to work out how to capture the XML POSTed to a VB.NET Rest API in VS 2019
I've created a new ASP.NET web application project, created it Empty but checked the 'Add folders & core references' Web API option.
After loading..
I added a new class library (VB)
I added an ADO.net entity data model to the class just created and connected it to my database procedure
I added a reference to my web api projects pointing it to the my new data access project
Finally i added a new 'WEB api2 controller - Empty' to the web api project
In the controller I see the following code
Namespace Controllers
    Public Class EmployeesController
        Inherits ApiController

        ' *what code goes in here?*

    End Class
End Namespace

My question is how do I read the incoming xml at this point?
I am using POSTMAN to post the following test XML, keeping it really simple
<stock>
    <stock_code>abc1234</stock_code>
</stock>

I can do it in C# and am able to process the XML Ok. I've been pulling my hair out with this but just cant fathom out how to do it in VB.NET, any help greatly appreciated.
Ok so, in C# I would be doing something like this:
namespace MyApp.Controllers
{

public class MyController : ApiController
{
    public string ReturnXmlDocument(HttpRequestMessage request)
    {
        var doc = new XmlDocument();
        doc.Load(request.Content.ReadAsStreamAsync().Result);

        String Mystr;
        Mystr = GetXMLAsString(doc);

do other stuff....
    }
}

A: Well who knew this website which converts C# code to VB existed?
https://converter.telerik.com/
I quick bit of cut & pasting and I now have my C# code is converted to VB which works a treat. the Vb code is below:
Public Class MyController
    Inherits ApiController

    Public Function ReturnXmlDocument(ByVal request As HttpRequestMessage) As String
        Dim doc = New XmlDocument()
        doc.Load(request.Content.ReadAsStreamAsync().Result)
        Dim Mystr As String
        Mystr = GetXMLAsString(doc)

        Do
            Dim stuff As other
        Loop While _
    End Function
End Class


text:
Q: Jquery UI Slider change value of slider when changed in input field

$("#storlekslider").slider({
  range: "max",
  min: 0,
  max: 1500,
  value: 0,
  slide: function(event, ui) {
    $("#storlek_testet").val(ui.value);
    $(ui.value).val($('#storlek_testet').val());
  }
});
// $( "#storlek_testet" ).val( $( "#storlekslider" ).slider( "value" ) );

$("#storlek_testet").change(function() {
  $("#storlekslider").slider("value", $(this).val());
});

<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css">

<input type="text" name="storlek" id="storlek_testet" value="500" />

Heres a js fiddle
im trying to get the slider to jump to the correct position when I change the value in the input field.
Iam using the Jquery UI slider.

A: $("#storlek_testet").keyup(function() {
    $("#storlekslider").slider("value" , $(this).val())
});

http://jsfiddle.net/C8X4D/

A: You attach to the change event of your input like so:
$("#storlek_testet").change(function() {
    $("#storlekslider").slider("value", $(this).val());
});

A: Change values from several inputs:
$("#input-1").change(function() {
    $("#slider").slider('values',0,$(this).val());
});
$("#input-2").change(function() {
    $("#slider").slider('values',1,$(this).val());
});

https://jsfiddle.net/brhuman/uvx6pdc1/


text:
Q: Flask application does not execute upon a submit button click on IE, Edge and Chrome (only on Firefox) I have a Flask application in Python that has a run() function in it. The HTML/CSS/JavaScript/JQuery website is rendered properly on all the browsers after I run the app, but my Python script is not executed upon a click of a submit button on any browser other than Firefox (I've tried Internet Explorer, Microsoft Edge and Google Chrome).

Parts of my code that I believe are relevant:

# app.py

from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap

from main.__main__ import main

app = Flask(__name__)
Bootstrap(app)

@app.route('/', methods=['GET', 'POST'])
def run():
    print('run function was run!!!')

    file = request.files.get('testers_csv_file')

    if file is None:
        return render_template('home.html')

    file.save('testers_file.csv')

    main('testers_file.csv')  # executes only on Firefox

    return render_template('success.html')

if __name__ == '__main__':
    app.secret_key = 'some secret key'
    app.config['SESSION_TYPE'] = 'filesystem'
    app.run(debug=True)

<!doctype html>

    <link rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.css"/>

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Web tool for assigning test cases to testers and updating trackSpace accordingly">
    <meta name="author" content="Jakub Bober">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
          crossorigin="anonymous">

    <title>My application</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

    <link href="static/styles/signin.css" rel="stylesheet">

    <form class="form-signin" id="form" method="post" action="/" enctype="multipart/form-data">
        Tester's details
        <input type="file" id="testers_csv_file" name="testers_csv_file" class="form-control" accept=".csv" required>

        <button class="btn btn-lg btn-primary btn-block" id="submitbtn" name="submitbtn" type="submit" value="submit">
            Assign tests
        </button>
    </form>

//signin.css

html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -webkit-box-align: center;
  -webkit-box-pack: center;
  justify-content: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  width: 100%;
  max-width: 460px;
  padding: 0px;
  margin: 0 auto;
}

.form-signin {
  font-weight: 400;
}

.form-signin .form-control {
  position: relative;
  left: 25%;
  width: 50%;
  height: auto;
  padding: 5px;
  font-size: 14px;
}

.form-signin .form-control:focus {
  z-index: 20;
}

#loading-img {
    background: url('loading3.gif') center center no-repeat;
    height: 100%;
    z-index: 20;
}

.overlay {
    background: #e9e9e9;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    opacity: 0.9;
}

success.html contains just a text that the app has run successfully.

As I said, when I launch app.py in any browser, I get the file field and submit button (and the gif image shows up when I click on it). But only on Firefox the main function executes and success.html shows up after main is executed, on other browsers nothing happens and the gif just stays forever.

The console message I get when I launch the app from Firefox:
run function was run!!!
127.0.0.1 - - [12/Sep/2019 12:33:06] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Sep/2019 12:33:06] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -
127.0.0.1 - - [12/Sep/2019 12:33:06] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -
127.0.0.1 - - [12/Sep/2019 12:33:07] "GET /static/styles/loading3.gif HTTP/1.1" 200 -

 and from Chrome:
run function was run!!!
127.0.0.1 - - [12/Sep/2019 12:34:19] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [12/Sep/2019 12:34:19] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -
127.0.0.1 - - [12/Sep/2019 12:34:19] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -

 So in Chrome less stuff gets rendered, but the app runs too.
BUT when I click on the submit button on Chrome, NOTHING IS PRINTED IN THE CONSOLE. Meanwhile on Firefox:
run function was run!!!
127.0.0.1 - - [12/Sep/2019 12:35:59] "POST / HTTP/1.1" 200 -
127.0.0.1 - - [12/Sep/2019 12:35:59] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -
127.0.0.1 - - [12/Sep/2019 12:35:59] "GET /jquery-validation-1.15.0/lib/jquery.js HTTP/1.1" 404 -

I THINK there is a problem with rendering the templates when the file is None in the app.py script and Firefox somehow deals with it better, but I don't know how to solve this issue. Do you have any ideas?


text:
Q: Can I wrap a List object without copying? I have a List<List<Object>>, but I don't want to always write that out wherever I use it, which also increases readability. So I wanted to wrap it in an object called ValueSheet.  This is what I've done, but it creates massive overhead, because it creates a copy of the List, which is not necessary:
public class ValueSheet extends ArrayList<List<Object>> {

    public ValueSheet(List<List<Object>> values) {
        super(values);
    }

}

would it be possible to do that without overhead while preserving the fact that this Object is a List<List<Object>>? This means that I am NOT looking for this:
public class ValueSheet {

    List<List<Object>> values;

    public ValueSheet(List<List<Object>> values) {
        this.values = values;
    }

}

PS: NO, I can not instantiate a ValueSheet directly, because the List<List<Object>> is provided from external sources.

A: ArrayList is not really designed for extension.
Its parent class, AbstractList is designed for extension,
and it may be suitable for your purpose. Here's a minimal example:
public class ValueSheet extends AbstractList<List<Object>> {

  private final List<List<Object>> values;

  ValueSheet(List<List<Object>> values) {
    this.values = values;
  }

  @Override
  public List<Object> get(int index) {
    return values.get(index);
  }

  @Override
  public int size() {
    return values.size();
  }
}

Note that calling methods that modify the list will throw UnsupportedOperationException.
If you need any of those methods,
you will need to override and implement them yourself.
(It could be as simple as delegating to the underlying list.)

A: Why do you have to create your ValueSheet with a copy constructor in the first place?
Try refactoring your code to work directly with ValueSheet, and simply never instantiate a List<List<Object>>.


text:
Q: Wordpress post categories Ajax URL structure I have a basic wordpress blog that has categories and when the categories are clicked the posts filter. This works great but I ideally want when the category is clicked the URL to change to
http://site.preview/resources/CATEGORYNAME

currently the blog loads as http://site.preview/resources/ and when a category is clicked it changes to http://site.preview/resources/#
Hope I explained this properly. Please find my code below.
Home.php - blog
<?php get_header('home'); ?>

        <img src="<?php echo get_stylesheet_directory_uri() . '/assets/images/blue-cover-with-illustrations.png' ?>">

The Good Air Resources Center

Knowledge to figure out indoor air quality. Tips to breathe cleaner air

        <?php
        $categories = get_categories(); ?>

Categories

                        <?php foreach ( $categories as $cat ) { ?>
                        <li id="cat-<?php echo $cat->term_id; ?>">
                            <a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#">
                                <?php echo $cat->name; ?>

                        <?php } ?>

                    <?php
                    $args = array(
                        'post_type' => 'post',
                        'orderby' => 'publish_date'
                    );
                    $post_query = new WP_Query($args);
                    if($post_query->have_posts() ) {
                    while($post_query->have_posts() ) {
                    $post_query->the_post();
                    ?>

                                    <?php the_post_thumbnail(); ?>

                                        <a href="<?php the_permalink(); ?>">
                                            <?php the_title(); ?>

                                    <?php the_excerpt(); ?>

                                    <a href="<?php the_permalink(); ?>" class="btn btn--brand btn--block">Read More >

                        <?php } } ?>

                <img src="<?php echo admin_url ( 'images/loading-publish.gif' ); ?>" />

<?php get_footer('home'); ?>

Functions.php
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
         $args = array (
        'cat' => $cat_id,
        'order' => 'DESC'

    );
    $posts = get_posts( $args );
            global $post;
    ob_start ();
    foreach ( $posts as $post ) {
    setup_postdata( $post ); ?>

            <?php the_post_thumbnail(); ?>

                <a href="<?php the_permalink(); ?>">
                    <?php the_title(); ?>

            <?php the_excerpt(); ?>

            <a href="<?php the_permalink(); ?>" class="btn btn--brand btn--block">Read More >

    <?php } wp_reset_postdata();
$response = ob_get_contents();
ob_end_clean();

echo $response;
die(1);
}

Thanks

A: You can use window.history.pushState function for this. in functions php inside ajax success part you can add that.
success: function (response) {
                jQuery(".posts .in").html(response);
                jQuery("#loading-animation").hide();
                window.history.pushState("category"+catID, "Category"+catID, "http://site.preview/resources/"+catID);
                return false;
            }

If it works for you, then you know how to change catID to category name in my given example.


text:
Q: Additional Scroll Bar Below the Header of JQuery Datatable I am using Datatables (Jquery).
Using the code i am getting a horizontal Scroll bar above my footer of the table as in the Link :
 "sScrollX": "100%",
 "sScrollXInner": "120%",
 "bScrollCollapse": true,

Now i want to get another Scroll Bar below the Header also.
Help me out.

A: Add the following code to the Datatable initialization:
"fnInitComplete": function(){

    // Enable THEAD scroll bars
    $('.dataTables_scrollHead').css('overflow', 'auto');

    // Sync THEAD scrolling with TBODY
    $('.dataTables_scrollHead').on('scroll', function () {
        $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
    });
},

Reference: DataTables plug-in - Display scrollbar below tfoot tag?
jsFiddle:  http://jsfiddle.net/3xvpznd3/

A: For this you have to add another container which has a fixed width like 1000px with overflow auto. And if the content overflows by 1000px then you will able to show the scroller in the container
Like:
CSS
.newcontainer{width:1000px;overflow:auto;}
HTML
<div class="newcontainer">
    <!-- Your div having the datatable-->
</div>

A: A slight update to the above code by Joseph:
When you add a Thead scroll bar and change its position on scroll event, it gets called thousands of times in a minute which will make your browser respond slowly resulting in a slow scrolling X horizontal bar. To avoid this add throttle like shown below which will basically make sure that the function is executed once in 100 milli seconds.
"fnInitComplete": function(){

                        // Enable THEAD scroll bars
                        $('.dataTables_scrollHead').css('overflow', 'auto');

                        // Sync THEAD scrolling with TBODY
                        $('.dataTables_scrollHead').on('scroll', $.throttle( 100,function () {
                            $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                        }));
                    }


text:
Q: What is the end result of Batch Job?
In the image below,what will be the result at the end of ON COMPLETE block?
Here https://docs.mulesoft.com/mule-user-guide/v/3.6/batch-processing, it is mentioned that gives both options, a BatchResultObject and also records of successful and unsuccessful logs. But i need to know that what should be the default result?

A: In the On Complete phase, Mule will always return a instance of BatchJobResult with JUST the statistics, not the records themselves. the following fields:
https://docs.mulesoft.com/mule-user-guide/v/3.7/batch-processing-reference#batchjobresult-processing-statistics
If you log it it will look something like this:
BatchJobInstanceId:09b38430-8474-11e4-9c5c-0a0027000000
          Number of TotalRecords: 0
          ProcessedRecords: 0
          Number of sucessfull Records: 0
          Number of failed Records: 0
          ElapsedTime in milliseconds: 0


text:
Q: While Loop Compare Got problem when using while loop, it says illegal starts of operation
   int monthInput;
        System.out.println("Prefered Month :  (1-12)");
        monthInput = promptUser.nextInt();
        while((monthInput <= 31) && (monthInput => 1)){
            monthInput = promptUser.nextInt();

        }
        Month dateMonth = Month.of(monthInput);
        System.out.println(dateMonth);

}

A: Change your monthInput => 1 condition to monthInput >= 1
int monthInput;
System.out.println("Prefered Month :  (1-12)");
monthInput = promptUser.nextInt();
while((monthInput <= 31) && (monthInput => 1)){
   monthInput = promptUser.nextInt();
}
 Month dateMonth = Month.of(monthInput);
 System.out.println(dateMonth);
}

A: In your loop condition, you wrote
monthInput => 1

This is wrong - there is no operator => in Java.
You probably meant
monthInput >= 1