text:
Q: How to remove newline in jquery? I have got the content of a div as a string (assume the string name is str ) using html() method. Div content is basically a table like this.

MMMK

So how can i remove newline of the string (str) if the new line found inside string \n Other string line	 that newline should not remove. Why i'm doing this ? because i need to get the content of the div and set to a text area. After set the text to textarea form submitted and place the textarea content to a page. Before place the textarea content to the page i use nl2br() method in PHP. So how can i do this?

A: /********************************************************************************/
// Replaces newlines on everything except what is in the given tags

function nl2br_excluding($string, $open, $close) {

    $substring = array();

    // Strip the backslashes so we have a clean representation of the tags.
    $open_tag = stripslashes($open);
    $close_tag = stripslashes($close);

    $count = preg_match_all("#$open(.*?)$close#si", $string, $matches);
    for($i = 0; $i < $count; $i++) {

        // Save the substring between the tags in a numbered array.
        $substring[$i] = $matches[1][$i];

        // Replace the substring within the tags with a number so we can replace it later.
        $match = $open_tag.$substring[$i].$close_tag;
        $replace = $open_tag.$i.$close_tag;

        $string = str_replace($match, $replace, $string);
    }

    $string = nl2br($string);

    // After replacing the newlines go back through our substring array and put them back
    // based on their key values.

    foreach($substring as $i => $value) {
        $match = $open_tag.$i.$close_tag;
        $replace = $open_tag.$value.$close_tag;
        $string = str_replace($match, $replace, $string);
    }

    return $string;
}

Then call
nl2br_excluding($string,"","	");

Source: http://hawkee.com/snippet/9705/


text:
Q: Unified Navigation System for JSF (menus, breadcrumbs, sitemap) We're using MyFaces, Richfaces & Restfaces to build a website on top of Oracle Stellant CMS. We're not using Site Studio. Are there any widgets/combination of widgets out there that could provide a unified navigation system? The site structure needs to be read from a DB table and CMS metadata fields, and we need a top tab menu, an expandable sidebar menu, breadcrumbs, and a sitemap (bonus points if it uses the sitemaps.org standard). We're currently using a combination of autonomous hand-rolled and off-the shelf widgets that aren't interoperating very well - the different navigation features aren't staying in sync as the site is navigated.

A: We faced a very similar issue last year and didn't find any set of widgets that could provide an integrated solution (we were using JSF, Facelets, RichFaces & Spring).
We ended up developing our own navigation system with menu state holders (stored per session) and the breadcrumbs would just go up in the menu tree from the current selection to construct itself.
The menu model itself was built once at application startup (read from an xml file) using Spring and bound to the view using facelets (
<rich:tabPanel id="topMenu" binding="#{menuBean.menu}" />
Keeping the components in sync was mainly managed by a Spring WebFlow FlowExecutionListener
Hope this helps..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sitecore WFFM Captcha Detection Thresholds not working First off, I'm running WFFM 2.3.0 rev.130118.
I have a form with a Captcha field. If I set the Captcha field to display all the time, everything works fine.  If the Captcha field is configured to display if certain Detection Thresholds are met, as far as I can tell, the Captcha is never displayed.
Here is a screenshot of the Detection Threshold dialog:

I say "as far as I can tell" because it may be a bit difficult to replicate "suspicious form activity" in your local dev environment. However, as you can see, I've set the visitor submission values to 3 times in 5 minutes.  If I then go and submit the form a number of times beyond that threshold, I'm never presented with a Captcha.
Beyond the Captcha field, it's a basic contact us form with 4 text fields, nothing fancy and WFFM is effectively a "stock" configuration.
Anyone have any ideas?

A: I found the problem, it had to do with the form and its fields having multiple language versions.
Essentially, the site supports multiple languages but I only added a en-US Captcha field and forgot to translate for each supported language.
Even though 3 out of 4 fields involved are shared(Field Link, Required & Parameters) and Title isn't even being utilized in this case, Sitecore assumes the context language and if you don't have a translated version of that field, the intended functionality never gets triggered.


text:
Q: bash: git pull works only if it is last command platform: Raspberry Pi 3 B
Please help me with this, git pull works only if it is last command, but I need it earlier. This is weird to me and I didn't find any solution

working
script.sh
#!/bin/bash
echo Hello World
git pull

sh script.sh gives:
Hello World
Already up-to-date.

not working
script.sh
#!/bin/bash
echo Hello World
git pull
echo Hello World

sh script.sh gives:
Hello World
' is not a git command. See 'git --help'.

Did you mean this?
    pull
Hello World

A: The file has the wrong EOL format (CRLF). CRLF is the format that comes from text files that are written on windows application. *NIX uses LF as EOL separator so your interpreter is getting a strange character (CR) as part of the content of every line and it's being passed onto git as part of the command you are calling... that's why it's breaking. Run dos2unix script.sh to convert it so that it can be read correctly.

A: There is no reason other than perhaps your script has un-closed quotes or special characters. In fact going by the error message, it is treating Hello World as a git command.
It is like you are saying:
[vturlapati:~] $ git Hello World
git: 'Hello' is not a git command. See 'git --help'.

The most similar command is
    reflog
[vturlapati:~] $ git 'Hello World'
git: 'Hello World' is not a git command. See 'git --help'.

Can you double check for special characters? If you are using vim, you could do that by executing :set list


text:
Q: What is the correct way of quoting named arguments in bash? In bash I can use named arguments like this:
command --argument=value

What is the correct way of quoting them if I need to include spaces?
command --argument="long value"
or
command "--argument=long value"

A:
What is the correct way of quoting them if I need to include spaces?

Any quoting that does the job - preserves the space that you want to preserve - is fine. Any of these run the same command:
echo cmd --argument="long value"
echo cmd "--argument=long value"
echo cmd --argument=long\ value
echo cmd --argument=long' 'value
echo cmd --argument=long" "value
echo cmd --argument=long" value"
echo cmd --argument=l'ong 'value
echo cmd '--argument=long value'
echo cmd '''--argument=long value'''   # same as above, with empty '' pairs
echo cmd '-'-'a'r'g'u'm'e'n't'='l'o'n'g v'a'l'u'e'  # just having fun

You can check if your quoting is fine with set -x and inspecting the output.
$ set -x
$ echo cmd --argument="long value"
+ echo cmd '--argument=long value'
$ echo cmd "--argument=long value"
+ echo cmd '--argument=long value'


text:
Q: Лицензирование дипломного проекта в университете, какую лицензию выбрать для исходного кода? Какую лицензию выбрать для исходных кодов дипломного проекта для того, чтобы университет не мог использовать его в коммерческих целях?
И является ли использование исходных кодов для обучения на коммерческой основе нарушением той же лицензии GNU GPL v3?

A:
является ли использование исходных кодов для обучения на коммерческой основе нарушением той же лицензии GNU GPL v3?

нет, не является.
стандартные общественные лицензии gnu, к которым относится и третья версия gnu gpl, не налагают никаких ограничений на цели использования программ, скомпилированных из исходников, распространяющихся под этими лицензиями. а уж про цели использования самих исходных текстов и речи нет. но, разумеется, при опубликовании этих исходных текстов должно быть и упоминание про лицензию, под которой они распространяются.

Какую лицензию выбрать для исходных кодов дипломного проекта для того что-бы университет не мог использовать его в коммерческих целях?

образцов подобных ограничивающих лицензий очень много.
из наиболее, пожалуй, известных — несколько лицензий из набора creative commons, в названии которых фигурирует NC (non-commercial).


text:
Q: Setting up Cron jobs for Laravel on Hostinger's hpanel I have a Laravel project that is already deployed on a live server using Hostinger's web service. I have a task scheduled to run every minute that will basically check if there are organizations that have already expired subscription dates, which will revert their subscription type back to "Free". I tried it first on my local machine and it works great.
However, when I tried to implement this task scheduling in Hostinger, it doesn't work.
I followed Laravel's official documentation for running a Scheduler on a live server. Since Hostinger doesn't allow special characters, I created a bash file containing the artisan run command with special characters following their article.
Here's the content of my created bash file:
/usr/bin/php /home/u482004401/domains/caviom.org/public_html/artisan && php artisan schedule:run > /dev/null 2>&1

app/Console/Kernel.php:
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {

        CharitableOrganization::whereDate('subscription_expires_at', '>=', now())
            ->update([
                'subscription' => 'Free',
                'subscribed_at' => null,
                'subscription_expires_at' => null
            ]);
    })->everyMinute();
}

When I try to view the output of my cron job in Hostinger, it just shows a generic message of a list of artisan commands.

I have test data on my database that should be updated with this Cron job, but it did not change at all. Has anyone successfully tried setting up cron jobs on Hostinger for a Laravel project?

A: Looks like I wrote the wrong syntax. I fixed it by replacing my bash file:
/usr/bin/php /home/u482004401/domains/caviom.org/public_html/artisan && php artisan schedule:run > /dev/null 2>&1

with
#!/bin/sh
/usr/bin/php /home/u482004401/domains/caviom.org/public_html/artisan schedule:run

Once I saw that the output is now what I expected, I then returned back the
/dev/null 2>&1


text:
Q: Compare two text inside elements I have the following html markup:

October 19th 2022

-

October 19th 2022

The page is a list of events divided in several containers (.container-1, .container-2, ...). When the end date (.end-date) of the event is equal to the start-date (.start-date) I want to hide the end date.
What I got so far:
(function($) {

  $(".start-date").attr("id", "startDate");
  var samedate = $("#startDate").text();
  $(".end-date:contains(' +++ samedate +++ ')").addClass("hide-date");
})(jQuery);

CSS:
.hide-date { display: none; }

A: As said in comment you had multiple quotes missing from your code, it needs to look like this:
$(".start-date").attr("id", "startDate");
var samedate = $('.container-1 #startDate').text();
$(".end-date:contains(" + samedate + ")").addClass("hide-date");

Also I'm not sure if there is a specific reason why you use this line $(".start-date").attr("id", "startDate"). If it's only so you can use the select on the next line, then you dont need it.
Demo

(function($) {

  $(".start-date").attr("id", "startDate");
  var samedate = $('.container-1 #startDate').text();
  $(".end-date:contains(" + samedate + ")").addClass("hide-date");
})(jQuery);
.hide-date {
  display: none;
}

October 19th 2022

-

October 19th 2022


text:
Q: rCharts HighCharts X-axs grouping Basically I would like to use scatter plot to show a person use how many hours to perform a task. So, the Y-axis is Time (hour) and X-axis is Day (irregular dataset). My question is, can I do X-axis category Day grouping so the data (Time) can be populated correctly?
Day   Time    Task
----------------------------
Mon    1.3      A
Mon    0.6      B
Tue    2.1      A
Wed    1.5      C
Fri    0.4      C
Sun    0.2      B

For now, i am able to plot the chart using code below. Assume 'dat' is the data frame for the sample above.
a <- hPlot(Time~ Day, data =dat,  group= 'Task' ,type = "scatter", title = "Data chart" )

The output for the code above able to group the X-axis for Day, but the Time data will not follow and not populating correctly. It will show Mon=1.3, Tue=0.6, Wed=2.1 etc...
Then i explore another approach by using direct passing the parameters to highchart with the code below through series.
   a$series(name = 'task plot', type = 'scatter', color= 'blue' ,data =??? )

This can plot the scatter plot as well using rcharts highchart, but i do not know how to handle the data=??? in R code so the highchart will get the data as below into highchart to ensure the X-axis grouping with Time data populated correctly. The x values is corresponding to categories array defined in axis as per how highchart work.
    xAxis: {
            categories: ['Mon','Tue','Wed','Thu']
        },
...
series: [{
                type: 'scatter',
                data: [
                    [0,1.3], // Mon 1.3
                    [0,0.6], // Mon 0.6
                    [1,2.1], // Tue 2.1
                    [2,1.5]  // Wed 1.5
    ...

A: This forum seems not really many active users. : )
I managed to solve my own problem after did some further study on the behavior of the rcharts and highcharts for both method above. Here is the approach for the benefits of everyone who interested to do the same thing.
If you study the behavior of highchart X-axis grouping, it will do grouping if you assign each X with a value instead of string. Therefore, for both method i have to first create a index grouping based on the Day which will serve as my X value for the plot. I use 'match' function to create a new column 'Index' as below corresponding to Day.
Day   Time    Task   Index
----------------------------
Mon    1.3      A      0
Mon    0.6      B      0
Tue    2.1      A      1
Wed    1.5      C      2
Fri    0.4      C      3
Sun    0.2      B      4

Method#1, in the hPlot approach, i have to use Index as my X value so the plot will do the X-axis grouping and the Y value (Time) will populate correctly.
a <- hPlot(Time~ Index, data =dat,  group= 'Task' ,type = "scatter", title = "Data chart" )

After the plot, you will observe the X-axis label by the Index value. Then, you can just re-label them with the code below. I have to use unique since the Day is a irregular dataset and have repeated day as you can see.
a$xAxis(categories=unique(dat$Day))

Method#2, by using the R to highcharts i have my own new learning (probably I am new). Instead of using a$series, i change it to use a$data which can take x and y value for data input to the plot.
 a$data(name = 'task plot', type = 'scatter', x=dat$Index, y=dat$Time )

And of course same as method#1, need to re-label the a$xAxis by using the unique Day.
Now, i have both methods can work for the plot that i wanted and it work perfectly fine.


text:
Q: Print an item in a list in a color based on the item I've written a script for a very clunky version of minesweeper.
The player selects the square they want to reveal based on co-ordinates (like in chess) and the board is updated with the values showing how many mines are in the squares around the chosen co-ordinates. The player can also flag where they think a mine is, which shows up as an "f".

Unfortunately this is unreadable which makes it very slow going. So I was hoping to update the code with some colour, where all "2"s are printed in blue, all "3"s in red etc. I have all the components; I've downloaded colorama but I can't get it to work. I'm stuck with the rest.
Code that prints the initial empty grid:
difficulty_dictionaries = {
    1 : {
        "difficulty": "Beginner",
        "x_axis": 8,
        "y_axis": 8,
        "mine_no": 10
    },
    2 : {
        "difficulty": "Intermediate",
        "x_axis": 16,
        "y_axis": 16,
        "mine_no": 40
    },
    3 : {
        "difficulty": "Expert",
        "x_axis": 26,
        "y_axis": 16,
        "mine_no": 98
    }
}

ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def set_difficulty():
    print ("Please select difficulty level by entering either 1, 2 or 3 based on the corresponding difficulty")
    diff_input = input ("1. Beginner: \n2. Intermediate: \n3. Expert: ")

    return difficulty_dictionaries[int(diff_input)]

def set_user_board():
    grid = []
    grid.append("  ")
    for set_x in range(diff_dict["x_axis"]):
        grid.append(ALPHABET[set_x])
    grid[0] = (" ".join(grid))

    del grid[1:]
    grid.append("  " + "+" + ("-+")*(diff_dict["x_axis"]))
    for set_y in range(diff_dict["y_axis"]):
        grid.append(str(set_y + 1) + " |" + (" " + "|")*diff_dict["x_axis"]) if set_y < 9 else grid.append(str(set_y + 1) + "|" + (" " + "|")*diff_dict["x_axis"])
        grid.append("  +" + ("-+")*diff_dict["x_axis"])
    return(grid)

def print_grid():
    print('\n'.join(' '.join(map(str, b)) for b in grid))
    return

diff_dict = set_difficulty()
grid = set_user_board()
print_grid()

Output:

As squares are selected, the values are taken from another reference list of lists and inserted into grid at the relevant point.
I stole the part of the code that prints the grid from another answer on SO but I don't know how it works. I have also tried this:
def print_grid():
    for x in grid:
        print(*x)
    return

which is far more understandable. But when I try to apply the colour to the items in the list I'm encountering some problems - mostly with the *.
def print_grid():
    for x in grid:
        print(f"{Fore.RED}" + x)

    return

That prints an all red grid - but it's squished:

A: First explanations:
You have 2D grid and x can means row with many values -
When you use print(*x) then it runs it as print(x[0], x[1], ...) so it prints many separated elements and print() automatically add space between elements. You could say that every comma , adds space in output.
Try print("A", "B") and you get "A B" instead of "AB"
When you print(f"{Fore.RED}" + x) then you print one string (probably row converted to string) and print() doesn't know that it needs spaces between elements. You have to format this string with spaces before using print()

It would be simpler to keep grid as 2D grid (without converting rows to string) and use nested for-loops `(with better names for variables)
for row in grid:
    for item in row:
        print(item, end=' ')
    print() # go to next line

And now you can use if/else to print it in different colors
for row in grid:
    for item in row:
        if item in ('+', '-', '|'):  # or `if item in "+-|"`
            color = Fore.RED
        elif item in ('1', '2', '3', '4', '5'): # or `if item in "12345"`
            color = Fore.GREEN
        else:
            color = Fore.WHITE
        print(f"{color}{item}", end=' ')   # I add `space` instead of `\n` as `end`
    print() # go to next line

Minimal working example:
from colorama import Fore, Back, Style

grid = [
    ['+', '-', '+', '-', '+', '-', '+'],
    ['|', '1', '|', ' ', '|', ' ', '|'],
    ['+', '-', '+', '-', '+', '-', '+'],
    ['|', 'X', '|', '2', '|', ' ', '|'],
    ['+', '-', '+', '-', '+', '-', '+'],
    ['|', ' ', '|', 'O', '|', '3', '|'],
    ['+', '-', '+', '-', '+', '-', '+'],
]

# ---

# letters

print(end='   ')
for item in 'ABC':
    print(f" {Fore.WHITE + Style.BRIGHT}{item} ", end=' ')
print()

# rows

for number, row in enumerate(grid, 1):

    # row's number

    if number % 2 == 1:
        print("  ", end='')
    else:
        print(f"{Fore.WHITE + Style.BRIGHT}{number//2} ", end='')

    # row's grid
    for item in row:
        if item in ('+', '-', '|'):  # or `if item in "+-|"`
            color = Fore.RED + Style.BRIGHT
        elif item in ('1', '2', '3', '4', '5'): # or `if item in "12345"`
            color = Fore.GREEN + Style.BRIGHT
        elif item in ('X', 'O'): # or `if item in "12345"`
            color = Fore.BLUE + Style.BRIGHT
        else:
            color = Fore.WHITE + Style.BRIGHT
        print(f"{color}{item}", end=' ')   # I add space at the end of `f-string`
    print() # go to next line

Result (with colors) in console:

EDIT:
I made more universal version which use grid without lines +-+
from colorama import Fore, Back, Style
import string

grid = [
    ['1', 'D', ' ', 'A', '4'],
    ['E', '2', '5', ' ', 'B'],
    ['6', 'F', '3', 'C', ' '],
]

# ---

HEIGTH = len(grid)
WIDTH  = len(grid[0])

LETTERS = string.ascii_uppercase[:WIDTH]

# --- columns letters ---

print(end='   ')
for item in LETTERS:
    print(f' {Fore.WHITE + Style.BRIGHT}{item}  ', end='')
print()

# --- rows ---

for number, row in enumerate(grid, 1):

    # top line

    print(f'{Fore.RED + Style.BRIGHT}  +' + ' - +'*WIDTH)

    # row with data

    # number
    print(f'{Fore.WHITE + Style.BRIGHT}{number} ', end='')

    # first left line
    print(f'{Fore.RED + Style.BRIGHT}| ', end='')

    # data with right line
    for item in row:
        if item in '123':
            color = Fore.GREEN + Style.BRIGHT
        elif item in '456':
            color = Fore.YELLOW + Style.BRIGHT
        elif item in 'ABCDEF': # or `if item in "12345"`
            color = Fore.BLUE + Style.BRIGHT
        else:
            color = Fore.WHITE + Style.BRIGHT

        print(f"{color}{item} {Fore.RED + Style.BRIGHT}| ", end='')   # I add space at the end of `f-string`

    print() # go to next line

# --- last (bottom) line ---

print(f'{Fore.RED + Style.BRIGHT}  +' + ' - +'*WIDTH)

Result (with colors) in console:


text:
Q: How to cut a part of a 3D object? I am noob with Blender.
I am here because I have some difficulty using the "project knife" tool in edit mode.
I have watched some tutorials about this, but no one helped me.
In "object mode" I select first the mesh model and with Shift+LMB the entire object, when I switch thought the edit mode and I select knife project, but I receive an error: "no other selected object found to use for projection".
Can anyone help me? Thanks in advance.

A: Knife Project requires two objects to work: a reference object, and the one you want the part cut out of. So, for example, if you want to cut a circular hole out of a cube, you would do the following:

*

*Create the cube mesh object

*Create a circle mesh object

*position the circle so that it's aligned with wherever you want the hole to be cut out of (i.e., if you want a hole cut out of the top of the cube, rotate and move the circle to the top of the cube)

*Select the circle, then shift+LMB select the cube

*Go to edit mode and click Edit > Knife Project

That's all! You should then be able to see the new vertices of the circle placed onto the cube. You can choose to remove the selected faces in your newly cut out hole, or not.
Are you sure you're selecting two separate mesh objects? That seems to be the error you're getting.


text:
Q: Python package installation issue : PyAudio and PortAudio I tried installing pyaudio from various source such as pip, conda, whl file, unofficial python, pyaudio.exe but none of them worked.
When I write:
conda install pyaudio

it says All requested packages already installed.
I went to lib of anaconda and there I found pyaudio.py but then also I cannot import it in my program.

A: Please install pyaudio using pipwin.
pip install pipwin
pipwin install pyaudio


text:
Q: Why is Let's Encrypt now failing to look up an A record from Pragmatometer.com? I have used Let's Encrypt successfully for two of my domains; but when I tried the same steps as https://antipaucity.com/2016/01/06/lets-encrypt-centos-6-truly-free-ssl/, it hangs and eventually throws the exception below. All domains in question are hosted on the same server, with administrative details like DNS being the same AFAIR.
When letsencrypt-auto --debug certonly crashed, here was the output:
Traceback (most recent call last):
  File "/home/cjsh/.local/share/letsencrypt/bin/letsencrypt", line 11, in
    sys.exit(main())
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/main.py", line 692, in main
    return config.func(config, plugins)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/main.py", line 509, in obtain_cert
    _, action = _auth_from_domains(le_client, config, domains, lineage)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/main.py", line 93, in _auth_from_domains
    lineage = le_client.obtain_and_enroll_certificate(domains)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/client.py", line 274, in obtain_and_enroll_certificate
    certr, chain, key, _ = self.obtain_certificate(domains)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/client.py", line 246, in obtain_certificate
    self.config.allow_subset_of_names)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/auth_handler.py", line 74, in get_authorizations
    self._respond(resp, best_effort)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/auth_handler.py", line 131, in _respond
    self._poll_challenges(chall_update, best_effort)
  File "/home/cjsh/.local/share/letsencrypt/local/lib/python2.7/site-packages/letsencrypt/auth_handler.py", line 195, in _poll_challenges
    raise errors.FailedChallenges(all_failed_achalls)
FailedChallenges: Failed authorization procedure. pragmatometer.com (tls-sni-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: DNS problem: query timed out looking up A for pragmatometer.com

IMPORTANT NOTES:
 - The following errors were reported by the server:

   Domain: pragmatometer.com
   Type:   connection
   Detail: DNS problem: query timed out looking up A for
   pragmatometer.com

   To fix these errors, please make sure that your domain name was
   entered correctly and the DNS A record(s) for that domain
   contain(s) the right IP address. Additionally, please check that
   your computer has a publicly routable IP address and that no
   firewalls are preventing the server from communicating with the
   client. If you're using the webroot plugin, you should also verify
   that you are serving files from the webroot path you provided.

A: My best guess is that there was an intermittent / short-lived DNS failure / timeout from the Let's Encrypt side (or maybe you happen to be on a slow connection).
Indeed, a quick check of the core error message ("query timed out looking up A for" site:letsencrypt.org) reveals some reports on the LE forum site like this one.
Try again in a little bit, and you should be golden.


text:
Q: Refresh NetSuite portlet on save/submit I have created a PortLet to create task in NetSuite. And new task getting create when an user press Submit button, but  portlet not geting refresh automatially. Every time user need to refreash portlet manully. Is there any way to refresh portlet on submit?
function formCreateTaskPL(portlet, column) {
var user = 257;
var entityid = 1985;
var trandate = nlapiDateToString(new Date());
var contact = 201;

portlet.setTitle('Quick Add Task');

var fld = portlet.addField('custpage_cust', 'text', 'Customet');
fld.setDefaultValue(entityid);

var fld = portlet.addField('custpage_user', 'text', 'User');
fld.setDefaultValue(user);

var fld = portlet.addField('custpage_date', 'date', 'Date');
fld.setDefaultValue(trandate);

var fld = portlet.addField('custpage_contact','text','Contact');
fld.setDefaultValue(contact);

var fld = portlet.addField('custpage_title', 'text', 'Title');
var fld = portlet.addField('custpage_text', 'longtext', 'Detail');

var url = nlapiResolveURL('SUITELET', 'customscript_create_task','customdeploy_create_task');

portlet.setSubmitButton(url, 'Submit');

}

A: try this
https://chrome.google.com/webstore/detail/netsuite-portlet-refreshe/odpaehonnmgmjkneccjjhgaoannpnghg
If you install this plugin ,Refreshes the portlets in your Netsuite Dashboard Automatically every time you login or access your netsuite Home Page.

A: What is the Suitelet returning? You might try changing the setSubmitButton target parameter to _parent and have the Suitelet redirect the page.

A: I wrote a Chrome extension for this purpose. You can set your own refresh interval. Unlike the other extension linked here, it doesn't refresh browser at all, just the portlets.
https://chrome.google.com/webstore/detail/freshportlet-for-netsuite/djphbeeppdbbljolikpmhcjbodaakanh


text:
Q: NextJS GetStaticProps and GetStaticPaths authentication I'm using NextJS and I have a doubt.
My app has an page like this
/supperter/[id]

where I have to be authenticated to render it.
I did all the auth part, and it works perfectly for every other page I have except this one because I don't have any chance to access the cookie that is setted up to access the backend.
export async function getStaticPaths() {
  const resProducts = await fetch(`${process.env.PRIVATE_ENDPOINT}/developers`, {
    headers: {
      Authorization: 'myToken', // I NEED TO ACCESS TO THE AUTH RIGHT HERE
    },
  });
  const assignments = await resProducts.json();
  const paths = assignments.data.map((p) => ({
    params: {
      id: p.id.toString(),
    },
  }));
  return {
    // this should be dynamic
    paths,
    fallback: true,
  };
}

is there any chance to achiieve this? I already know that this is serverside BUT I NEED IT.
thanks in advance.
PS: Next sometimes is so unuseful


text:
Q: Optimised path. I had been wondering while walking in corridors, me being lazy, what could be the shortest path between the two ends of the "L" shaped corridor.

Note: take the dimensions to be arbitrary.
Starting from any point from the 2cm line segment to any point in the 4cm line segment at the top.
Would going along the wall give the shortest path?
Or is there another path which is smaller than it?
This question has been solved please check out the sequel:
Optimised path 2.

A: Place the picture on a coordinate system with the lower left corner being the origin.
No matter which path we take, we have to go through a point of the form of $(4,t)$ where $t\in [0,2]$ from a point of the form of $(10,s)$ where $s\in [0,2]$, of which the distance is $\sqrt{(10-4)^2+(s-t)^2}\ge6$
The end point is $(p,9)$ where $p\in [0,4]$, to travel from  $(4,t)$ to $(p,9)$, the distance is $$\sqrt{(4-p)^2+(9-t)^2}\ge\sqrt{(4-4)^2+(9-2)^2}=7$$
Hence a lower bound of the distance is $13$. We just have to walk along the inner wall, this holds for general L shape.


text:
Q: How to update an uploaded file in Laravel 4 public function update($id)
    {
        $validation = MarketingMaterial::validator_edit(Input::all());

        if ($validation->fails()) {

            return Redirect::to('marketing_materials/'. $id . '/edit')->withErrors($validation);

        } else {

            $marketing_material                                  = MarketingMaterial::findOrFail($id);

            $old_title = $marketing_material->title;

            $marketing_material->title                           = Input::get('title');
            $marketing_material->description                     = Input::get('description');
            $marketing_material->marketing_materials_category_id = Input::get('marketing_materials_category_id');

            $thumb_path = Input::file('thumb_path');

            if (Input::hasFile('thumb_path'))
            {

                $file            = Input::file('thumb_path');
                $destinationPath = base_path().'/app/files/marketing_materials/'.$marketing_material->title.'/thumb_path/';
                $filename        = $file->getClientOriginalName();
                $extention       = $file->getClientOriginalExtension();
                $filesize        = $file->getSize();
                $uploadSuccess   = $file->move($destinationPath, $filename);

                $marketing_material->thumb_path = $filename;
            }

            $media_path = Input::file('media_path');

            if (Input::hasFile('media_path'))
            {

                $file            = Input::file('media_path');
                $destinationPath = base_path().'/app/files/marketing_materials/'.$marketing_material->title.'/media_path/';
                $filename        = $file->getClientOriginalName();
                $extention       = $file->getClientOriginalExtension();
                $filesize        = $file->getSize();
                $uploadSuccess   = $file->move($destinationPath, $filename);

                $marketing_material->media_path = $filename;
                $marketing_material->media_size = $filesize;
            }

            dd($old_title);

            $marketing_material->save();

            return Redirect::to('marketing_materials')
            ->with('success','The electronic marketing material was updated succesfully!');
        }
    }

Goal:
Able to edit an uploaded file (file that already uploaded).
Controller --> update function
As you can see, I rely my destination path, on my title, as soon as the user change the title, everything will be mess up.
I'm not sure how to go around that.
Question:
Can someone tell me how to get around this in Laravel 4 or point me to the right direction ?
Thanks.
Screenshots
My Form
Error

A:     public function update($id)
{
    $validator = CatalogDownload::edit_validator(Input::all());

    if ($validator->fails()) {
        return Redirect::to('catalog_downloads/'. $id . '/edit')
        ->withErrors($validator);

    }else {

        $catalog_download        = CatalogDownload::findOrFail($id);
        $catalog_download->title = Input::get('title');
        $catalog_download->note  = Input::get('note');

        $catalog_download->save();

        foreach (ExportType::all() as $export_type)
        {

            if (Input::hasFile('type_' . $export_type->id))
            {

                $success = File::deleteDirectory(base_path().'/app/files/product_export/'. $catalog_download->id.'/'. $export_type->id.'/'); // Answer

                $product_export  = new ProductExport;

                $zip             = Input::file('type_' . $export_type->id);
                $filename        = $zip->getClientOriginalName();
                $filesize        = $zip->getSize();

                $destinationPath = base_path().'/app/files/product_export/'. $catalog_download->id.'/'. $export_type->id.'/';
                $uploadSuccess   = $zip->move($destinationPath, 'Bioss 2015 Catalog.zip' );

                if  (!isset($uploadSuccess ))
                {
                    return Redirect::to('catalog_downloads/create')
                    ->with('error', 'Problem during upload')
                    ->withInput();
                }

                $product_export->file_path           =  'Bioss 2015 Catalog.zip';

                $product_export ->exported_date      = DateHelper::getDateFormatMySQL(Input::get('exported_date'));
                $product_export->catalog_download_id = $catalog_download->id;
                $product_export->export_type_id      = $export_type->id;

                $product_export->size                = $filesize;

                $product_export->save();
            }

        }

        return Redirect::to('catalog_downloads/')
        ->with('success','The catalog_download was updated successfully!');

    }
}

The Code above is the solution for it.
The magic happened in this line :
$success = File::deleteDirectory(base_path().'/app/files/product_export/'. $catalog_download->id.'/'. $export_type->id.'/');

Solution
I deleted old files, and then re-create new files.


text:
Q: How to know if the 7th radio button is selected without knowing name or id I have a product page that dynamically creates item options. I would like to know if the 7th option is selected, but I wont know the "name" or "id" of the radio button because they are generated automatically.

function teasamplecheck() {
 if(document.form1.radio1[7].checked == true) {
    alert("You have selected a sample");
}
    else {
        // DO NOTHING
        }
    }
}
});

<input type="radio" name="[oname]" id="radio-[value]" value="[value]" onClick="teasamplecheck();validateValues(document.add,1);updateprice();"  [selected]>
[feature]

So how to I look at this set of radio buttons and know that the 7th one is selected?

A: The use of the jQuery .eq() may be a way.
function teasamplecheck() {
    if( $(".radio-format input").eq(6).prop("checked") ) {
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

This is .eq(6) because the argument is zero-based.
So... This is the 7th input inside its parent radio-format...
If you have the whole radio-format div repeated many times... It would be :
function teasamplecheck() {
    if( $(".radio-format").eq(6).children("input").prop("checked") ) {
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

EDIT
See question in comments
To trigger the alert ONLY if the click has occured on the 7th radio, you have to change the condition:
function teasamplecheck(obj) {
    if (( obj.value == $(".radio-format input").eq(6).val() ) && ( obj.checked )){
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

OR (if the whole radio-format div is repeated) :
function teasamplecheck(obj) {
    if (( obj.value == $(".radio-format").eq(6).children("input").val() ) && ( obj.checked )){
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

It compares the value of the obj passed by the onclick handler:
onClick="teasamplecheck(this); ...


text:
Q: Is there a way to convert qcow2 images to ovf format? I have one qcow2 image. But, I need image in ovf format. I know there is already one answer here Any way to convert qcow2 to ovf?, but I don't have vCenter installed with me. So, i am looking for any linux utility or some other way to convert?

A: A ovf file is a desription file for your vm hardware. Number of CPUs, Memory, Disk Files, Network interfaces and no Disk Image.
It is the open form of a .vmx File.
You can't convert a disk image to a ovf.


text:
Q: interprocess communication using pipe I want to receive data from two microcontollers through USB and UART respectively and intergrate and synchronize the data (with a timestamp) in the main process.
Is it a good decision to use multiprocess instead of multithread? I want the processes to work fully in parallel.
For the interprocess communication, I decided to use Pipe (as it is said to be faster than Queue...)
import multiprocessing
from multiprocessing import Process,Pipe

def read_uart(uart_conn):
    while True:
        reading =uart.readline()
        uart_conn.send(reading)

def read_usb(usb_conn):
    while True:
    reading =usb.readline()
    usb_conn.send(reading)

if __name__ == '__main__':
    parent_usb_conn, usb_conn = Pipe()
    parent_uart_conn, uart_conn = Pipe()

    process_usb = multiprocessing.Process(target=read_usb, args=(usb_conn,),).start()
    process_uart = multiprocessing.Process(target=read_uart, args=(uart_conn,),).start()

    while True:
        if parent_uart_conn.poll():
            print(parent_uart_conn.recv())

        if parent_usb_conn.poll():
            print(parent_usb_conn.recv())

I want to receive the data from each process and print out in the main process as soon as the main process receives the data.
But my code above doesnt work as I expected.
How can I make the code better?
update
As the process_uart sends data more frequently than process_usb does,
it prints out only data from process_uart
so I changed code like :
while True:
    if parent_uart_conn.poll():
        print(parent_uart_conn.recv())

        if parent_usb_conn.poll():
            print(parent_usb_conn.recv())

It seems to work but I feel bad about the code...
I want to print out the data from each process as soon as they send the data to the main process.


text:
Q: What is the address of a null pointer? This is a quite basic question but I've been looking everywhere and couldn't find an answer.
Consider the following code:
myFunction(MyObject** obj) {...}

int main()
{
  MyObject *obj = NULL;
  myFunction(&obj);
}

What is the result of this?
Is &obj NULL? undefined? Does it segfault?

A: No, the &obj will not be NULL,
it will be the memory address holding the "value of obj", the pointer to MyObject.
It is as simple as
int x = 0;
int *ptrTox = &x;

In this case ptrTox will contain address of x, and not zero. It can be any valid address.

A: A pointer is simply a variable that stores an address (with a constraint on the type of what lies at this address).
So while it stores an address, it also has its own address in memory.
In your case, &obj is the address of this variable, and is neither NULL nor undefined, and accessing it won't segfault (if you avoid performing operations with obj that need to access what's pointed at, obviously). Indeed, the variable obj is declared and defined in your code.

A: Your myFunction() is getting the address of the obj (as passing &obj). You have created a pointer of MyObject class named obj. So It should not be null. Which hold address of memory of obj pointer.
Segfault is described here
What is a segmentation fault?


text:
Q: Xamarin.Forms persistent system clock I am struggling to find a way for my scheduling app to account for the user changing the system time. I appreciate that if the user changes the time zone I can see that, but if they make a change to the actual clock then it sends everything out.
To make it more awkward there might be several hours between use of my app in which the phone might be switched off, and it will have no connectivity for most of the time.
I was hoping there was a persistent clock that unaffected by the user changing the time, or that there was a way (in xamarin.forms) of catching an event or a message of the user changes the time.
Thanks in advance of your help
AJ

A: Android's Location, iOS CLLocation and Mac CLLocation includes the UTC of timefix (doesn't have to be GPS, just cell tower is enough). In theory user can operate rogue bluetooth GPS provider, fake software GPS provider with rooting or jailbreaking, but unless you can move the time collection & calculation logic to your own server instead of user's controlled device, relying on location provider would be the least effort.


text:
Q: How to create a multi-option Style Switcher using jQuery? I need to create a multi-option Style Switcher for my WordPress theme, but I can't get anything working (see code below). By multi-option I mean this: The user should be able to select a custom color, pattern and font independently of each other (a simple css link swap-out won't do). All this is far beyond my current skill level, can anyone help me in the right direction?
Basic Markup:
<!doctype html>

    <meta charset="utf-8">
    <title>Style Switcher</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/plugins.css">

The quick brown fox jumps over the lazy dog.

scripts.js (2nd attempt) Adapted from this theme.
// DOM READY, NO CONFLICT REMAP
jQuery(document).ready(function($){

    // THEME NAME
    var themeID='mytheme';

    // STYLE SWITCHER MARKUP
    $('body').append(
        '
'+
            '
'+
                '<select id="ssColor" name="ss-color">'+
                    '<option value="red">Red</option>'+
                    '<option value="green">Green</option>'+
                    '<option value="blue">Blue</option>'+
                '</select>'+
            '
'+
            '
'+
                '<select id="ssPattern" name="ss-pattern">'+
                    '<option value="pat-a">Pattern A</option>'+
                    '<option value="pat-b">Pattern B</option>'+
                    '<option value="pat-c">Pattern C</option>'+
                '</select>'+
            '
'+
            '
'+
                'Reset'+
            '
'+
        '
'
    );

    // RESET
    $('#ssReset').click(function(){
        var i=0;
        var cookies = new Array();
        $('#ss select').each(function(){
            var cookie = $(this).attr('name');
            cookies[i] = cookie;
            i++;
        });
    });

    // ???
    var cookiesMax=cookies.length;
    for(var i=0, max=cookiesMax; i<max; ++i){
        $.dough(themeID+'-'+cookies[i],'remove');
    }

    // APPLY CHANGES FUNCTION
    function applyChanges(id,selectName,selectValue){
        var cookieName=id+'-'+selectName;
        $.dough(cookieName,selectValue);
        location.reload();
    }

    // PROCESS
    $('#ss select').change(function(){
        var selectName = $(this).attr('name');
        var selectValue = $(this).val();
        applyChanges(themeID,selectName,selectValue);
    });

});

scripts.js (1st attempt) Adapted from this tutorial.
// DOM READY, NO CONFLICT REMAP
jQuery(document).ready(function($){

    // APPLY STYLES FUNCTION
    function apply_styles(bgcolor,bgpattern){
        $('html').css('backgroundColor','#'+bgcolor);
        $('html').css('backgroundImage','url(img/'+bgpattern+')');
    }

    // CREATE COOKIE FUNCTION
    function create_cookie(bgcolor,bgpattern){
        $.dough('bgcolor','remove');
        $.dough('bgcolor',bgcolor);
        $.dough('bgpattern','remove');
        $.dough('bgpattern',bgpattern);
    }

    // READ COOKIES ELSE DEFAULTS
    var cbgcolor=$.dough('bgcolor');
    var cbgpattern=$.dough('bgpattern');
    if(cbgcolor!=undefined&&cbgpattern!=undefined){
        apply_styles(cbgcolor,cbgpattern);
    }else{
        apply_styles('fff','default.gif');
    }

    // STYLE SWITCHER
    $('body').append(
        '
'+
            '

'+
            '
'+
                '

'+
                '

'+
                '

'+
            '
'+
            '
Save
'+
        '
'
    );

    // COLORPICKER
    $('#colorpicker_box').ColorPicker({
        onShow:function(colpkr){$(colpkr).fadeIn(500);return false;},
        onHide:function(colpkr){$(colpkr).fadeOut(500);return false;},
        onChange:function(hsb,hex,rgb){
            $('#colorpicker_box em').css({backgroundColor:'#'+hex});
        }
    });

    // PROCESS VALUES
    var pickerValue= // store 'hex' from COLORPICKER above, but how?
    var patternValue= // store rel="" value of CLICKED '#patterns li img'
    $('#save_css').click(function(){
        apply_styles(pickerValue,patternValue);
    });

});

A: You need to move your "PROCESS VALUES" bit into the onChange event in the colour picker, since the code is executed straight away otherwise and you want to act when the colour picked is KNOWN, then process that value.
$('#colorpicker_box').ColorPicker({
        onShow:function(colpkr){$(colpkr).fadeIn(500);return false;},
        onHide:function(colpkr){$(colpkr).fadeOut(500);return false;},
        onChange:function(hsb,hex,rgb){
            // PROCESS VALUES
            var patternValue= // store rel="" value of CLICKED '#patterns li img'
            $('#save_css').click(function(){
                apply_styles('#' + hex, patternValue);
            });

            $('#colorpicker_box em').css({backgroundColor:'#'+hex});
        }
    });

I'm not sure I get your comment "store rel="" value of CLICKED '#patterns li img" -- you've not even got a click event on any of the images, nor is there a rel value on them.

A: Ok here we go:

  <link class="css" href="red.css" />

<select>
 <option value="black">black</option>
 <option value="red">red</option>
</select>

Besides you have jquery theme switcher anyways why mess around ? lol


text:
Q: Update notification content of the existing notification present on Notification bar like Whatspp,Gmail,etc in Android When I observed the whats app and gmail notifications,they are automatically updates the existing notification of there app without creating new one.
So How I can achieve this?
I have created One notification like in above image.So

*

*When Notification create at that time There are four messages are there.

*So When I get Fifth message it should append content of existing notification like shown in image with Red color.
Please suggest me which methods are used in Gmail like app?
How I can achieve this?

A: My problem resolve with the below link
Update text of notification, not entire notification
Here is my code:-
        PendingIntent pendingIntent = PendingIntent.getBroadcast(objContext, (int) (Math.random() * 100), intent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationManager manager = (NotificationManager) objContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if (firstTime) {
            intCount++;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                inboxStyle = new Notification.InboxStyle();
            }
            Bitmap icon = BitmapFactory.decodeResource(objContext.getResources(), R.drawable.ic_launcher);
//            Notification.Builder builder = new Notification.Builder(objContext);
            builder = new Notification.Builder(objContext);
            builder.setAutoCancel(true);
            builder.setContentTitle("Studyboard");
            builder.setDefaults(Notification.DEFAULT_ALL);
            builder.setSmallIcon(R.drawable.ic_launcher_transparent_s);
            builder.setLargeIcon(icon);
            builder.setWhen(Calendar.getInstance().getTimeInMillis());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                builder.setStyle(inboxStyle);
            }
            builder.setOngoing(false);
            builder.setContentIntent(pendingIntent);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                builder.build();

                inboxStyle.addLine(senderFullName + " : " + strDisplayMsg);
                inboxStyle.setSummaryText("");
            }
            System.out.println("Creating New Notification");
            Notification myNotication = builder.getNotification();
            manager.notify("Example", 12345, myNotication);
            firstTime = false;

        } else {
            intCount++;
            builder.setWhen(Calendar.getInstance().getTimeInMillis());
            System.out.println("Not Creating");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                builder.setStyle(inboxStyle);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                if (intCount <= 3)
                    inboxStyle.addLine(senderFullName + " : " + strDisplayMsg);
                if (intCount > 3 && intCount - 3 > 0)
                    inboxStyle.setSummaryText("+" + (intCount - 3) + " more messages");
            }
            Notification myNotication = builder.getNotification();
            manager.notify("Example", 12345, myNotication);
        }

And For next execution Reset the flag and count in Broadcast Receiver which catch action for the Notification


text:
Q: Error with my project - The method 'collection' was called on null Good,
I have a problem with my application, since it generates an error when pressing the add to cart button, it generates an error and it is not added in firebase, I already checked that the variables have their name correctly, however I cannot find how solve this error, I appreciate all the help you can give me to solve this error!
void checkItemInCart(String shortInfoAsID, BuildContext context)
{
  EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsID)
      ? Fluttertoast.showToast(msg: "El artículo ya existe en el carrito")
      : addItemToCart(shortInfoAsID, context);
}

addItemToCart(String shortInfoAsID, BuildContext context) {
  List tempCartList = EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList);
  tempCartList.add(shortInfoAsID);

  EcommerceApp.firestore.collection(EcommerceApp.collectionUser)
    .document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID))
    .updateData({
      EcommerceApp.userCartList: tempCartList,
    }).then((v){
      Fluttertoast.showToast(msg: "Artículo añadido al carrito");

      EcommerceApp.sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);

      Provider.of<CartItemCounter>(context, listen: false).displayResult();
  });
}

The following NoSuchMethodError was thrown while handling a gesture:
The method 'collection' was called on null.
Receiver: null
Tried calling: collection("users")

When the exception was thrown, this was the stack:
0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
1      addItemToCart (package:e_shop/Store/storehome.dart:283:26)
2      checkItemInCart (package:e_shop/Store/storehome.dart:276:9)
3      sourceInfo.<anonymous closure> (package:e_shop/Store/storehome.dart:246:27)
4      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:993:19)
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#696c2
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(338.5, 338.3)
  finalLocalPosition: Offset(32.5, 27.8)
  button: 1
  sent tap down
====================================================================================================

A: Declare this:
List tempCartList = List<>();

Then do this :
  void checkItemInCart(String shortInfoAsID, BuildContext context)
        {
          EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsID)
              ? Fluttertoast.showToast(msg: "El artículo ya existe en el carrito")
              : addItemToCart(shortInfoAsID, context);
        }

        addItemToCart(String shortInfoAsID, BuildContext context) {
          tempCartList = EcommerceApp.sharedPreferences.getStringList(EcommerceApp.userCartList);
          tempCartList.add(shortInfoAsID);

          EcommerceApp.firestore.collection(EcommerceApp.collectionUser)
            .document(EcommerceApp.sharedPreferences.getString(EcommerceApp.userUID))
            .updateData({
              EcommerceApp.userCartList: tempCartList,
            }).then((v){
              Fluttertoast.showToast(msg: "Artículo añadido al carrito");

              EcommerceApp.sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);

              Provider.of<CartItemCounter>(context, listen: false).displayResult();
          });
        }


text:
Q: Запрос к бд - вбрать максимальную сумму Есть mysql таблица вида:
login | cena
--------------
user1 | 50
--------------
user1 | 50
--------------
user2 | 40

Нужно сложить все sum для каждого из логина и вывести из них сортировку по убыванию.
Должно получиться (из примера):
user1 100
user2 40

Имею код:
SELECT `table`.user AS user, SUM(`table`.cena) AS cena FROM `table` ORDER BY `table`.cena ASC;

Но он выводит общую сумму всех строк. Как ни крутил, ничего не выходит.
A: SELECT login, SUM(cena) AS sum_cena FROM `table` GROUP BY login ORDER BY cena ASC;


text:
Q: Make view NOT to update on change in array of objects I have seen a dozen of SO posts like THIS ONE where people claim that the view rendering array of objects using *ngFor directive is not updating if any object value changes.
I am trying to replicate the same scenario and then want to test out concepts like KeyValueDiffers and the not so efficient slice method to forcefully invoke change detection.
I know that we can do it by using trackBy in *ngFor directive or by setting ChangeDetectionStrategy to OnPush but these would be forcefully not invoking change detection.
Can I force this behavior just by having a complex data structure where I change a nested property and the view doesn't update
For DEMO, I have created a component having array of objects which is passed as Input() property to the child component as a whole and as individual items inside *ngFor. I have written a service which tries to updated a value inside the array and the view gets updated. I don't want that.


text:
Q: if $a\in acl(b)$, then there's $\varphi(x;b)\in tp_\mathcal{M}(a;b)$ algebraic and $\varphi(x;c)$ algebraic for all $c\in\mathcal{M}$. For given theory $T$ and $\mathcal{M}\models T$, if $a\in acl(b)$, then there's $\varphi(x;b)\in tp_\mathcal{M}(a;b)$ algebraic and $\varphi(x;c)$ algebraic for all $c\in\mathcal{M}$ in $\mathcal{M}$.
Corresponding definitions : ($A\subseteq\mathcal{M}\models T$ is given)
$\cdot$$acl(A)$:=$\{a\in\mathcal{M}\mid tp_{\mathcal{M}} (a/A) \text{ is algebraic}\}$
$\cdot$type $p$ in $\mathcal{M}$ is algebraic if it contains algebraic formulas
$\cdot$$\varphi(x)$ is algebraic in $\mathcal{M}$ if it has only finitely many realizations in $\mathcal{M}$.
I think $\varphi(x;b)$ isolating $tp(a/b)$ will be the right one but don't know how to deal with this. I can't relate $\varphi(x;b)$ to $\varphi(x;c)$

A: Isolating $\text{tp}(a/b)$ is not sufficient in general. For example, consider an equivalence relation $E$ with two classes: The first class $C_1$ has only two elements, $a$ and $b$. The second class $C_2$ has infinitely many elements. Let $\varphi(x,y)$ be the formula $(xEy)\land (x\neq y)$. Then $\varphi(x,b)$ is algebraic and isolates $\text{tp}(a/b)$. But if $c\in C_2$, the formula $\varphi(x,c)$ is not algebraic.
Going back to the general case, note that if $a\in \text{acl}(b)$ and $\varphi(x,b)$ isolates $\text{tp}(a/b)$, then there is some natural number $k$ such that $\varphi(x,b)$ has at most $k$ solutions. The problem is that $\varphi(x,y)$ might not be "strong enough" so that this upper bound is true of $\varphi(x,c)$ for all $c$.
To fix this, we can just beef up $\varphi(x,y)$ to assert this upper bound! Let $\varphi'(x,y)$ be the formula $$\varphi(x,y)\land (\exists^{\leq k} x\, \varphi(x,y)).$$
Now $\varphi'(x,b)\in \text{tp}(a/b)$, and for any $c$, either

*

*$\exists^{\leq k} \varphi(x,c)$ is true, in which case $\varphi(x,c)$ is algebraic, and hence $\varphi'(x,c)$ is algebraic, or

*$\exists^{\leq k} \varphi(x,c)$ is false, in which case $\varphi'(x,c)$ has no solutions, and hence is algebraic.
In the case of the equivalence relation example above, $\varphi'(x,a)$ defines $\{b\}$, $\varphi'(x,b)$ defines $\{a\}$, and $\varphi'(x,c)$ defines $\varnothing$ for all $c\in C_2$.


text:
Q: Slow Redshift COPY Performance into an Interleaved table We are seeing slow performance when using the COPY command into an interleaved table with 4 Sort Keys. When I remove the interleaved option, the copy finishes very quickly.
These are the stats to copy data from S3 to Redshift:
We loaded 70 million records
Interleaved sort key - 52 mins
Compound sort key - 8 mins
No Sort Key - 7mins
Our sort key had 4 columns in it. We have a DIST KEY also.
Can anyone provide a reasoning of why copy performance into an interleaved sort key performs poorly?

A: There was an automated backup which was running at the same time, which caused the COPY into the Interleaved table go slow..


text:
Q: cant hide div if value is empty How to hide all data in that code? It hide only 'field_value' in foreach, but didnt hide all over information. Where is the problem? I need to hide all info in div if there is no 'field_value'.
When I have value in 'field_value', for exmpl '24', i see this:"abc 24 info", but when there is no value, i see this:"abc info". when value is empty i dont need to see anything. (field_value is from field_id, maybe i need to write if empty field value from that field id? how to do it?)
<?php
if(!empty($v['field_value'])) {
?>

 abc

    <?php
    foreach($custom_fields as $v) {
        if($v['field_id'] == 22) echo $v['field_value'];
    }
    ?>

   info

<?php
}
?>

A: According to the php documentation for empty, a value is considered empty if it does not exist or it evaluates to false, check if this: $v['field_value'] is actually empty or not.
You said that you want to hide all the data : "if there is no 'field_value'" then i suggest you check out isset


text:
Q: IdentityServer4 Refresh Token Is Null I've been scratching my head on this problem for quite a few days already. I have a problem with IdentityServer4 where the token response does not contain a refresh token. The code I have already works fine regarding getting the access token - it's just the refresh token that I cannot seem to figure out.
In my project.json file, I have added the following entries:
"IdentityServer4": "1.0.0-rc3",
"IdentityServer4.AccessTokenValidation": "1.0.1-rc3"

My Startup.cs file contains the following:
public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddInMemoryClients(Config.Clients.Get())
        .AddInMemoryScopes(Config.Scopes.Get())
        .AddInMemoryUsers(Config.Users.Get())
        .AddTemporarySigningCredential();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseIdentityServer();
}

You may have noticed that I am using Config.Clients, Config.Scope, and Config.Users. Here is the code for those (Config.cs):
public class Config
{
    internal class Clients
    {
        public static IEnumerable<Client> Get()
        {
            return new List<Client> {
                new Client
                {
                    ClientId = "client",
                    ClientName = "Authentication Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    AccessTokenLifetime = 1800,
                    RefreshTokenExpiration = TokenExpiration.Absolute,
                    AbsoluteRefreshTokenLifetime = 1800,
                    ClientSecrets = new List<Secret> {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = new List<string>
                    {
                        "api",
                        StandardScopes.OfflineAccess.Name, //For refresh tokens

                    }
                }
            };
        }
    }

    internal class Scopes
    {
        public static IEnumerable<Scope> Get()
        {
            return new List<Scope>
            {
                StandardScopes.OfflineAccess, //For refresh tokens
                new Scope {
                    Name = "api",
                    DisplayName = "API",
                    Description = "API scope",
                    Type = ScopeType.Resource,
                    Claims = new List<ScopeClaim> {
                        new ScopeClaim(JwtClaimTypes.Role)
                    },
                    ScopeSecrets =  new List<Secret> {
                        new Secret("secret".Sha256())
                    }
                }
            };
        }
    }

    internal class Users
    {
        public static List<InMemoryUser> Get()
        {
            return new List<InMemoryUser>
            {
                new InMemoryUser {
                    Subject = "5BE86359-073C-434B-AD2D-A3932222DABE",
                    Username = "admin",
                    Password = "admin",
                    Claims = new List<Claim> {
                        new Claim(JwtClaimTypes.Role, "admin")
                    }
                }
            };
        }
    }
}

And I am calling this IdentityController.cs in order to get the Token:
[Route("api/[controller]")]
public class IdentityController : ControllerBase
{
    [HttpPost("GetToken")]
    public string GetToken()
    {
        DiscoveryResponse dr = new DiscoveryClient("http://localhost:5000").GetAsync().Result;
        TokenClient tokenClient = new TokenClient(dr.TokenEndpoint, "client", "secret", AuthenticationStyle.BasicAuthentication);
        TokenResponse tokenResponse = tokenClient.RequestClientCredentialsAsync("api").Result;

        return tokenResponse.AccessToken; //"tokenResponse" does not contain the refresh token!?
    }
}

I have read quite a few articles, but no where could I find a place where they focus on the Refresh Token alone. They all seem to focus just on basic code that returns the Access Token.
Can someone tell me what I am missing, and maybe show/point me in the right direction? Any help will be greatly appreciated!

A: You need to include the offline_access scope when requesting the token.
But the client credentials flow does not have support for refresh tokens - so this will not work.


text:
Q: PHP $_SESSION not working
Possible Duplicate:
PHP session seemingly not working

I'm currently coding my own CMS for fun but when I use $_SESSION, it doesn't work. The session isn't saved...
There's my code:
<?php
include('header.php');
if (isset($_SESSION['logged_in']))
{
    $link = 'profile.php';
    $link_name = 'Profile';
}
else
{
    $link = 'login.php';
    $link_name = 'Login';
}

if (isset($_POST['action']))
{
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    $password = md5($password);
    $user = mysql_query("SELECT * FROM users WHERE `username`='".$username."'");
    if (mysql_num_rows($user) == 1)
    {
            while ($userinfo = mysql_fetch_array($user))
            {
                    if ($userinfo['banned'] != true)
                    {
                            $_SESSION['user_id'] = $userinfo['id'];
                            $_SESSION['username'] = $userinfo['username'];
                            $_SESSION['logged_in'] = "true";
                            header('Location: index.php');
                    }
                    else
                    {
                            header('Location: login.php?error=banned');
                    }
            }
    }
    else if (mysql_num_rows($user) == 0)
    {
            header('Location: login.php?error=not-found');
    }
}
?>

In the code, I get the user information in my database then I check if the user isn't banned. If not, I set my $_SESSION[] and I redirect to the home...

A: you should call session_start() in the beginning of the script. make sure you call it on every page you need the access to session variables as well

A: You need session_start() at first.

A: Make sure session_start() is being called. Use Tamper Data to check the Headers for Sent and Received requests. Your looking for the Set-Cookie Header from the server and the Cookies Header from the client. This should contain your PHPSESSID. If you don't see this then your session is not started. Good Luck!


text:
Q: Vagrant and Docker not playing nice Update: I have uninstalled both Vagrant and Docker, and will accept any answer that helps me re-install both of them in such a way that:

*

*I can run Vagrant without any dependency on Docker whatsoever; and

*I can run Docker without any dependency on Vagrant whatsoever; and

*I can run Vagrant and use Docker as the backing provider

If you look at the Vagrant source code, you'll see that my error comes from this line of code, which, for VirtualBox providers, comes from this usable method raising an error. That usable method raises an error if it thinks that VirtualBox has an invalid version (VirtualBoxInvalidVersion) or if its not detected on the local system (VirtualBoxNotDetected).
Not being a Ruby dev, it's now getting difficult for me to figure out how Vagrant is deciding to throw either of those two errors. But I think I'm getting closer to figuring out why Docker is hosing my Vagrant/VirtualBox config.

Original question:
Mac here. A few days ago I installed Vagrant and VirtualBox like so:
brew cask install virtualbox
brew cask install vagrant
brew cask install vagrant-manager

...which got it Vagrant up and running no problem whatsoever. I was able to vagrant init hashicorp/precise32; vagrant up and everything looked like it was running perfect (hashicorp/precise32 uses VirtualBox by default).
Then last night I installed Docker, which also requires VirtualBox, and got it up and running with no problem whatsoever. I was even able to get the whalesay container examples working. So far so good.
Today I went to go play around in Vagrant, and it looks like my Docker install hosed my Vagrant/VirtualBox configuration.
Now, when I run vagrant init hashicorp/precise32 on an empty directory, and then run vagrant up, I get:
myuser@mymac:~/sandbox/myapp$vagrant up
No usable default provider could be found for your system.

Vagrant relies on interactions with 3rd party systems, known as
"providers", to provide Vagrant with resources to run development
environments. Examples are VirtualBox, VMware, Hyper-V.

The easiest solution to this message is to install VirtualBox, which
is available for free on all major platforms.

If you believe you already have a provider available, make sure it
is properly installed and configured. You can see more details about
why a particular provider isn't working by forcing usage with
`vagrant up --provider=PROVIDER`, which should give you a more specific
error message for that particular provider.

So then I tried specifying the provider type, even though I shouldn't have to, just to see what happens:
myuser@mymac:~/sandbox/myapp$vagrant up --provider=VirtualBox
The provider 'VirtualBox' could not be found, but was requested to
back the machine 'cortex'. Please use a provider that exists.

And just for good measure, running vagrant -v produces Vagrant 1.7.2 as output.
Any ideas what went awry and what the fix is?

A: Vagrant cares about case (at least Vagrant 1.8.1 does), so use lower case for the provider name:
vagrant up --provider=virtualbox

I think the 1.8.1 error message is much more helpful:
$ vagrant up --provider=VirtualBox  # NOTE: this is the WRONG capitalization
An active machine was found with a different provider. Vagrant
currently allows each machine to be brought up with only a single
provider at a time. A future version will remove this limitation.
Until then, please destroy the existing machine to up with a new
provider.

Machine name: default
Active provider: virtualbox
Requested provider: VirtualBox

You may also be able to set a default provider in your Vagrantfile.

A: I was having the same problem, and fixed it by updating Vagrant to the latest version (had 1.7.2, updated to 1.8.1).

A: I got this working, but have no idea what the actual solution was.

*

*Uninstall both Vagrant and Docker

*Reinstall Vagrant manually (not via brew/cask)

*Reinstall Docker from this link

*Use this Vagrantfile to confirm that your Vagrant-Docker-VirtualBox are all working together nicely

A: I was unable to reproduce the problem.  However, I read a bit of the source code from Vagrant's VirtualBox provider.  It sounds like it probably couldn't find VBoxManage in $PATH.  It should be located at /usr/bin/VBoxManage, even when installed via Homebrew.  Chances are your $PATH variable was incorrect, or VBoxManage was somewhere else.
Other readers who have the same problem should:

*

*Check /etc/paths to ensure that /usr/bin is listed, along with all the other directories typically found in $PATH.

*Look for a file named ~/.bashrc or ~/.bash_profile.  Mac OS X does not ship with either of those files by default, but some users add them to customize bash, and some programs may attempt to automatically edit/create them.  Be wary of any lines that look like export PATH=....  On OS X, changes to $PATH should be made in /etc/paths and /etc/paths.d/*, not in a bash script.

*Run type -a VBoxManage to see all the known locations of executables named VBoxManage.  There could be a stray binary somewhere that's taking precedence over the real binary.


text:
Q: What is the docker command to run my Django server? I'm trying to Dockerize my local Django/MySql setup.  I have this directory and file structure ...
apache
docker-compose.yml
web
    - manage.py
    - venv
    - requirements.txt
    - ...

Below is the docker-compose.yml file I'm using ...
version: '3'

services:
  web:
    restart: always
    build: ./web
    expose:
      - "8000"
    links:
      - mysql:mysql
    volumes:
      - web-django:/usr/src/app
      - web-static:/usr/src/app/static
    #env_file: web/venv
    environment:
      DEBUG: 'true'
    command: [ "python", "./web/manage.py runserver 0.0.0.0:8000" ]

  mysql:
    restart: always
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: 'maps_data'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'chicommons'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3406:3406"
    expose:
      # Opens port 3406 on the container
      - '3406'
    volumes:
      - my-db:/var/lib/mysql

volumes:
  web-django:
  web-static:
  my-db:

However when I run
docker-compose up

I get errors like the below
maps_web_1 exited with code 2
web_1    | python: can't open file './web/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory
maps_web_1 exited with code 2
maps_web_1 exited with code 2
web_1    | python: can't open file './web/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory
maps_web_1 exited with code 2

Is there another way I'm supposed to be referencing the manage.py file?
Edit: Added info requested in comments ...
FROM python:3.7-slim

RUN apt-get update && apt-get install

RUN apt-get install -y libmariadb-dev-compat libmariadb-dev
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc \
    && rm -rf /var/lib/apt/lists/*

RUN python -m pip install --upgrade pip

COPY requirements.txt requirements.txt
RUN python -m pip install -r requirements.txt

COPY . .

A: As others suggested, this is most probably because of running the manage.py runserver from a wrong directory or something very similar to this.
You are not using WORKDIR directive in your Dockerfile, at all. It is much safer if you do use them. Change your Dockerfile and docker-compose.yml files as below, and you problem should be solved.
Dockerfile
FROM python:3.7-slim

RUN apt-get update && apt-get install

RUN apt-get install -y libmariadb-dev-compat libmariadb-dev
RUN apt-get update \
    && apt-get install -y --no-install-recommends gcc \
    && rm -rf /var/lib/apt/lists/*

RUN python -m pip install --upgrade pip
RUN mkdir -p /app/

WORKDIR /app/

COPY requirements.txt requirements.txt
RUN python -m pip install -r requirements.txt

COPY . /app/

docker-compose.yml
version: '3'

services:
  web:
    restart: always
    build: ./web
    expose:
      - "8000"
    links:
      - mysql:mysql
    volumes:
      - web-django:/usr/src/app
      - web-static:/usr/src/app/static
    #env_file: web/venv
    environment:
      DEBUG: 'true'
    command: [ "python", "manage.py", "runserver", "0.0.0.0:8000" ]
...

Notice
You should be able to fix the problem by simply deleting web from your command for running the server. That's because when you are building the Dockerfile, you are inside the web directory. So when you do COPY . . you are copying contents inside web directory, and not the web directory itself. Actually, your file structure inside the docker image, should look something similar to this:
- root
- home
- var
- ...
- manage.py
- venv
- requirements.txt
- ...

A: In the command: directive, if you're using the array syntax, you're responsible for breaking up the command into words.  As you've shown it you're running the equivalent of python "manage.py runserver 0.0.0.0:8000" at the shell prompt, and it's dutifully considering the entire command and options as the filename of a script to be run, including spaces.  If you break this up into single words it will work better
command: ["python", "manage.py", "runserver", "0.0.0.0:8000"]

But there's not really a reason to specify this in docker-compose.yml at all.  This is the default command you'd want to run to launch the container no matter how you ran it, so it should be the default command in your image's Dockerfile
...
EXPOSE 8000
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

You don't need links: at all on modern Docker (Docker Compose automatically sets up inter-container networking for you).  You definitely don't want to mount named volumes over your application code: this hides what's in your image, and (since you've told Docker this is critical user data) it forces Docker to use an old version of your application if you try to update your image.
That leaves you with a simpler docker-compose.yml file:
version: '3'
services:
  web:
    restart: always
    build: ./web
    ports:           # to access the container from outside
      - "8000:8000"
    environment:
      DEBUG: 'true'

  mysql:
    restart: always
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: 'maps_data'
      MYSQL_USER: 'chicommons'
      MYSQL_PASSWORD: 'password'
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3406:3306"  # second port is always container-internal port
    volumes:
      - my-db:/var/lib/mysql

volumes:
  my-db:

A: Let us try to debug this error:
maps_web_1 exited with code 2
web_1    | python: can't open file './web/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory

Looks like either code is not not copied to container (named 'web') or command is triggered from root/home directory, where manage.py is not accessible.
1. Is the code available on container? How to check?
Usually, docker will just commands in container execute and exit unless there is unfinished running task (like server running in background).
To stop exiting and enable debugging it, let us add a running command, so that you can login to container and see if code is present.
command: tail -f /dev/null #trick to keep the docker alive for debug mode.
docker-compose.yml
  web:
    restart: always
    build: ./web
    expose:
      - "8000"
    links:
      - mysql:mysql
    volumes:
      - web-django:/usr/src/app
      - web-static:/usr/src/app/static
    #env_file: web/venv
    environment:
      DEBUG: 'true'
    command: tail -f /dev/null #trick to keep the docker alive for debug mode.

*Login to container 'web', from command line run docker exec -it web bash
Check if project files are present, now you can run python manage.py runserver 8000 command manually. If it works, then we can be sure of that the server can be run on container. Now, we can analyse initial working directory.

*If code is present, check why manage.py is not found? Is the working directory set? meaning, does the container know what is the base directory to run command?
Specify which is the working directory, in Dockerfile, before you copy the project files in to container.
Dockerfile in web directory
        ENV PYTHONUNBUFFERED 1
        ARG PROJ_DIR=/usr/project/web
        RUN mkdir -p $PROJ_DIR
        WORKDIR $PROJ_DIR
        COPY . $WORKDIR

docker-compose.yml
        restart: always
        build: ./web
        expose:
          - "8000"
        links:
          - mysql:mysql
        volumes:
          - web-django:/usr/src/app
          - web-static:/usr/src/app/static
        #env_file: web/venv
        environment:
          DEBUG: 'true'
        command: python manage.py runserver 0.0.0.0:8000 #note this command is triggered from $WORKDIR that we set in Dockerfile.

I think this should resolve the issue or help you to figure out the problem.


text:
Q: searchview for multicolum listview I am using a ListViewAdapter which extends ArrayAdapter to display results in ListView. I have 3 TextView in the ListView to display the output. I want to implement a searchview but when I type in search bar the screen goes blank. How do I implement it? I tried with addTextChangedListener using EditText also but no output.This is Activity
 searchView = (SearchView)findViewById(R.id.searchView);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });

}

private void loadDescriptionList() {
    final ProgressDialog progressDialog = new ProgressDialog(TestDetails.this);
    progressDialog.setMessage("Loading Data...");
    progressDialog.show();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response)
                {
                    progressDialog.dismiss();

                    try {
                        JSONObject obj = new JSONObject(response);
                        JSONArray heroArray = obj.getJSONArray("list");

                        for (int i = 0; i < heroArray.length(); i++) {
                            JSONObject heroObject = heroArray.getJSONObject(i);
                            TDescription hero = new TDescription(heroObject.getString("test_code"), heroObject.getString("test_description"),heroObject.getString("test_price"));
                            heroList.add(hero);
                        }
                         adapter = new ListViewAdapter(heroList, getApplicationContext());
                        listView.setAdapter(adapter);
                    } catch (JSONException e) {
                        progressDialog.dismiss();
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.dismiss();
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

LISTVIEWADAPTER.JAVA
public class ListViewAdapter extends ArrayAdapter<TDescription> {
private List<TDescription> heroList;
private Context mCtx;
Typeface typeface;
TextView rup;
public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
    super(mCtx, R.layout.list_items, heroList);
    this.heroList = heroList;
    this.mCtx = mCtx;
    typeface = Typeface.createFromAsset(mCtx.getAssets(), "fontawesome-webfont.ttf");
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View listViewItem = inflater.inflate(R.layout.list_items, null, true);

    TextView code = (TextView)listViewItem.findViewById(R.id.code);
    TextView desc = (TextView)listViewItem.findViewById(R.id.desc);
    TextView price = (TextView)listViewItem.findViewById(R.id.price);
    rup = (TextView)listViewItem.findViewById(R.id.rupee);
    rup.setTypeface(typeface);
    TDescription hero = heroList.get(position);
    code.setText(hero.getCode());
    desc.setText(hero.getDesc());
    price.setText(hero.getPrice());
    return listViewItem;
}

}
enter image [description]1 here

A: You have to implement filterable interface to get your result just change your listview adapter class to below code
public class ListViewAdapter extends ArrayAdapter<TDescription> implements Filterable {
private List<TDescription> heroList;
private List<TDescription> mFilterData;
private Context mCtx;
private ItemFilter mFilter = new ItemFilter();
private TextView rup;

public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
    super(mCtx, R.layout.list_items, heroList);
    this.heroList = heroList;
    this.mFilterData = heroList;
    this.mCtx = mCtx;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(mCtx);
    View listViewItem = inflater.inflate(R.layout.list_items, null, true);

    TextView code = (TextView) listViewItem.findViewById(R.id.code);
    TextView desc = (TextView) listViewItem.findViewById(R.id.desc);
    TextView price = (TextView) listViewItem.findViewById(R.id.price);
    rup = (TextView) listViewItem.findViewById(R.id.rupee);
    TDescription hero = mFilterData.get(position);
    code.setText(hero.getCode());
    desc.setText(hero.getDesc());
    price.setText(hero.getPrice());
    return listViewItem;
}

public int getCount() {
    return mFilterData.size();
}

public TDescription getItem(int position) {
    return mFilterData.get(position);
}

public long getItemId(int position) {
    return position;
}

@NonNull
public Filter getFilter() {
    return mFilter;
}

private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        String userString = constraint.toString().toLowerCase();

        FilterResults filterResults = new FilterResults();

        final List<TDescription> originalList = heroList;

        int count = originalList.size();
        final ArrayList<TDescription> resultList = new ArrayList<>(count);

        TDescription tDescription;

        for (int i = 0; i < count; i++) {
            tDescription = originalList.get(i);
            if (tDescription.getDesc().toLowerCase().contains(userString)) {
                resultList.add(tDescription);
            }
        }

        filterResults.values = resultList;
        filterResults.count = resultList.size();

        return filterResults;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        mFilterData = (ArrayList<TDescription>) results.values;
        notifyDataSetChanged();
    }

}

}

it will filter the data based on your description


text:
Q: Bottom Navigation Bar not showing icons or text I'm having a little bit of trouble trying to implement a Bottom Navigation Bar with icons and text in my Android application.
The bar currently functions as expected and takes you to the desired fragment but isn't showing icons or text for some reason.
I've done a few searches but haven't been able to find a solution or a reason as to why it is behaving this way.Any help would be appreciated. Thanks.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:itemBackground="@color/turquoise"
        android:foreground="@color/colorPrimary"
        app:itemIconTint="@android:color/white"
        app:itemTextColor="@android:color/white"
        app:menu="@menu/navigation" />

</android.support.design.widget.CoordinatorLayout>

navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/nav_0"
        android:icon="@drawable/ic_launcher_foreground"
        android:title="home"
        app:showAsAction="ifRoom|withText"/>

    <item
        android:id="@+id/nav_1"
        android:icon="@drawable/ic_launcher_foreground"
        android:title="email"
        app:showAsAction="ifRoom|withText"/>

    <item
        android:id="@+id/nav_2"
        android:icon="@drawable/ic_home"
        android:title="profile"
        app:showAsAction="ifRoom|withText"/>

    <item
        android:id="@+id/nav_3"
        android:icon="@drawable/ic_home"
        android:title="map"
        app:showAsAction="ifRoom|withText"/>

</menu>

in MainActivity.java
 toolbar = getSupportActionBar();

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

A: Remove android:foreground="@color/colorPrimary" attribute inside your BottomNavigationView


text:
Q: Can't get the configuration file from Google when integrating google sign-in into Android Application I am following the following article:
https://developers.google.com/identity/sign-in/android/start-integrating
They have an option there to "Get Configuration File" by just entering your cloud-platform app name and your android app's package.  However, when I do this, I get text-box saying:

"To use Google Sign-In, you'll need to provide the SHA1 of your
  signing certificate so we can create an OAuth2 client and API key for
  your app."

The button to "Enable Google-Sign In" is disabled, and there's no place to enter a SHA1 key manually....I had done this previously, and if i remember, this page would automatically find by SHA1 key once I entered the necessary info.
I have double checked that my cloud platform application has a client-id for android application defined and I double-checked the package names as well.

A: Go into Google Developer Console and agree to new Terms of Service. It'll will work after that


text:
Q: How to print a string formatted properly I am doing Test Driven Development.So I created a case that needs to send an array of strings to the function.That function will check if the array has any uppercase letter strings.If there is then it needs to print all the strings as "name , name, name and name are amazing".So before the last one it should be putting an "and".
It is sometimes giving me dead code error because there are other cases that might be interfering with the execution of this case.
Test Case
@Test
    void testAcceptsAJumbleOfUpperCaseAndLowerCase() {
            theAmazingPeter obj = new theAmazingPeter();
            String[] arr = {"Peter","GUNEET"};
            String result = obj.AmazingPerson(arr);
            assertEquals("Peter, and GUNEET are amazing",result);
        }
    }

Statement
else {
    for (int i = 0; i < names.length; i++) {
        if (names.length >= 1 && names[i].equals(names[i].toUpperCase())) {
            if (i > 0) {
                sb.append(", ");
                if (i == names.length - 1) {
                    sb.append("and ");
                }
            }
            sb.append(names[i]);
        }
        System.out.println(sb.toString() + " are amazing");
    }
    String result = sb.toString() + " are amazing";
    return result;
}

A: If it is needed to check if the string contains capital letter, it will need to be implemented as following:
    StringBuffer sb = new StringBuffer();
    char ch;

    for (int i = 0; i < names.length; i++) {
        if (Character.isUpperCase(names[i].charAt(0))) {
            if (i == names.length - 1) {
                sb.append(" and " + names[i]);
            } else if (i == names.length - 2) {
                sb.append(names[i]);
            } else {
                sb.append(names[i] + ", ");
            }
        }
    }
    System.out.println(sb.toString() + " are amazing");
    String result = sb.toString() + " are amazing";
    return result;

A: This line in your code is wrong:
if(names.length >= 1 && names[i].equals(names[i].toUpperCase()))

This if statement comes true only when all the letters of string are capital letters.
For example: if names[i] contains "Peter" then names[i].toUpperCase() equals "PETER" and the expression will return false. But what you want is accepting this string because it contains capital letter.
Instead doing this, you can use Character.isUpperCase(char) method.
public boolean containsUpper(String s){
      for (int i = 0 ; i< s.length(); i++){
          if(Character.isUpperCase(s.charAt(i)))
             return true;
      }
      return false;
}

You may call this function for every string then continue.


text:
Q: Dask how to avoid recomputing things Using dask I have defined a long pipeline of computations; at some point given constraints in apis and version I need to compute some small result (not lazy) and feed it in the lazy operations. My problem is that at this point the whole computation graph will be executed so that I can produce an intermediate results. Is there a way to not loose the work done at this point and have to recompute everything from scratch when in a following step I am storing the final results to disk?
Is using persist supposed to help with that?
Any help will be very appreciated.

A: Yes, this is the usecase that persist is for. The trick is figuring out where to apply it - this decision is usually influenced by:

*

*The size of your intermediate results. These will be kept in memory until all references to them are deleted (e.g. foo in foo = intermediate.persist()).

*The shape of your graph. It's better to persist only components that would need to be recomputed, to minimize the memory impact of the persisted values. You can use .visualize() to look at the graph.

*The time it takes to compute the tasks. If the tasks are quick to compute, then it may be more beneficial just to recompute them rather than keep them around in memory.


text:
Q: How to get the same result as modifying /etc/hosts file, without root access? The question is simple: no root access, but need to point particular domain name to the specified IP address.
What are the other ways to do the same thing as with adding the record to /etc/hosts file?
UPDATE:
Clarification:
My domain had been expired, but I still want to gain the access to it from corporate network (no root privileges on my linux workstation) by it's domain name for: http, https, imaps, smtps, ftp, and couple of specific ports.

A: You could LD_PRELOAD in your own versions of gethostby{addr,name..}
which read /etc/hosts and then the users own hosts file in their homedirectory.

A: The server is using a nameserver right ? (cat /etc/resolv.conf) so you could, if you have access, configure it to return a specific IP address for a particular domain.


text:
Q: Error while trying to access phone camera with opencv python I expected to receive a video feed in my laptop from my phone. In my opinion, the code is correct. The same code is running on other devices. But when I tried doing the same in my laptop, it displayed the following error:
[ERROR:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap.cpp (142) cv::VideoCapture::open VIDEOIO(CV_IMAGES): raised OpenCV exception:

OpenCV(4.5.1) C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-wvn_it83\opencv\modules\videoio\src\cap_images.cpp:253: error: (-5:Bad argument) CAP_IMAGES: can't find starting number (in the name of file): http://192.168.1.3:8080/video in function 'cv::icvExtractPattern'

Since I am a newbie to the world of opencv, I could'nt understand what caused the error. Hence, I did'nt try anything worthwhile other than changing a few lines of code.
My code is:
import cv2
url= 'http://192.168.1.3:8080/video'
cap=cv2.VideoCapture(url)
cap.set(3,240)
cap.set(4,240)
while(True):
   ret,frame=cap.read()
   if frame is not None:
    cv2.imshow('frame',frame)
   q=cv2.waitKey(1)
   if q==ord("q"):
    break
cv2.destroyAllWindows()
cap.release()

A: I had encountered the same issue but with a a saved video file as the input.
The file path I had entered did no exist and I got the same error.
I would suggest to check if your have given the right permissions to for accessing your phone's camera and if the feed is live and is returning images in the correct format.


text:
Q: Is it possible to directly test whether of not the vacuum gravitates? According to GR, all sources of stress-energy (e.g. everything on the $T_{\mu\nu}$ side of the EFE) should gravitate (e.g. affect the curvature/$G_{\mu\nu}$ side of the EFE). We observe the expansion of the universe, which (for now) fits the expected expansion of a small cosmological constant. However, that does not mean that the expansion is due to a cosmological constant (the expansion may be a slowly moving scalar field, for ex., or something else). Also GR (while well tested) may be a limit of a more fundamental theory. Particle physics expects the cosmological constant to be much greater than what is observed in cosmology.
How would we go about testing whether or not the vacuum itself gravitates? The only way I can think of is something involving combining an Eot-Wash experiment with a casimir force measurement.
p.s. The casimir force itself (as I understand) might not even be probing the vacuum.....there was a paper i saw a year ago explaining the casimir effect as the result of a van der waals force between the plates or something like that (i'd have to dig to find it if anyone is curious).

A:
How would we go about testing whether or not the vacuum itself gravitates?

Do we need to? General relativity is one of the best-tested theories we've got, see Clifford M Will's paper at http://arxiv.org/abs/1403.7377. And in the Foundation of The General Theory of Relativity Einstein did say this: "the energy of the gravitational field shall act gravitatively in the same way as any other kind of energy". The space around a star is vacuum, and it itself gravitates.
One could argue that flat galactic rotation curves and gravitational lensing in the bullet cluster are direct tests of this. It's not as if anybody has actually detected any WIMPs. Let's not forget that we don't know of any breaches of conservation of energy, and that the raisin-cake analogy tells us that space expands between the galaxies but not within. That ought to suggest that vacuum energy density is now greater where the galaxies are. And we ought to expect it to act gravitatively in the same way as any other kind of energy. Space is dark, it has its vacuum energy, and this has a mass-equivalence.
As for the cosmological constant, there's plenty of references where it's described as a negative pressure. A negative pressure is a tension. And where have we seen that before? In the balloon analogy:

Image courtesy of the one-minute astronomer.
If you have a balloon in a vacuum, the pressure of the air inside is balanced by the tension in the skin, and there's two ways to make it expand. One way is to blow more air into the balloon. However energy = pressure x volume so this in breach of conservation of energy. But there is another way that isn't: make the skin weaker.