text:
Q: Oracle SQL -- how to delete partial duplicates with a preference Could you please help me in deleting duplicates (partial) from table? I have a table containing 5 columns. And in this table I have duplicates -- but only 4 columns are the same and one of the columns (field5) is different. That is:
F1 F2 F3 F4 F5
A1 A2 A3 A4 103
A1 A2 A3 A4 3

So, for a duplicate, 4 columns/fields are the same, except the 5th one. And I want to delete the row containing number "103", that's, a higher number. How can I achieve this?
If this was a normal duplicate, I would just use max(rowid) and remove that row. But now this could delete the row containing lower number instead of the higher number.
One method that I can think of is creating a new table containing rows which are duplicate and Field5 has a higher number from this table. Then deleting rows from original table by comparing it to this new table. But that seems not so good solution to me -- especially if the original table is big, this might take long time.
Any help would be much appreciated. Thank you.

A: Idea is to keep a record for each combinations of F1,F2,F3,F4 and delete the rest.
Try this:
    DELETE FROM TABLE_NAME WHERE ROWID IN
    (SELECT ROWID FROM
        (SELECT ROWID, row_number() OVER(PARTITION BY F1,F2,F3,F4 ORDER BY F5) RN
           FROM TABLE_NAME)
    WHERE RN<>1);

A: How about this?
SQL> select * from test order by f1, f5;

F1 F2 F3 F4         F5
-- -- -- -- ----------
a1 a2 a3 a4          3
a1 a2 a3 a4         50  --> delete
a1 a2 a3 a4        103  --> delete
b1 b2 b3 b4          2
b1 b2 b3 b4        200  --> delete
c1 c2 c3 c4          1

6 rows selected.

SQL> delete from test t
  2        where rowid not in (select rowid
  3                              from test t1
  4                             where     t1.f1 = t.f1
  5                                   and t1.f2 = t.f2
  6                                   and t1.f3 = t.f3
  7                                   and t1.f4 = t.f4
  8                                   and t1.f5 =
  9                                          (select min (t2.f5)
 10                                             from test t2
 11                                            where     t2.f1 = t.f1
 12                                                  and t2.f2 = t.f2
 13                                                  and t2.f3 = t.f3
 14                                                  and t2.f4 = t.f4));

3 rows deleted.

SQL> select * from test order by f1, f5;

F1 F2 F3 F4         F5
-- -- -- -- ----------
a1 a2 a3 a4          3
b1 b2 b3 b4          2
c1 c2 c3 c4          1

SQL>

A: I normally just do this:
delete demo
where  rowid in
       ( select lead(rowid) over (partition by f1, f2, f3, f4 order by f5) as next_rowid
         from   demo );

That is, delete every "next" row in order of f5 within its (f1, f2, f3, f4) group.


text:
Q: yad notification in Gnome Shell 3 yad notifications (https://sourceforge.net/p/yad-dialog/wiki/NotificationIcon/) like in this example are not displayed:
yad --notification --image="gtk-help" --command="echo 'Hello World'" --text="The notification's tooltip"

I guess it has to do with gnome shell. How can I show the yad notification?
GNOME Shell 3.34.1 Ubuntu 19.10
I used gnome tweaks to enable Ubuntu Appindicators to no effect.

A: The classical "system tray" where any application could create an icon has been deprecated in various desktops since 2010. See https://ubuntu.com/blog/notification-area. A more standard notification system has been retained, where applications could, through dbus, create a notification in the notification area that acts in a more standard way for all applications.
Up to version 2.26, Gnome had a "legacy tray" area as a pop out in the bottom corner that could host such icons. Then, Gnome Shell developpers got rid of it all together. Yet, Gnome ShellExtensions such as Topicons Plus and KStatusNotifierItem/AppIndicator Support (used also in Ubuntu desktop as the "Ubuntu appindicators" extension) brought these notification icons back to the topbar. However, application icons have disappeared.
yad for its --notification option may rely on the old mechanism that is now obsolete. Therefore, the option does not work anymore on Unity desktop or Gnome Shell, even with the KStatusNotifierItem/AppIndicator enabled.
Still, the Excellent Gnome Shell extension Argos allows you to create interactive indicators in your top bar. Alternatively, use the notification system instead. In the shell, notifications can be created using notify-send.

A: The gnome shell extension Topicons plus allow us to show icon from  yad --notification
https://extensions.gnome.org/extension/1031/topicons/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't run script from my own package

I have created a simple package using this guide, but I can't run the script inside it.
There is a folder named mypack, which includes /usr/bin/myscript.sh with some command in it (let's say it just echoes a message like "Hello World"), and a folder named DEBIAN with a control file with this text inside:
Package: mypack
Version: 1.0-1
Maintainer: Alex
Architecture: all
Section: misc
Description: echo me

I built and installed it using dpkg-deb --build mypack; dpkg -i mypack.deb as the guide says.
Finally, when I wanted to run the script script to see if it is works, I could not. I have tried:

*

*myscript (returns myscript: command not found)

*myscript.sh (returns bash: /usr/bin/myscript.sh: Permission denied)

*sudo myscript.sh (returns sudo: myscript.sh: command not found)

*mypack myscript and mypack myscript.sh (both return mypack: command not found)

How can I execute it then, so it actually works, or am I missing some important steps, which doesn't let me run the script?

A: Your script isn't set as executable; just like a script not installed by packaging, you need to make sure it has the executable bit set.
You have two options:

*

*When creating the package, make sure that your script has the executable bit set before creating the package, by running this in your work directory Before building the package:
chmod +x /path/to/script.sh
OR...

*Use the postinst script for your package to set the executable bit after installation.  Add a command to the .postinst script similar to the following:
chmod +x /usr/bin/myscript.sh
For some of my things, I use both methods just to make sure it sets things as executable.  That introduces headaches sometimes, but it's better to make sure than not make sure.  At least, in my opinion.

As for the script not being able to be executed as myscript, that's because myscript and myscript.sh are different objects.
If you want that, do the following in your .postinst script for your package:
ln -s /usr/bin/myscript.sh /usr/bin/myscript

... and then assuming you fix the executable bit problem, it should then 'just work' for both of the versions you were trying, both myscript.sh and myscript.
HOWEVER the proper way to do this is, instead, to just package the script as myscript and not include the shell extension.  You should then include a shebang line at the beginning (#!) indicating the interpreter to use.  Since .sh could be anything.  Then, set up the package to just install myscript.  As muru stated, you should avoid making links in your postinst, but it's up to you what you want to do.  There's many different ways to achieve your goal, but not really much strict guidance in the documentation for packaging.


text:
Q: Tableau blended data show null values as zero Blended data contains null values which I would like to show as zeros.
Is there a neat way to do this without introducing additional measures?
How do I attach a file to this query as an example.

A: If you use a measure that contains Null values you usually get a notification on the bottom right corner of the Tableau window on how many null values there are. If you click on it you can define what should happen with these (eg. "Show data at default position" - which is 0)


text:
Q: DoDragDrop() where data is aquired asynch My application is a smart client using a WCF service.
I have a ListView where items are filenames.
Files data are stored server side.
When user drag an item from the list, the data is not client side yet.
Instead of downloading the data up front on the ItemDrag event, I want to download the data from the server only when the item is droped (at MouseUp on Windows Explorer).
Is there a way to implement an AsyncDataObject (IDataObject) and pass it to Control.DoDragDrop()  ?
Or is there any other way that I can acheive this behaviour ?
Thaks

A: Fire an event from the Drop event after the drop is validated that will go ahead and fire off a query that will call back to update the UI with the new data.
This will need a loading indicator directly after the drop to invalidate the current area that the data is being plopped into.

A: What you are doing is dragging virtual content into Explorer. Here's an example in managed code. Here's another. In the first example, you would replace their GetFileContents with a version that downloaded the data.


text:
Q: SQL to join two views Need some help joining these two tables
I have two views that looks like this
view1                view2
+------+--------+    +------+--------+
| code | SUM(*) |    | code | SUM(*) |
+------+--------+    +------+--------+
| AAA  |      4 |    | AAA  |      4 |
| BBB  |      3 |    | CCC  |      1 |
+------+--------+    +------+--------+

I want to join them into a table that looks like this
+------+--------+
| code | SUM(*) |
+------+--------+
| AAA  |      4 |
| BBB  |      3 |
| CCC  |      1 |
+------+--------+

I have tried, but only failed..

A: select *
from view1
union
select *
from view2

Utilizing a UNION will not return duplicate entries, which is what it seems you are looking for.

A: You can use a UNION for this:
SELECT * FROM view1
UNION DISTINCT
SELECT * FROM view2

A: For your first result, the answers posted using union will do the trick:
select * from view1
union
select * from view2

However, given the fact that one of your columns is a sum, this seems unlikely to be what you actually want.
For your second result (where the values are added), you'll need to use a union and a subquery:
select
    code,
    sum(yourcol)

from
(
    select
        code,
        yourcol

    from view1

    union all

    select
        code,
        yourcol

    from view2
) source

group by code


text:
Q: How can I slice a block of text so that it doesn't end on a split word? I've written code that takes a large block of text, splits it into 995 character blocks and pushes each block into an array. However, this often results splits words when they fall at the 995-character line- how could I edit my code so that each block of text is as close as possible to 995 characters long (must be under) but ends at the last available space?
function cutUp() {
var PAname = prompt("Determine PA type and PA Name (e.g. 5=mexican food=");
var chunks = [];
var OGstring = document.getElementById('PATypes').value;
var my_long_string = OGstring.split('1').join('').split('2').join('').split('3').join('').split('4').join('').split('5').join('').split('6').join('').split('7').join('').split('8').join('').split('9').join('').split('0').join('').split('[edit]').join('').split('[citation needed]').join('').split('[').join('').split(']').join('').split('(').join('').split(')').join('');

var i = 0;
var n = 0;
while (n < my_long_string.length) {
    chunks.push(my_long_string.slice(n, n += 995));

}
if (chunks[0] != null) {
    $('PAType=Name=Value8').innerHTML = PAname + chunks[0];
}
if (chunks[1] != null) {
    $('PAType=Name=Value9').innerHTML = PAname + chunks[1];
}
if (chunks[2] != null) {
    $('PAType=Name=Value10').innerHTML = PAname + chunks[2];
}
if (chunks[3] != null) {
    $('PAType=Name=Value11').innerHTML = PAname + chunks[3];
}
if (chunks[4] != null) {
    $('PAType=Name=Value12').innerHTML = PAname + chunks[4];
}
if (chunks[5] != null) {
    $('PAType=Name=Value13').innerHTML = PAname + chunks[5];
}
if (chunks[6] != null) {
    $('PAType=Name=Value14').innerHTML = PAname + chunks[6];
}
if (chunks[7] != null) {
    $('PAType=Name=Value15').innerHTML = PAname + chunks[7];
}
if (chunks[8] != null) {
    $('PAType=Name=Value16').innerHTML = PAname + chunks[8];
}
if (chunks[9] != null) {
    $('PAType=Name=Value17').innerHTML = PAname + chunks[9];
}

////this is to create new exportable table
$('exportTable').innerHTML += $('tableContents').innerHTML;
$("exportTable").removeClass('hidden');
///this resets to default
defaultReset();

}

A: Without any specific Javascript knowledge, I'd say to look ahead 995 characters, and if that character isn't itself a space, to start looking back towards the start until you find a space, and truncate there.
In C-like pseudocode, with chars being your big array of characters:
for(truncOffset = 995; truncOffset > 0; truncOffset--):
{
    if chars[currentLoc + truncOffset] = ' ': /* a space character */ break;
}

Rinse, repeat to taste. Remember to move currentLoc to currentLoc + truncOffset after finding that space.


text:
Q: I need help to put and share a code on gitlab Hello i made a project wit my gr

package CTJ;
import robocode.*;
/**/
public class Firsty extends Robot         <!--part 1-->

{
    public static final int MAX_HITS = 3;
    public static final int TIMER = 3;
    double lastBearing = 0;
    int hitCounter = 0;
    int myTimer = TIMER;

    public void run() {

        while(true) {

            myTimer = myTimer - 1;
            ahead(lastBearing);
            turnGunRight(360);
            back(100);
            turnGunRight(lastBearing + 90);

                if(myTimer == 0) {

                    if(hitCounter > MAX_HITS) {
                        runLikeHell();
                    } else {
                        hitCounter = 0;
                        myTimer = TIMER;
                    }
                }
        }
    }

    public void onScannedRobot(ScannedRobotEvent e) {         <!--PART 2-->

        fire(10);
        back(5);
    }

    public void onHitByBullet(HitByBulletEvent e) {
        turnLeft(90 - e.getBearing());
        lastBearing = e.getBearing();
        hitCounter = hitCounter + 1;
    }

    public void onHitWall(HitWallEvent e) { <!--PART 3-->
        turnRight(e.getBearing() + 153);
    }

    public void runLikeHell() {
        out.println("evading....");
        turnLeft(172);
        ahead(500);
        hitCounter = 0;
        myTimer = TIMER;
    }
}

n the gitlab. i already create the project and i alredy invite them but i dont know how to put the code in, i have the file on my desktop, but i dont know how to use gitlab i dont know the basic stuffs about it i have the gitbash on my computer i use windows can someone help me with it. if possible use screenshot so i can se step by step
This is my code


text:
Q: SharePoint Designer 2010 Errors
Possible Duplicate:
Sharepoint site does not appear on IIS Manager, error in opening site in a sharepoint designer

I have installed SharePoint server 2010 and sp designer 2010 32 bit and ms office 2010 32 bit.
SharePoint server 2010 is working fine.
When I create a new blank web site on SharePoint Designer 2010
Error:
this web site must be created on a server that is running microsoft SharePoint foundation. Please choose another location.
When I open a site from sp designer following error comes.
Unable to open website following causes:

*

*the web server may not have sharepoint installed

*The web server may be temporarily out of service

*if you are connecting through a proxy server the proxy settings may
be incorrect

*An error may be occured in the web server

When I click on customize my website on spdesigner 2010, this error comes
The server unexpectdly closed the connection


text:
Q: How to change the Ruby version in Gemfile I tried starting Zammad from cPanel, and when I executed the command
bundle install --without test development mysql

I got an error about the version of Ruby in the Gemfile:
Your ruby version is 2.4.3 but your Gemfile specified 2.5.5

I manually changed the version of Ruby in the Gemfile, but the error persists. It seems that it does not support my modification:
source 'https://rubygems.org'

# core - base
ruby '2.4.3'
gem 'rails', '5.2.3'

# core - rails additions
gem 'activerecord-import'
gem 'activerecord-session_store
gem 'bootsnap', require: false
gem 'composite_primary_keys'
gem 'json'
gem 'rails-observers'


text:
Q: Google Apps Script - Retrieving username This will hopefully be an easy one for you experienced developers. I'm trying to use the Google Apps Script service to get the username of the logged in user for my Google Site. I can get the email to display fine, however when I try to use the substring method to shorten to the username I get the follow error.

TypeError: Cannot find function substring in object email@email.com. (line 4, file "getusername")

I understand why I'm getting this error but not sure how to fix it. Below is my code
    function doGet() {

  var userEmail = Session.getEffectiveUser();
  var username = userEmail.substring(0, userEmail.indexOf("@"));

  var HTMLString= "
 Logged in as " + userEmail +",
";

    HTMLOutput = HtmlService.createHtmlOutput(HTMLString);
  return HTMLOutput
}

I'm guessing that because the variable userEmail is dynamic depending on the logged in user, the variable username is unable to see the email address until it has executed ?
Any help would be greatly appreciated.
Complete Javascript newbie here.
Thanks
Jack

A: Change:
var userEmail = Session.getEffectiveUser();

to:
var userEmail = Session.getEffectiveUser().getEmail();

If you look at the documentation for Session.getEffectiveUser(), you'll see what the "return" is.  I never paid much attention to that for a long time.  But, you need to always know what is returned.  Some return types are: string, or an object, or an integer, or a Class.  Depending upon what is returned, that will determine what you can further do.  Lots of beginners notice that there is a period in between things, and are able to figure out that they need to patch things together with a period.  But they don't really know what that period is for.  That period is called a dot operator, and every place there is a "dot operator" is basically another step in a process.  You're "chaining" multiple operations together.  In the code: Session.getEffectiveUser().getEmail()  there are two periods (dot operators) and two separate things happening, each with a different returned value.  The getEmail() method returns a string.  The documentation states that getEffectiveUser() returns a "User"  But if you go to the documentation for "User" you'll see it described as a "Class".  To understand what a "Class" is, you'll need to do some research.


text:
Q: How to get the object from a dictionary for a key that is an NSObject? Likely there already are posts dealing with this issue, but I'm not able to find exactly what I want... I've an NSMutableDictionary whose keys are a subclass of NSObject<NSCopying>. I'm finding that objectForKey: is not working, I'm getting always nil even if I use the same key object I've just used for calling setObject:forKey:.
What the best way to handle this should be?

A: When you call setObject:forKey: the key is copied, so the dictionary doesn't get the key object itself. That's why you are getting nil when you call objectForKey:.
You need to implement also -(BOOL)isEqual:(id)anObject.

A: Well, I suppose you need implement
- (id)copyWithZone:(NSZone*)zone;
- (BOOL)isEqual:(id)object
- (NSUInteger)hash;

all method all above in order to use NSObject as key in NSDictionary


text:
Q: Calculating total area of pie charts in ArcMap Background: I am scaling the size of pie charts by a field which indicates a percentage. I am doing this for two datasets displayed on two maps and would like the resulting areas of the scaled pies to be equal between the two maps. I think that I would be able to do this by normalizing the scaled pie sizes using one of the two total areas of the pie charts.
Question: Is it possible to find out the total area of the pies as they are displayed on the map? I am able to scale the sizes manually for example, by setting a larger minimum size symbol, however it is difficult to visually gauge equal total areas this way.

A: While I am unable to determine their areas to create a normalizing field, I was able to just add the percentages from one map's sizing percentage field to the other's and vice versa, such that the pies are now scaled in reference to each other (this way, the percentages were able to take each other into account and display the pies in proportion to all the pies between the two maps).


text:
Q: What is the best way to integrate Picasa and JSF-software? I am implementing small software with JSF. I would like to show users' photos from Picasa, but I have no idea what is the best way to do it? There can be many users and everyone of them has their own Picasa albums.
What do you recommend and why? Is it the wisest to use already implemented JavaScript-softwares like JQuery plugins or Googles Picasa Web Albums Data API to fetch photos etc?
Thanks!
Sami
EDIT:
Have you or somebody else tried Fancybox, I have problems with js and css-files and I think that because of paths to those files. What is the correct way to refer to JS and CSS-files in JSF-files.

A: I recommend using a jQuery based solution like Picasa Webalbum Integrator. All you have to do is to add the required script files to your page and call the needed function, passing it the username of the gallery, like this:
<script type="text/javascript">
$(document).ready(function() {  //-- default jQuery call, do stuff when page is loaded
    $("#container").pwi({  //--specify your DIV's ID here
        username: '#{user.userName}'
    });
});
</script>

Where #{user.userName} is an EL expression pointing to the name of the user which gallery you want to show.

A: My mistake!
Two things what you have to remember when using jquery plugins with JSF.
<h:outputStylesheet library="css" name="pwi.css"  />
<h:outputScript library="js" name="jquery.pwi.js" />

You have to use those tags. I used only h:outputScript for both of them and it seems to be ok, but of course not, generated html wasn't ok.
Other thing was that:
 <h:outputScript library="primefaces" name="jquery/jquery.js" target="head" />

I am using jquery with is in Primefaces, without it there is a conflict between jquery versions or pwi doesn't find jquery at all. At least I think so :) No everything is working fine, so I am happy!
Sami


text:
Q: How to revert changes on a file in sublime-text 2? Through some horrible circumstances one of my files has been changed without me knowing, possibly by repeatedly having pressed Ctrl+Y or something like that. Is there are any internal buffer in Sublime Text where I can have the changes reversed?
Please save my day.


text:
Q: How to specify which group each columns should belong in pandas explicitly? I have dataframe with following columns.

[A,B,C,D,E,F,G...]

I want to use groupby method for this dataframe specifying which group each column should belong to as below.

group1=[A,C,D,G...]
  group2=[B,E,F...]

I could find some page explaining how to use groupby with condition. But could not find answer which fit to this question.
Could anyone tell me how to implement this logic?

A: I believe need:
df = pd.DataFrame({'A':[4,5,4,5,5,4],
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':[4,5,4,5,5,4],
                   'G':[4,5,4,5,5,4]})

print (df)
   A  B  C  D  E  F  G
0  4  4  7  1  5  4  4
1  5  5  8  3  3  5  5
2  4  4  9  5  6  4  4
3  5  5  4  7  9  5  5
4  5  5  2  1  2  5  5
5  4  4  3  0  4  4  4

Create dictionary of groups in lists and then swap keys with values in dicts comprehension with flattening:
d = {'g1':['A','C','D','G'], 'g2':['B','E','F']}
d1 = {k: oldk for oldk, oldv in d.items() for k in oldv}
print (d1)
{'A': 'g1', 'C': 'g1', 'D': 'g1', 'G': 'g1', 'B': 'g2', 'E': 'g2', 'F': 'g2'}

df = df.groupby(d1, axis=1).sum()
print (df)
   g1  g2
0  16  13
1  21  13
2  22  14
3  21  19
4  13  12
5  11  12

A: Create a dictionary that defines the groupings then use that dictionary in a groupby on axis=1
m = {
    *dict.from_keys(['A', 'C', 'D', 'G'], 'group1'),
    *dict.from_keys(['B', 'E', 'F'], 'group2'),
}

df.groupby(m, axis=1).mean()

A: By using for loop with concat
l=[['A', 'C', 'D', 'G'],['B', 'E', 'F']]
pd.concat([df[x].sum(1) for x in l],1)
Out[322]:
    0   1
0  16  13
1  21  13
2  22  14
3  21  19
4  13  12
5  11  12


text:
Q: Boot / shutdown time charge in Azure IaaS Anyone know if, when I create a new VM in Azure, the boot time is charged? when I'm shutting down, is it charged too?
Thanks a lot

A: From https://azure.microsoft.com/en-us/pricing/details/virtual-machines/
It seems yes, you get charged until the point where the status flips to Stopped (Deallocated).


text:
Q: Return 404 for every null response I'd like to return 404 when the response object is null for every response automatically in spring boot.
I need suggestions.
I don't want to check object in controller that it is null or not.

A: You need more than one Spring module to accomplish this. The basic steps are:

*

*Declare an exception class that can be used to throw an exception when a repository method does not return an expected value.

*Add a @ControllerAdvice that catches the custom exception and translates it into an HTTP 404 status code.

*Add an AOP advice that intercepts return values of repository methods and raises the custom exception when it finds the values not matching expectations.

Step 1: Exception class

public class ResourceNotFoundException extends RuntimeException {}

Step 2: Controller advice

@ControllerAdvice
public class ResourceNotFoundExceptionHandler
{
  @ExceptionHandler(ResourceNotFoundException.class)
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public void handleResourceNotFound() {}
}

Step 3: AspectJ advice

@Aspect
@Component
public class InvalidRepositoryReturnValueAspect
{
  @AfterReturning(pointcut = "execution(* org.example.data.*Repository+.findOne(..))", returning = "result")
  public void intercept(final Object result)
  {
    if (result == null)
    {
      throw new ResourceNotFoundException();
    }
  }
}

A sample application is available on Github to demonstrate all of this in action. Use a REST client like Postman for Google Chrome to add some records. Then, attempting to fetch an existing record by its identifier will return the record correctly but attempting to fetch one by a non-existent identifier will return 404.

A: Simplest way to do this in Spring is write your own exception class like below
@ResponseStatus(value = HttpStatus.NOT_FOUND)
class ResourceNotFoundException extends RuntimeException{
}

Then just throw the ResourceNotFoundException from anywhere.
if (something == null) throw new ResourceNotFoundException();

For more -> Read

A: Similar to @manish's answer (https://stackoverflow.com/a/43891952/986160) but without the AspectJ pointcut and using another @ControllerAdvice instead:

Step 1: NotFoundException class:

public class NotFoundException extends RuntimeException {
    public NotFoundException(String msg) {
        super(msg);
    }
    public NotFoundException() {}
}

Step 2: Check if body returned in endpoint is null and throw NotFoundException:

@ControllerAdvice
public class NotFoundAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            throw new NotFoundException("resource not found");
        }
        return body;
    }
}

Step 3: handle NotFoundException and make the response have a status of 404

@ControllerAdvice
public class GlobalExceptionAdvice {

    @Data
    public class ErrorDetails {
        private Date timestamp;
        private String message;
        private String details;

        public ErrorDetails(Date timestamp, String message, String details) {
            super();
            this.timestamp = timestamp;
            this.message = message;
            this.details = details;
        }
    }

    @ExceptionHandler(NotFoundException.class)
    public final ResponseEntity<ErrorDetails> notFoundHandler(Exception ex, WebRequest request) {
        ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(),
                request.getDescription(false));
        return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
    }
}

Alternative to Step 3:

You can just annotate your NotFoundException with @ResponseStatus and override fillInStackTrace() (from https://stackoverflow.com/a/31263942/986160) so that it has similar effect to GlobalExceptionAdvice and doesn't show stacktrace like this:
@ResponseStatus(value = HttpStatus.NOT_FOUND,reason =  "resource not found")
public class NotFoundException extends RuntimeException {
    public NotFoundException(String msg) {
        super(msg);
    }
    public NotFoundException() {}

    @Override
    public synchronized Throwable fillInStackTrace() {
        return this;
    }
}

A: There is no need to throw exceptions, now ResponseBodyAdvice does the trick:
@ControllerAdvice
public class NullTo404 implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        if (body == null) {
            response.setStatusCode(HttpStatus.NOT_FOUND);
        }
        return body;
    }
}

Similarly, you can implement ResponseBodyAdvice<Optional<?>>, and check for Optional.isEmpty() before setting the response status. It has the added benefit of working nicely with CrudRepository. Most controller methods eventually ends like this:
public Optional<Product> getProductBySku(@PathVariable String sku) {
    // logic goes here...
    return productRepository.findBySku(sku);
}


text:
Q: Task.Factory.StartNew and Application.Current.Dispatcher.Invoke Given this code:
Task.Factory.StartNew(() =>
{
    Application.Current.Dispatcher.Invoke(() =>
    {
        //Code to run on UI thread
    });
    //Code to run on a background thread
}).

Is it safe to assume that "Code to run on a background thread" will not be reached under any circumstances until "Code to run on UI thread" is finished executing?

A: When you start the Task, it will run as an worker thread and it will block until Invoke(...) is over.
When Invoke(..) is done it will continue on the worker thread.
"Code to run on UI thread" will run first, next will be "Code to run on a background thread".
You then have the possibility to do some work in a worker thread like read files, write files, query on database with out blocking the main thread, and when needed you can update UI elements with data via Invoke(...)
But take a look at Async/Await, it can make async operation and updating UI element easier to understand.

A:
Dispatcher.Invoke Method (Delegate, Object[])
Executes the specified delegate with the specified arguments synchronously on the thread the Dispatcher is associated with.

https://msdn.microsoft.com/en-us/library/cc647509(v=vs.110).aspx
also see this:
Asynchronous vs synchronous execution, what does it really mean?
Because Dispatcher.Invoke is executed synchronously, and how synchronous execution is defined, your assumption is safe.


text:
Q: Cocoa Scripting: Deletion of elements in a loop getting out of sync While adding scriptability to my Mac program, I am struggling with the common programming problem of deleting items from an indexed array where the item indexes shift due to removal of items.
Let's say my app maintains a data store in which objects of type "Person" are stored. In the sdef, I've define the Cocoa Key allPersons to access these elements. My app declares an NSArray *allPersons.
That far, it works well. E.g, this script works well:
repeat with p in every person
  get name of p
end repeat

The problem starts when I want to support deletion of items, like this:
repeat with p in (get every person)
  delete p
end repeat

(I realize that I could just write "delete every person", which works fine, but I want to show how "repeat" makes things more complicated).
This does not work because AppleScript keep using the original item numbers to reference the items even after deleting some of them, which naturally shifts the items and their numbering.
So, considering we have 3 Persons, "Adam", "Bonny" and "Clyde", this will happen:
get every person
    --> {person 1, person 2, person 3}
delete person 1
delete person 2
delete person 3
    --> error number -1719 from person 3

After deleting item 1 (Adam), the other items get renumbered to item 1 and 2. The second iteration deletes item 2 (which is now Clyde), and the third iteration attempts to delete item 3, which doesn't exist any more at that point.
How do I solve this?
Can I force the scripting engine to not address the items by their index number but instead by their unique ID so that this won't happen?

A: It's not your ObjC code, it's your misunderstanding of how repeat with VAR in EXPR loops work. (Not really your fault either: they're 1. counterintuitive, and 2. poorly explained.) When it first encounters your repeat statement, AppleScript sends your app a count event to get the number of items specified by EXPR, which in this case is an object specifier (query) that identifies all of the person elements in whatever. It then uses that information to generate its own sequence of by-index object specifiers, counting from 1 up to the result of the aforementioned count:
person 1 of whatever
person 2 of whatever
...
person N of whatever

What you need to realize is that an object specifier is a first-class query, not an object pointer (not that Apple tell you this either): it describes a request, not an object. Ignore the purloined jargon: Apple event IPC's nearest living relatives are RDBMSes, not Cocoa or SOAP or any of the OO messaging crud that modern developers so fixate on as The One True Way To Do... well, EVERYTHING.
It's only when that query is sent to your application in an Apple event that it's evaluated against the relational graph your Apple event IPC View-Controller  – aka "Apple Event Object Model" – presents as an idealized, user-friendly representation of your Model's user date that it actually resolves to a specific Model object, or objects, with which the event handler should perform the requested operation.
Thus, when the delete command in your repeat loop tells your app to delete person 1 of whatever, all your remaining elements move down by one. But on the next iteration the repeat loop still generates the object specifier person 2 of whatever, which your script then sends off to your app, which resolves it to the second item in the collection – which was originally the third item, of course, until you shifted them all about.
Or, to borrow a phrase:
Nothing in AppleScript makes sense except in light of relational queries.
..
In fact, Apple events' query-based approach it actually makes a lot of sense considering it was originally designed to be efficient over very high-latency connections (i.e. System 7's abysmally inefficient process switcher), allowing a single Apple event carrying one or more complex queries to manipulate many objects at once. It's even quite elegant [when it works right], but is quite undone by idiots at Cupertino who think the best way to make programmers not hate the technology is to lie even harder about how it actually works.
So here, I suggest you go read this, which is not the best explanation either but still a damn sight better than anything you'll get from those muppets. And this, by its original designer that explains a lot of the rationale for creating a high-level coarse-grained query-based IPC system instead of the usual low-level fine-grained OO message passing crap.
Oh, and once you've done that, you might want to consider try running this instead:
delete every person whose name is "bob"

which is pretty much the whole point of creating a thick declarative-y abstraction that does all the work so the user doesn't have to.
And when nothing but an imperative client-side loop will do, you either want to get a list of by-ID object specifiers (which are the closest things to safe, persistent pointers that AEOMs can do) from the app first and then iterate over that, or at least use your own iterator loop that counts over elements in reverse:
repeat with i from (count every person) to 1 by -1
    tell person i
        ..
    end tell
end repeat

so that, assuming it's iterating over an ordered array on the server side, will delete from last to first, and so avoid the embarrassing off-by-N errors of your original script.
HTH

A: re: "If you want your scripable elements to be deletable, make sure you use NSUniqueIDSpecifiers to identify them."
Yes, Apple recommends using formUniqueId or formName for object specifiers, but you can't always do that. For instance, in the Text Suite, you really only have indexing to work with; e.g. character 1, word 3, paragraph 7, etc. You don't have unique IDs for text elements. In addition to deletion, ordering can be affected by other Standard Suite commands: open, close, duplicate, make, and move.
The app implementer is a programmer, but so is the scripter. So it is reasonable to expect the scripter to solve some problems themselves. For instance, if the app has 5 persons, and the scripter wants to delete persons 2 and 4, they can easily do so even with indexed deletion:
delete person 4
delete person 2

Deleting from the end of an ordered list forward solves the problem. AS also supports negative indexes, which can be used for the same purpose:
delete person -2
delete person -4

A: The key to solving this lies in implementing the objectSpecifier method correctly so that it does return an NSUniqueIDSpecifier.
My code did so far only return an index specifier and that was wrong for this purpose. I guess that had I posted my code (which is, unfortunately, too complex for that), someone may have noticed my mistake.
So, I guess the rule is: If you want your scripable elements to be deletable, make sure you use NSUniqueIDSpecifiers to identify them. For read-only element arrays, using an NSIndexSpecifier is (probably) safe, though, if your element array has persistent ordering behavior.
Update
As @foo points out, it's also important that the repeat command fetches the references to the items by using … in (get every person) and not just … in every person, because only the former leads to addressing the items by their id whereas the latter keeps indexing them as item N.


text:
Q: Windows Authentication PopUp I've setup SharePoint 2019 and I'm having an issue windows authentication where a login box is shown to the site.  I've read tons of doc and here is what I have done:
Web Application port: 443
Full Read for accounts:
NT AUTHORITY\LOCAL_SERVICE,
<Share Point User>,
All Users (windows)

Under the Site.  In Site Permissions I added:
Site Visitors - Read

Advanced Permission Settings:
Everyone - Domain Group - Read
SharePoint Group - Read

but every time a user goes to the site page it asks for authentication.  Any ideas on what I'm missing.  Its setup to use AD authentication.
For example, if I set up a domain user as a Farm Administrator and have them go to the central admin page:    http://someserver:11667 it works with the page showing but on the site page it prompts for a login still.
I've seen articles about adding the site to your local browser as trusted sites.  But since we using Windows 10 client and Window 2016 Server with SharePoint 2019, I would have thought it would work.  I'm testing on Edge, Chrome and Firefox.

A: Edge and Firefox, this is expected. Add the site to the Trusted Sites list in IE and then test with Chrome.

A: To handle the basic authentication popup, we can pass the username and password along with the web page's URL. When the login pop-up is prompted, we enter the username as "admin" and the password as "admin" and then log in. Thus, the user would be successfully logged into the website.


text:
Q: CSS3 Simultaneous Image Rotation, Scaling, animating and Opacity reduction I wanted to create a Metro Style Website and want to add Buttons like in the following :
http://themeforest.net/item/metro-lab-responsive-metro-dashboard-template/full_screen_preview/5359122
When we hover over the 'New User', 'Sales' etc Tabs, the icons/Images in the tabs rotates, increases its size and looses opacity.
But I am not able to get the exact output. I get only 2 outputs at a time :
--> Opacity and Scaling
--> Opacity and Rotation
but not all of them simultaneously.
You can see where I had reached at :
http://developer.nuevothoughts.com/jiteen/attendance/docs/#
My Current CSS is :
.icon-rocket{
-webkit-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-o-transition-duration: 0.8s;
transition-duration: 0.8s;

-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
-o-transition-property: -o-transform;
transition-property: transform;

overflow:hidden;

}

.icon-rocket:hover
{
    -webkit-transform:rotate(360deg);
    -moz-transform:rotate(360deg);
    -o-transform:rotate(360deg);

/******************************/

-webkit-transform: scale(2.5,2.5);
-moz-transform:scale(2.5,2.5);
opacity: 0.5;
-moz-opacity: 0.5;
}

I would appreciate any kind of Help in this.

A: add following code
.main_tab.shortcut.span2.padding20.text-center a:hover i {
  font-size: 40px;
  opacity: 0.5;
  transform: rotate(45deg);
}

and remove the hover you used (icon-rocket:hover)


text:
Q: Drawing tables and arrows connecting them I would like to know whether it is possible to draw something like the example below with ggplot2. If not, could you please direct me to an appropriate tool to accomplish that in R? Thanks!

A: Short answer: Yes, of course it's possible. It depends a bit on what your use case is on how much automatisation you want to put into it. The tricky bit is clearly the arrow bit, and on trying an automated approach it became slightly convoluted, so I'll leave that to you - just showing one principle way to get this in ggplot2.
library(tidyverse)
ls_tbl <- replicate(3, data.frame(label = paste0("Field", 5:1)), simplify = FALSE)
## make the data frames for tables and rects
ls_df <- lapply(seq_along(ls_tbl), function(i){
  df <- rbind(ls_tbl[[i]], paste0("Table", i))
  df$y <- seq_len(nrow(df))
  df$x <- i
  df_rect <- data.frame(xmin = i-.2, xmax = i+.2, ymin = min(df$y)-.5, ymax = max(df$y)+.5)
  y_seg <-  (df$y[length(df$y)] + df$y[length(df$y)-1])/2
  df_seg <- data.frame(x = i-.2, xend = i+.2, y =y_seg, yend = y_seg)
  setNames(list(df, df_rect, df_seg), c("text", "rect", "seg"))
})
## draw arrows, this can be automated based on the position of fields and tables
## that's not suuuuper straight forward, so I won't do that here
arrow_df <- data.frame(x = c(1, 3), xend = rep(2, 2), y = c(5, 5), yend = c(2, 4)) %>%
  mutate(x = ifelse(xend > x, x + .2, x - .2),
         xend = ifelse(xend > x, xend- .2, xend + .2))

## now plotting fun
ggplot() +
  geom_rect(data = bind_rows(map(ls_df, "rect")), color = "black", fill = NA,
            aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax)) +
  geom_segment(data = bind_rows(map(ls_df, "seg")), aes(x, y, xend = xend, yend = yend))+
  geom_text(data = bind_rows(map(ls_df, "text")), aes(x, y, label = label)) +
  geom_segment(data = arrow_df, arrow = arrow(type = "closed"),
               aes(x, y, xend = xend, yend = yend)) +
  theme_void()

Created on 2021-12-24 by the reprex package (v2.0.1)

A: I have meanwhile found a way with DiagrammeR and graphviz ports:
library(DiagrammeR)

grViz("
digraph G {
    graph [layout=neato overlap = true]
    node [shape=plaintext]

    a [label=<

Table 1

Field 1

Field 2

Field 3

Field 4

Field 5

> pos = '0,0!'];

    b [label=<

Table 2

Field 1

Field 2

Field 3

Field 4

Field 5

> pos = '1.5,-0.5!'];

    c [label=<

Table 3

Field 1

Field 2

Field 3

Field 4

Field 5

> pos = '3,0!'];

    a:11 -> b:21;
    c:31 -> b:24;

}")

A: You might want to look into the DiagrammeR package, as it has a lot of options for visualizing information like this. So, for example, you could do the following to do something similar to your example:
library(DiagrammeR)

grViz("
      digraph CFA {
      a [label = <Table 2
 Field 1
 Field 2
 Field 3
 Field 4
 Field 5>, shape = rectangle];

      node [shape = rectangle]
      T1    [label = <Table 3
 Field 1
 Field 2
 Field 3
 Field 4
 Field 5>];
      T2    [label = <Table 1
 Field 1
 Field 2
 Field 3
 Field 4
 Field 5>];

      {rank = same; a T1 T2}

      # Connect nodes with edges and labels
      a -> T1[dir=back]
      T2 -> a[dir=forward]
       }

      ")

Output

You can see Richard Iannone's webpage for more in depth information on how to manipulate the layout, different shapes, etc.


text:
Q: Creating classes with for loop with the index name in it I want to make 4 classes for 4 players. So i thought that it can be easily fixed with a for loop.
for(int i = 0; i<playerlist.size(); i++){
    PlayerStats player+i = new PlayerStats(playerlist.get(i),app,0f,135f,190f,100f);
    app.addGameObject(player+i);
    }

This does not work..
Has anyone a solution for this problem?
Thanks in advance!


text:
Q: Django: Uppercase/Lowercase values of Django Model attributes should be treated as same I have model city:
class City(models.Model):
    state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True)
    name_regex = RegexValidator(regex=r'^[a-zA-Z]+$',
                                message="Name should only consist of characters")
    name = models.CharField(validators=[name_regex], max_length=100)
    postalcode = models.IntegerField(unique=True)

    class Meta:
        unique_together = ["state", "name"]

In this model name of city with all the cases (Uppercase/lowercase) should be treated as same like Udaipur/udaipur/udaiPuR all should be treated as same.

A: Try this in your model, it should do the trick for you
class NameField(models.CharField):
    def __init__(self, *args, **kwargs):
        super(NameField, self).__init__(*args, **kwargs)

    def get_prep_value(self, value):
        return str(value).lower()

class City(models.Model):
    state = models.ForeignKey('State', on_delete=models.SET_NULL, null=True)
    name_regex = RegexValidator(regex=r'^[a-zA-Z]+$',
                                message="Name should only consist of characters")
    name = NameField(validators=[name_regex], max_length=100)
    postalcode = models.IntegerField(unique=True)

    class Meta:
        unique_together = ["state", "name"]


text:
Q: Rails running on virtual machine in Windows The reason why I want to switch to Ubuntu is that people said that GEMS works better on Linux than on Windows.
I don't want to get a MacBook Pro just for Rails development since I love Windows and I cannot stand the lack of apps for Mac. Moreover, people are saying that Ubuntu is "better" than Mac: http://www.reddit.com/r/Ubuntu/comments/1bgj1s/are_there_advantages_of_ubuntu_over_os_x_for/
Does Virtual Box work well enough that it doesn't have any lag at all? I am using i7-3517U CPU with 8GB memory. I need to program in an environment that is lag-free and not sluggish. Or are there any alternatives to recommend?
I am unsure about all the permission settings or any complicated stuffs regarding the terminal. But I'll be using the terminal to develop. I'm still quite new here for development in Linux. Please be kind to me >< Thanks.

A: @holyxiaoxin I am pretty sure you should be asking this on superuser instead.
Nevertheless, I would suggest you to install Ubuntu in a partition instead of running a Virtual Machine. Here's a guide https://help.ubuntu.com/community/WindowsDualBoot
Also, yes. Developing in a virtual machine could be very accurate, but at the end you could experiment weird behaviour when working with native libs mostly and you will be wondering if it is the VM or your setup.
Hope this help you get started. Also Ubuntu and Ruby on rails
P.S. I use OSX and it's the best you can get for RoR and development environments. Think about it as an investment to the future.

A: @holyxiaoxin hi. I have only ran rails on windows and Mac. Me personally I just got a MacBook pro. In my opinion Mac makes my life easier when it comes to rails development plus I am learning xcode and swift at the same time. I feel like you have to jump through hoops and ladders to fix certain errors and install gems on windows such as paperclip and even public activity. Yes it does help you with your skills in debugging but it slows down the learning process. Not only that but Mac is a faster development environment. I am not an expert but I just wanted to give you my personal experience if that is okay. I love windows as well and it makes me sad playing on my Mac while my windows is sitting over there but I still use my windows for things like packet tracer(which I haven't done in forever since discovering rails) Python, and writing essays and learning visual studios


text:
Q: Trying to install phpmyadmin on centos - mysqli missing Here is the error I get when trying to open my phpmyadmin directory:
phpMyAdmin - Error
The mysqli extension is missing. Please check your PHP configuration.

I have done the steps in the following tutorial:
http://chrisjean.com/2011/06/24/upgrade-php-5-1-or-5-2-to-5-3-on-centos/
(Only until the mcrypt section) (I wanted to upgrade php to 5.3 because phpmyadmin said I needed php 5.2+)
I've tried to install mysqli and go to the php.ini (changing mysqli.default_host = localhost) but I had no luck getting rid of this error message and starting to work with phpmyadmin.
Do you know any trick that could help me?

A: I just had the exact same problem with my installation of an Ubuntu server. It turned out all I had to do was
sudo apt-get install php5-mysqli
You could try the equivalent to centOS(and your situation) and see if it works
yum install php53-mysqli
EDIT:
Scratch the previous commands, just use these two:
yum install php-mysql and yum install php-mysqli


text:
Q: How to vertical align image and text cross client email templates

     Reliable service team, deployed to your location, at your convenience

I have the above code in Outlook. It displays fine but in Gmail, Yahoo and Hotmail, the bullets and text do not align vertically on top, it seems like there is padding round the top of the text. Any ideas?

A: Use this code

   Reliable service team, deployed to your location, at your convenience

A: First as a general practice with emails you'll want to put display block and typically border:none on all images.  Secondly you might be running into trouble with defaults. Set all styles on the td's.  If I need some specific spacing I'll set the font size and line height to 1px on the td to avoid inheritence. You might also need valign top on your first td. I can't really tell what part isn't lining up from the description. Good luck with your emails.

A: Long story short, in the testing that I've been doing this afternoon it looks like outlook supports the valign property on td elements but gmail and the rest want the vertical-align css rule. Gmail only supports inline styles, not style tags, so you have to do something like this:

Also make sure you declare a doctype! Make sure this is above your  element:
<!DOCTYPE html>


text:
Q: loadkeys has (almost) no effect I'm running CentOS 6.4 on vagrant and then doing a vagrant SSH into the box. I've been trying to get backspace to work correctly for a while now (as chronicled here: Centos Terminal Configuring Backspace and Ctrl-h Correctly)
As a part of this, I'm trying to use loadkeys to modify the actions in the keymap - but that doesn't seem to work very well. So, as root, I did the following (as specified here):
[root@localhost vagrant]# dumpkeys -f  | grep -iE string
...
string F9 = "\033[20~"
string F10 = "\033[21~"
...

[root@localhost vagrant]# echo 'string F10 = "foo" ' | loadkeys   # to make F10 print "foo"

[root@localhost vagrant]# dumpkeys -f  | grep -iE string   # verify that keymap is changed
...
string F9 = "\033[20~"
string F10 = "foo"
...

Now type F10. This keeps giving me the ~ character instead of printing foo. This is the original behavior before loadkeys were invoked - so it looks like loadkeys has no effect at all?

A: loadkeys re-programs the terminal emulator that is built in to the kernel, via ioctl() requests through a kernel virtual terminal device.  You aren't using that terminal emulator when you connect to the machine via ssh.  Indeed, you aren't involving any terminal emulator, kernel or user space, on that machine at all.
The terminal emulator on your local machine is what is mapping function key presses into control sequences.  Of course loadkeys isn't reprogramming the terminal emulator that is running on a completely different machine at the local end of your ssh connection.
If you hadn't run loadkeys as the superuser, you'd have received the useful error message that when run from the ssh login session loadkeys couldn't find a kernel virtual terminal to talk to, because one wasn't involved in that login session.


text:
Q: TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'str' I am trying to take a string input and convert it using the table, but when I do so I get "TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'str'"
def solution(s):

    word = input("Enter Text:" ).lower()

    for i in range(0, len(s)):
        if s[i].isupper():
            word=input + '000001'

        word=input+braillecodes[asciicodes.index(s[i].lower())]

    return word

#The Alpha Lookup Table
asciicodes = [' ', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
braillecodes = [
'000000',
'100000',
'110000',
'100100',
'100110',
'100010',
'110100',
'110110',
'110010',
'010100',
'010110',
'101000',
'111000',
'101100',
'101110',
'101010',
'111100',
'111110',
'111010',
'011100',
'011110',
'101001',
'111001',
'010111',
'101101',
'101111',
'101011']

#Print
print (solution('s'))

A: you are trying to add Builtin input to the str that's why you get the error.


text:
Q: writing to text file in blackberry is there any way out that we can make the data in text file persistent? everytime a user finishes playing a game, in my program his name and respective score is written to a text file. When the next player comes the previous one gets overwritten. since am writing in write mode, I am not sure whether append mode is supported to save scores of this sort in blackberry...any suggestions are welcome

A: You should really use the PersistentStore to store this type of information - it's much easier to use and probably more reliable than trying to write files.
However, if you insist on writing files, here's the general code to open a file for appending:
private OutputStream openFileForWriting(String filePath) {
    try {
        FileConnection fconn = (FileConnection) Connector.open(filePath);
        // If no exception is thrown, then the URI is valid, but the file may or may not exist.
        if (!fconn.exists()) {
            fconn.create();  // create the file if it doesn't exist
        }
        return fconn.openOutputStream(fconn.fileSize());
    } catch (IOException ioe) {
        System.out.println("Could not open " + filePath + " for writing");
    }
    return null;
}


text:
Q: Hazelcast Spring Boot java.lang.ClassNotFoundException I am starting hazelcast instance in my spring boot application.
Hazelcast configuration
@Configuration
@EnableCaching
public class HazelcastConfig {
    @Bean
    public Config hazelCastConfig() {
        final Config config = new Config();
        config.setClassLoader(getClass().getClassLoader());
        config.setInstanceName("cache");
        return config;
    }

    @Bean
    public HazelcastInstance hazelcastInstance() {
        return Hazelcast.newHazelcastInstance(hazelCastConfig());
    }
}

And it fails time to time with class not found exception when I call my HTTP endpoint that queries data from hazelcast Map.
java.lang.ClassNotFoundException: com.someOrg.SomeClass
at org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader.loadClass(TomcatEmbeddedWebappClassLoader.java:70) ~[spring-boot-2.0.5.RELEASE.jar!/:2.0.5.RELEASE]
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137) ~[tomcat-embed-core-8.5.34.jar!/:8.5.34]
at com.hazelcast.nio.ClassLoaderUtil.tryLoadClass(ClassLoaderUtil.java:173) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.nio.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:147) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.nio.IOUtil$ClassLoaderAwareObjectInputStream.resolveClass(IOUtil.java:593) ~[hazelcast-3.9.4.jar!/:3.9.4]
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1826) ~[na:1.8.0_131]
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713) ~[na:1.8.0_131]
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000) ~[na:1.8.0_131]
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535) ~[na:1.8.0_131]
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422) ~[na:1.8.0_131]
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:79) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.internal.serialization.impl.JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:72) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.internal.serialization.impl.StreamSerializerAdapter.read(StreamSerializerAdapter.java:48) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.internal.serialization.impl.AbstractSerializationService.toObject(AbstractSerializationService.java:191) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.CachedQueryEntry.getValue(CachedQueryEntry.java:75) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.CachedQueryEntry.getTargetObject(CachedQueryEntry.java:108) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.QueryableEntry.extractAttributeValue(QueryableEntry.java:81) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.QueryableEntry.getAttributeValue(QueryableEntry.java:48) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.predicates.AbstractPredicate.readAttributeValue(AbstractPredicate.java:132) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.impl.predicates.AbstractPredicate.apply(AbstractPredicate.java:57) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.query.PredicateBuilder.apply(PredicateBuilder.java:51) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.map.impl.query.PartitionScanRunner.run(PartitionScanRunner.java:97) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.map.impl.query.CallerRunsPartitionScanExecutor.execute(CallerRunsPartitionScanExecutor.java:42) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.map.impl.query.QueryRunner.runPartitionScanQueryOnGivenOwnedPartition(QueryRunner.java:172) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.map.impl.query.QueryPartitionOperation.run(QueryPartitionOperation.java:55) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:194) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:409) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:115) ~[hazelcast-3.9.4.jar!/:3.9.4]
at com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.run(OperationThread.java:100) ~[hazelcast-3.9.4.jar!/:3.9.4]

Tried with config.setClassLoader(getClass().getClassLoader()); in hazelcast configuration class and without it - it fails after some time with the same ClassNotFoundException issue.
Why hazelcast fails with this issue and how to fix it ?

A: I fixed the issue by using Hazelcast feature User Code Deployment
Configuration file that works for me
@Configuration
@EnableCaching
public class HazelcastConfig {
    @Bean
    public Config hazelCastConfig() {
        final Config config = new Config();
        config.setClassLoader(Thread.currentThread().getContextClassLoader());

        final UserCodeDeploymentConfig distCLConfig = config.getUserCodeDeploymentConfig();
        distCLConfig.setEnabled(true)
          .setClassCacheMode(UserCodeDeploymentConfig.ClassCacheMode.ETERNAL)
          .setProviderMode(UserCodeDeploymentConfig.ProviderMode.LOCAL_CLASSES_ONLY);

        return config;
    }

    @Bean
    public HazelcastInstance hazelcastInstance() {
        return Hazelcast.newHazelcastInstance(hazelCastConfig());
    }
}


text:
Q: Two variations of Hilbert's 90 theorem Let $L/K$ be a finite Galois extension.
I know that $H^1(Gal(L/K), L^{\times}) = 0$ and $H^r(Gal(L/K), (L,+)) = 0$ for all $r>0$.
1) Do we have $H^r(Gal(L/K), L^{\times}) = 0$ for all $r>1$ ?
2) Do we have $H^1(Gal(L/K), (L^{\times})^n) = 0$ for all $n>1$, where I'm using the diagonal action on the product ?
Thank you!

A: In the following, write $G=Gal(L/K)$.
1) The main reason behind the nullity of all the cohomology groups $H^r(G, (L,+))$ is the so-called normal basis theorem: there exists $x\in L$ s.t. the system $s(x)$, for $s$ running through $G$, is a basis of the $K$-vector space $L$, in other words, $L$ is a $K[G]$-free module, hence has trivial cohomology.
2) The multiplicative version of Hilbert's thm.90 states that $H^1(G, L^*)=0$, but the higher cohomology groups do not vanish in general. And fortunately so, because what would be the interest of the cohomology theory of fields ? Here is a list of the most interesting cases:
a) If $K$ is a finite field, $G$ is cyclic, generated by the Frobenius automorphism. But in the cyclic case, say with $G=<\phi>$, it is known that $H^2(G, L^*)\cong K^*/NL^*$ and $H^1(G, L^*)\cong KerN/(L^*)^{\phi-1}$, where $N$ denotes the norm map. Since $L^*$ is finite, the kernel and cokernel of $\phi-1$ have the same order, and Hilbert's 90 then immediately implies the nullity of $H^2(G, L^*)$. This last property is known as the surjectivity of the norm in a finite extension of finite fields.
b) In the general case, $H^2(G, L^*)$ is known to be canonically isomorphic to the relative Brauer group $Br(L/K)$, which is a subgroup of the absolute Brauer group $Br(K)$, with exponent dividing the degree $[L:K]$. Recall that $Br(K)$ is a fundamental object which classifies the equivalence classes of central simple $K$-algebras.
c) Even "better", in local CFT, which describes the abelian extensions of a local $p$-adic field, $Br(L/K)$ is cyclic of order $[L:K]$, generated by a so-called fundamental class $u(L/K)$ which encapsulates the main properties of the theory. For instance, the cup-product with $u(L/K)$ defines an isomorphism of the abelian quotient $G^{ab}$ onto $K^*/NL^*$ (the inverse of this isomorphism is usually called the local reciprocity map or the norm residue symbol). More generally, the whole $G$-cohomology of $L^*$ is given by the cup-product with $u(L/K)$, which gives $H^r(G,\mathbf Z)\cong H^{r+2}(G,L^*)$ for all $r\in \mathbf Z$ (modified Tate cohomology groups here).
NB: On the archimedean side, as recalled by @Lord Shark the Unknown, local CFT boils down to an isomorphism $H^2(G(\mathbf C/\mathbf R), \mathbf C^*)\cong \mathbf Z/2\mathbf Z)$, and the fundamental class corresponds to the quaternion algebra.
d) In global CFT (for number fields or, more generally, global fields), one must replace $L^*$ gy the idèle class group $C_L$, and the main key is again a certain fundamental class $u(L/K)\in H^2(G, C_L)$ which has properties similar to those of the local classes. From these one can deduce global-local properties of the cohomology groups $H^r(G,L^*)$. For example, $H^3(G,L^*)$ is cyclic of order $n/n_0$, the global degree divided by the l.c.m. of the local degrees, generated by the Teichmüller class $\delta(u(L/K))$, where $\delta$ is the natural map $H^2(G, C_L) \to H^2(G, L^*)$.
For local and global CFT, I refer to chapters VI and VII of Cassels-Fröhlich.
3) You ask for $H^1(G,(L^*)^n$) with diagonal action of $G$ on the direct product. I wonder why, since this is not a very natural action. Anyway, if $A, B$ are two $G$-modules, then naturally $H^r(G, A\times B)\cong H^r(G,A)\times H^r(G,B)$  ./.

A: We don't in general have $H^2(\textrm{Gal}(L/K),L^\times)=0$. These $H^2$ groups are related to Brauer groups, which classify central division algebras over $K$.
In particular $H^2(\textrm{Gal}(L/K),L^\times)$ is the relative Brauer group
$\text{Br}(L/K)$, the kernel of the natural map $\text{Br}(K)\to
\text{Br}(L)$ between the Brauer groups
of $K$ and $L$.
An easy special case is $H^2(\textrm{Gal}(\Bbb C/\Bbb R),\Bbb C^\times)
\cong\Bbb Z/2\Bbb Z$.


text:
Q: dictate order of dynamically rendered table React.js I am dynamically rendering a table from an aws dynamo database. I want to have the newest posts rendered first. I am using the createdAt variable as the key but the table still renders randomly. I'm having trouble figuring out whats wrong and would appreciate the help. Code:
 export default class Home extends Component {
 constructor(props) {
  super(props);

  this.state = {
   isLoading: true,
   sort: {
    column: null,
    direction: 'desc',
   }
  };

  this.onSort = this.onSort.bind(this);

 }

 async componentDidMount() {
  if (!this.props.isAuthenticated) {
   return;
 }

 try {
  const results = await this.notes();
  this.setState({ notes: results });
 } catch (e) {
   alert(e);
 }

  this.setState({ isLoading: false });
 }

 notes() {
  return invokeApig({ path: "/notez" });
 }

 handleNoteClick = event => {
  event.preventDefault();
  this.props.history.push(event.currentTarget.getAttribute("href"));
 }

 onSort(column) {
   return(function(e) {
     let direction = this.state.sort.direction;

     if (this.state.sort.column === column){

      direction = this.state.sort.direction === 'asc' ? 'desc' : 'asc';
     }

     const sortedData = this.state.notes.sort((a, b) => {
      if(column === 'date') {

       return a.createdAt - b.createdAt;
      }
     });

     if(direction === 'desc'){
      sortedData.reverse();
     }

     this.setState({
      notes: sortedData,
      sort: {
        column,
        direction,
      }
     });
  }).bind(this);
 }

 renderNotesList(notes) {

  var styles = {
   progress: {
     backgroundColor: "#ffff00",
     color: '#000000'
   },
   completed: {
     backgroundColor: "#66CD00",
     color: '#000000'
   }
  }

  return (

          Title
          Employee

            Created

          Status

        {this.state.notes.map((note) =>
          <tr
            key={note.createdAt}
            href={`/notes/${note.noteId}`}
            onClick={this.handleNoteClick}
            className="workOrders"
          >
            {note.title}
            {note.employee}
            {new Date(note.createdAt).toLocaleString()}
            {note.jobStatus === 'In Progress' || note.jobStatus !== 'Completed' ? {note.jobStatus}	 : {note.jobStatus}	}

        )}

 );
}

The createdAt is stored as integer value in the database:

I thought I'd be able to render the list from newest to oldest since the createdAt date that is most recent is higher in value. Is this possible?

A: You are not sorting the data on initial render. You only sort them after table header column "Created" is clicked. You can try adding this.onSort('date') after the this.setState({ notes: results }); in your componentDidMount function or better yet, just sort the results before passing it to the state:
const results = await this.notes();
const notes = results.sort((a, b) => {
  return a.createdAt - b.createdAt;
});
this.setState({ notes });

Then of course you don't want to forget to change your default sort column in constructor from null to 'date'.


text:
Q: jacobson radical of a module Let $B:=k[r,s]/(r^2,s^2,rs)$ be a polynomial ring , $k$ a field and $m={\ }_BB$. What is the radical of $m$?
Thanks for the help.

A: Since $r$ and $s$ are nilpotent, $r,s\in rad(B)$, and $(r,s)\subseteq rad(B)$.
Since $B/(r,s)\cong k$, we have that $(r,s)$ is maximal, an hence $rad(B)\subseteq (r,s)$.
Hence, $rad(B)=(r,s)$.

A: Your subspaces are not closed under the action of $B$ (e.g. $r\cdot 1=r\notin <\{1,s\}>$). Each submodule of $B$ containing $1$ is already $B$ itself.
The only maximal submodule of $m$ is the two-dimensional subspace spanned by $r$ and $s$. Hence this is the radical.


text:
Q: Wait for all tasks when tasks run async methods I have been trying to combine the results of several questions on waiting for multiple threads, but my call to await Task.WhenAll(Tasks); is being passed before all tasks are finished!
List<Task> tasks = new List<Task>();
foreach (DownloadingFile file in downloadingFiles)
{
    Task t = new Task(async delegate { await file.PollDownload(); } );
    tasks.Add(t);
    t.Start();
}
await Task.WhenAll(tasks);

internal async Task PollDownload()
{
    string localFile = "pathToDestination";
    WebRequest headerRequest = WebRequest.Create(uri);
    headerRequest.Method = "HEAD";
    HttpWebResponse response = null;
    try
    {
        response = (HttpWebResponse) await headerRequest.GetResponseAsync();
    }
    catch
    {
        Thread.Sleep(500);
        try
        {
            response = (HttpWebResponse)await headerRequest.GetResponseAsync();
        }
        catch
        {
            response = null;
        }
    }
    if (response == null)
    {
        state = DOWNLOAD_STATE.FAILED;
        return;
    }
    totalBytes = response.ContentLength;
    state = DOWNLOAD_STATE.WAITING_START;
    //Check to see whether a local copy of the remote file exists
    if (File.Exists(localFile))
    {
        DateTime localFileUpdated = File.GetCreationTimeUtc(localFile);
        DateTime onlineFileUpdated = response.LastModified;
        // If the download date of the local file comes after the modification date of the remote copy
        // then we do not need to take any further action here.
        if (onlineFileUpdated <= localFileUpdated)
        {
            state = DOWNLOAD_STATE.SKIPPED;
        }
        //Otherwise we should remove the local copy and proceed with the download
        else
        {
            File.Delete(localFile);
        }
    }
    return;
}

I assume this is because the Tasks include async delegate methods? I don't WANT them to be async but they need to be because of the PollDownload() awaits other async methods ( though they can probably be changed to synchronous methods here they cannot be changed to synchronous methods in another instance of this problem so I still need a solution).

A: new Task() accepts an Action, so you're passing an async void that does not wait for its result.
You should use Task.Run() instead, which also accepts Func<Task>.


text:
Q: Generic Configurable Condition checker at Runtime I'm writing a "generic" achievement system for my MMORPG project, it needs to be friendly & efficient for my game designers (without having to write any kind of code to add new achievements).
For that, I thought about a solution, which is a basic configuration file that is linked to an enumeration of "eventType" and provide a list of optional args (based on the Event properties)
Here is an example
name: ACHIEVEMENT_NAME
event_type: ITEM_USAGE # enum as a string, there is a list of event types
count: 30 # 30 item usage
args: # every args are optional
  item_vnum: 1127 # vnum - optional
  map_id: 1 # on map id 1 only - optional

public enum AchievementEventType
{
    ITEM_USED,
    MONSTER_KILLED,
}

public interface IAchievementArgument
{
    AchievementEventType EventType { get;}
}

public class MonsterKilledAchievementArgument : IAchievementArgument
{
    public AchievementEventType EventType => AchievementEventType.MONSTER_KILLED;

    public long MonsterVnum { get; set; }
    public short? MapId { get; set; }
}

public class AchievementConfiguration
{
    public string Name { get; set; }
    public string EventType { get; set; }
    public long Count { get; set; }
    public Dictionary<string, object>? Args { get; set; }
}

public delegate bool AchievementFilter(IAchievementArgument achievementArgument);

I thought about generating an expression tree to build a delegate (AchievementFilter) for my "Achievement incremental condition"
(Basically, the function that will check if the player's specific achievement counter can be incremented or not)
There are two solutions I thought, both have their pros/cons, but I'm looking for external point of view, what do you think about it. (or maybe, another kind of solution that you could present me)
1 expression tree per achievement
I generate 1 expression tree per achievement that will compare the IAchievementArgument given as parameter with the achievement configuration.

*

*Pros :

*

*faster at execution time (each achievement condition have their own delegate)

*Cons:

*

*Memory footprint

1 expression tree per args type
I generate 1 expression tree per IAchievementArgument type that will fetch and compare achievement configuration one by one

*

*Cons :

*

*More execution time (needs to check all key/value equality of each achievement configuration)

*Pros :

*

*Lighter memory footprint

Thanks by advance :slight_smile:


text:
Q: After submit comments select the current tab In my single.php I have 3 tabs one for description, others for comments and reviews my question is when I submit the comments, the first tab is always selected. My code:

                    Description
                    Comments
                    Reviews

                    <?php the_content(); ?>

                    <?php if ( comments_open() || true): ?>
                        <?php comments_template( '', true ); ?>
                    <?php endif ?>

REVIEW

How can I pass the attribute class="selected" dynamically?

A: i think the best solution is to add an get attribute, in this case we don't need javascript like this:
your single.php :

                <a href="<?php the_permalink(); ?>&tab=description" class="<?php echo !isset($_GET['tab']) || ($_GET['tab'] == 'description') ? 'selected':''; ?>">Description
                <a href="<?php the_permalink(); ?>&tab=comment" class="<?php echo isset($_GET['tab']) && ($_GET['tab'] == 'comment') ? 'selected':''; ?>">Comments
                <a href="<?php the_permalink(); ?>&tab=review" class="<?php echo isset($_GET['tab']) && ($_GET['tab'] == 'review') ? 'selected':''; ?>">Reviews

            <div id="tab-description" class="tab-content" style="display: <?php echo !isset($_GET['tab']) || ($_GET['tab'] == 'description') ? 'block;':'none;'; ?>">
                <?php the_content(); ?>

            <div id="tab-comment" class="tab-content" style="display: <?php echo isset($_GET['tab']) && ($_GET['tab'] == 'comment') ? 'block;':'none;'; ?>">
                <?php if ( comments_open() || true): ?>
                    <?php comments_template( '', true ); ?>
                <?php endif ?>

             <div id="tab-review" class="tab-content" style="display: <?php echo isset($_GET['tab']) && ($_GET['tab'] == 'review') ? 'block;':'none;'; ?>;">

REVIEW

and in your function.php add this:
    if ( ! function_exists( 'redirect_after_comment' ) ) {
function redirect_after_comment($location)
{
    return get_permalink().'&tab=comment';
}
   }
   add_filter('comment_post_redirect', 'redirect_after_comment');


text:
Q: Was asked to create efi partition as well as bios grub partition while manually formatting whole drive in Ubuntu 22.04 installation. Is it normal? I was running Windows 10 fresh on my pc. It was a uefi system (i think but long ago i turned secure boot off and turned on legacy bios mode in my bios settings.) I had installed and removed and reinstalled Ubuntu and several linux distros several times, sometime dual booting with windows etc. This time i wanted to fully format my hdd and install fresh Ubuntu 22.04. while installing i chose something else in the partitioning, and deleted all existing partitions, created a new partition table and created a 8gb swap and the rest I allocated to '/'. Then i was asked to create an efi partition as i was warned otherwise system might not boot. I did so but then again I was asked to flag a new partition as biosgrub. And then i was able to install. Shouldn't just efi be used for uefi based systems, or is both necessary? Earlier before i never had to create both. Also although i created 4 partions 2 separate free spaces were left, one 764 kb and on 1 mb. I couldn't include them in any partion however i tried. Is this normal?

A: Partitions to make booting possible

*

*With a GUID partition table a small partition with the bios_grub flag is necessary to boot in BIOS mode (alias CSM alias legacy mode).

*An EFI system partition (usually with FAT32 file system) is necessary to boot in UEFI mode.
If I remember correctly from my installations, Ubuntu 22.04 LTS asks for both when installing in BIOS mode, which makes it easier, if you want to switch between boot modes later on, upgrade to UEFI mode, but in principle only one of those partitions is necessary (one for each boot mode).
But when installing in UEFI mode, only the EFI system partition is created (no bios_grub partition), which was kindly remarked by user68186.
See this link: help.ubuntu.com/community/DiskSpace.
Tiny unallocated fragments on the drive
And yes, it happens rather often that tiny fragments are left before, between and after partitions. The partitions are managed (read and written) more efficiently, when they are aligned to MiB (mibibyte) positions.


text:
Q: How do I invoke a UI method from a Systems.Timers thread in C# I have a windows form application.
I am supposed a create an SQL job, and execute it. The SQL job consists of around 9 steps and takes around 4 hours to complete.
I am supposed to display the status of the SQL job, in a datagridview, so that its not necessary to go to SQL server and monitor the events.
My code is as below
 public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Thread t1 = new Thread(FirstThread);
            t1.Start();
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 500;
            timer.Enabled = true;

            timer.Elapsed += timer1_Tick;
            timer.Start();
            t1.Join();

        }
 private void FirstThread()
        {

            // Creates a job
            // Invoke the job, via a bat file

        }
 private void checkStatus()
        {
            // Checks the status of the job using the EXEC sp_helpjob @jobName='JobName'
            // Populate the status on the DataGridView
            // If the status of the job, eg.
            dataGridView1.DataSource = ds.Tables[0];
            int CurrentExecution = Convert.ToInt32(dt.Rows[0]["Current_Execution_Status"]);
            if (CurrentExecution == 4)
                label1.Text = "Job is Over";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            checkStatus();
        }

I run into CrossThread Operation Not valid error. Could anyone please let me know how to call the UI controls inside the System.Timer Thread.

A: You should call Invoke on the Control or Form:
this.Invoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });

Or BeginInvoke if you don't want to wait until the action ended:
this.BeginInvoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });


text:
Q: Reveal li-nth-child number with jquery on click I need the code to reveal the number of the nth-child list after a click on a div.
In example:

My jquery script must return me the number of nth-child i clicked. For example, if i click on mydiv2, the script must return me "2".
Thank you for helping me.

A: Is this what you mean?
$(document).ready(function() {

  $("ul li").click(function(){

  alert ($(this).index()+1);

  });
});

or when you want the div to be the clicked element:
$(document).ready(function() {

 $("ul li div").click(function(){

  alert ($(this).parent().index()+1);

 });
});

A: https://jsfiddle.net/refan/8pryo1t2/
$(document).ready(function() {
  $("ul").on("click", "div", function() {
    var index = $("div").index(this);
    alert("Index: " + index);
  });
});


text:
Q: Exclude file that matches in project folder I have several js files located in a library and some matching js files in a project folder. I want to work with these files in a gulp task.
+--project/
|  +--core/
|     |--actor.js
+--library/
   +--core/
      |--actor.js
      |--like.js

Normally, I would do something like gulp.src(['./project/**/*.js','./library/**/*.js'] and then concat or uglify as needed, but this would join both versions of actor.js in the final result. I want to exclude the library/core/actor.js file so the final result only include project/core/actor.js and library/core/like.js.
Is there anyway to exclude a file or files from the library that's present in the matching location in the project folder?

A: This should work:
const gulp = require("gulp");
const filter = require('gulp-filter');
const fs = require('fs');
const concat = require('gulp-concat');
const path = require('path');

gulp.task('default', function () {

  const filterDuplicates = filter(function (file) {

    // console.log(path.basename(file.base));  returns "project" or "library"
    // don't filter out if in "project" folder

    if (path.basename(file.base) == "project") return true;

    else {
      // make a full path but with "project" replacing "library"
      let projectTestPath = path.join(file.cwd, "project", file.relative);

      // if the the "library" file exists in the "project" path filter out
      if (fs.existsSync(projectTestPath)) return false;
    }
    return true;
  });

  return gulp.src(['./project/**/*.js', './library/**/*.js'])

    .pipe(filterDuplicates)
    .pipe(concat("concat.js"))
    .pipe(gulp.dest('dist'));
});

For a more complicated but similar question and answer, see my answer at Gulp remove duplicates if exists.


text:
Q: Equivalent for optionsAfterRender on a foreach binding in knockout In Knockout, the "options" binding has an optional argument `optionsAfterRender which is used to modify the individual option tags as they are inserted. You can find more details in the documentation.
For one of my select lists, I am having to use a foreach binding instead, because it requires a two-level binding using optgroup.
<select  data-bind="foreach: { data: availableData,
                              value: editDataId">
  <optgroup data-bind="attr: {label: groupTitle}, foreach: groups">
    <option data-bind="value: id, attr: {title: name }"></option>
  </optgroup>
</select>

However, I would also like to modify these options after binding.
There is an afterRender option for foreach, but it seems to behave very differently than optionsAfterRender. I was able to get it to execute against all the options in the select list as follows:
<select  data-bind="foreach: { data: availableData,
                              value: editDataId,
                              afterRender: doStuff">
  <optgroup data-bind="attr: {label: groupTitle}, foreach: groups">
    <option data-bind="value: id, attr: {title: name }"></option>
  </optgroup>
</select>

And then in the viewmodel
doStuff(elements, data): void {
    for (let entry of elements[1].querySelectorAll("option")) {
        ko.applyBindingsToNode(entry, {disable: true }, entry);
    }
}

(I don't really want to disable them all - it's just a simple test) - but this lead to the curious result of the entire select list not rendering at all. On inspection the nodes are still there - in the HTML and they can be traveresed and logged - but they're not appearing on the page.
This isn't because they're disabled. Something in the binding is causing the whole thing to go screwy. Is there a way I can mimic the operation of optionsAfterRender on this foreach binding?

A: Aside from fixing the un-closed foreach binding typo I also found I needed to change the option's "title" binding to "label" to get the individual option text to show up. Other than that your code seems to function as expected.

function viewModel(){
  var self = this;
  self.editDataId = 1;
  self.availableData = [
    { groupTitle: 'group1', groups: [ {id: 1, name: 'item1'}, {id: 2, name: 'item2'} ] } ,
    { groupTitle: 'group2', groups: [ {id: 3, name: 'item3'}, {id: 4, name: 'item4'} ] }
  ];

  self.doStuff = function(elements, data) {
    for (let entry of elements[1].querySelectorAll("option")) {
      ko.applyBindingsToNode(entry, { disable: true }, entry);
    }
  }
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select  data-bind="foreach: { data: availableData,
                              value: editDataId,
                              afterRender: doStuff }">
  <optgroup data-bind="attr: {label: groupTitle}, foreach: groups">
    <option data-bind="value: id, attr: {label: name}"></option>
  </optgroup>
</select>


text:
Q: How install mcrypt for PHP7.2 I want to install a script on my locahost, i installed apache2, php7.2 and mysql
The problem that i have is running this command:
phpenmod mcrypt
it ALWAYS trow the same thing when i trow it in the console:
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
WARNING: Module mcrypt ini file doesn't exist under /etc/php/7.2/mods-available
PD: SOLUTION founded(see comentary)

A: SOLUTION:
After re-installing the entire SO, in a clean instalation i made this:
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04
Then:
https://www.digitalocean.com/community/tutorials/how-to-install-and-secure-phpmyadmin-on-ubuntu-16-04
Then:
https://websiteforstudents.com/install-php-7-2-mcrypt-module-on-ubuntu-18-04-lts/
And lastly:
Enable extension for apache
echo "extension=mcrypt.so" | sudo tee -a /etc/php/7.2/apache2/conf.d/mcrypt.ini
and:
echo "extension=mcrypt.so" | sudo tee -a /etc/php/7.2/mods-available/mcrypt.ini
sudo phpenmod mcrypt
The three last steps are from:
php-mcrypt package missing in Ubuntu Server 18.04 LTS
I really thanks to Epskampie and Werner for the solution


text:
Q: Problema com acentuações no vue-json-excel Estou utilizando o vue-json-excel para exportar uma planilha do Excel (eu tenho a tabela na minha tela e uso ele para exportar os mesmos dados para excel).
Até ai, tudo funciona perfeitamente, porem, tive problemas com acentuações. Exemplo, o não, aparece Não, e assim em diante.
    <download-excel
        class   = "btn btn-default"
        :data   = "data.resultado"
        :fields = "json_fields"
        :meta   = "json_meta"
        name    = "filename.xls" style="margin-bottom: 10px;">
    </download-excel>

JS
data(){
            return{
                data: {},
                filterTerm: '',
                json_fields : {},
                json_data: [],
                json_meta: [
                    [{
                        "key": "charset",
                        "value": "utf8"
                    }]
                ]
            }
        },

Os dados estão vindo do banco, e na tela, são exibidos corretamente.
Dessa maneira, eu faço para inserir os dados do meu banco em um objeto
for(let i = 0; i < this.data.titulos.length; i++){
                        this.json_fields[this.data.titulos[i]] = "String"
                    }

JSON RETORNO
{
   "titulos":[
      "Data Emissão",
      "Data Saída",
      "CAMPO 3",
      "CAMPO 4"
   ],
   "resultado":[
      [
         "Carta Correção",
         "Não",
         "Não ",
         "09/08/2017 17:56"
      ],
      [
         "Solicita Alteração",
         "Não",
         "Não ",
         "09/08/2017 17:56"
      ],
      [
         "UM",
         464752,
         "UM ",
         "09/08/2017 17:56"
      ],
      [
         "UM",
         464752,
         "UM ",
         "09/08/2017 17:56"
      ]
   ]
}

A: O teu problema parece-me somente um erro de digitação.
Muda
"value": "utf8"

para
"value": "utf-8"

jsFiddle: https://jsfiddle.net/Sergio_fiddle/s8wemmyL/

A: Depois de muito trabalho (nem tanto) eu descobri o erro e vou deixar aqui para aqueles que passarem pelo mesmo que eu.
O modulo possui o :meta para receber os parametros, porem, quando você instala o modulo, ex: npm install --save vue-json-excel e olha no codigo fonte, voce vê que ele não recebe os parametros. E para isso, uma solução simples é...
<template>

        <slot>
            {{button_text}}
        </slot>

</template>


text:
Q: Understanding how axios works in react native so I've come across a problem today that I do not really understand.
Here it is:
So basically I have for backend a node js server with mongoDB and when I call my first component I do the following:
in the constructor I call a function that will return an array will all users except the one that is logged in
fetchUsers = () => {
        axios.get(userAPI) //Array from all users in DB
        .then((res)=>{
          for(var k = 0; k <(res.data.length); k++){
            console.log(this.state.idUser)
            if(this.state.idUser==res.data[k]._id){
                console.log("forget same user")
            }
            else
            {
              realUsers.push(res.data[k])
            }
          }
          console.log(realUsers)
        })

What I do not understand is in this function this.state.idUser is equal to the id of the user logged in, and it's not null, however when I call a second axios function in the constructor that takes for URL a link+this.state.idUser this time the state of idUser is null.
historyUsers = () =>{
       axios({
         method:'GET',
         url : urlArrayHistory+this.state.idUser
       })
       .then((response)=>{
         console.log("response de historyVote",response)
         const realUsersId = []
         for(let p=0; p<realUsers.length;p++){
           realUsersId.push(realUsers[p]._id)
         }
         for(let k = 0;k<response.data[0].historyVote.length;k++){
           if(realUsersId.includes(response.data[0].historyVote[k])){
             console.log("it's in",realUsers)
             realUsers.pop(k)
             console.log(realUsers)
           }
           else{
             console.log("ain't in")
           }
         }
       })
     }

What I want at the end is that it compares the realUsers array that are all users on my app
and the array from historyVote that are all users that the current user (the one logged in) has already met.
Thanks for any help :)
If you need more code or something let me know.
EDIT : Here is a full code of my component

  const userAPI = 'http://localhost:5050/api/new/users'
  const urlHistory = 'http://localhost:5050/api/vote/historyvote/'
  const urlArrayHistory = 'http://localhost:5050/api/vote/array/'
  const realUsers = []

const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

export default class HomeScreen extends React.Component{
    constructor(props){
        super(props)
        this.position = new Animated.ValueXY()
        this.state={
          currentIndex : 0,
          idUser : null,
          nameUser : null,
          scoreUser : null,
          currentAdverseId :"",
          currentToken : this.props.screenProps.jwt,
          readyRender : 0,
          voteHistory : [],
        }
this.infoUserAdverse = {
          name :"",
          age : "",
          Score:"",
          idAdverse :""
        }
}
retrieveId = () =>{ //Get back the Id of current logged in user from the token
      const header = {
        'authorization':'Bearer '+this.props.screenProps.jwt
      }
      console.log(header)
      axios.get('http://localhost:5050/api/posts',{
        headers : header
      })
      .then((response) =>{
        console.log(response)
        this.setState({idUser: response.data._id})
        console.log(this.state.idUser)
    })
    .catch((error)=>{
      console.log(error)
    })
  }
      historyUsers = () =>{
        axios({
          method:'GET',
          url : urlArrayHistory+this.state.idUser
        })
        .then((response)=>{
          console.log("response de historyVote",response)
          const realUsersId = []
          for(let p=0; p<realUsers.length;p++){
            realUsersId.push(realUsers[p]._id)
          }
          for(let k = 0;k<response.data[0].historyVote.length;k++){
            if(realUsersId.includes(response.data[0].historyVote[k])){
              console.log("it's in",realUsers)
              realUsers.pop(k)
              console.log(realUsers)
            }
            else{
              console.log("ain't in")
            }
          }
        })
      }
      fetchUsers = () => {
        axios.get(userAPI) //Array from all users in DB
        .then((res)=>{
          for(var k = 0; k <(res.data.length); k++){
            if(this.state.idUser==res.data[k]._id){
                console.log("forget same user")
            }
            else
            {
              realUsers.push(res.data[k])
            }
          }
          console.log(realUsers)
        })
      }

      apiFetchId = () =>
      {
        const newHeader = {
        'authorization':'Bearer '+this.state.currentToken
      }
        axios.get('http://localhost:5050/api/new/'+this.state.idUser,{
        headers: newHeader
      })
      .then((res)=>{
        console.log(res)
        this.setState({
          nameUser:res.data.name,
          scoreUser:res.data.Score,
          voteHistory:res.data.historyVote
        })
      })
      }
componentDidMount(){
        this.fetchUsers()
        this.apiFetchId()
        //this.historyUsers()
        //this.renderUsers()
    }
renderUsers = () => {
        return realUsers.map((item, i) => {
          if(i< this.state.currentIndex){
            return null
          }
          else if (i == this.state.currentIndex){
            console.log("render users cas 2")
            this.infoUserAdverse=realUsers[i]
            return (
              <Animated.View
                {...this.PanResponder.panHandlers}
                key={item._id} style={[this.rotateAndTranslate , { height: SCREEN_HEIGHT - 220, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
                  <Animated.View style={{ opacity: this.likeOpacity, transform: [{ rotate: '-30deg' }], position: 'absolute', top: 50, left: 40, zIndex: 1000 }}>
                    <Text style={{ borderWidth: 1, borderColor: 'green', color: 'green', fontSize: 32, fontWeight: '800', padding: 10 }}>++</Text>
                  </Animated.View>
                  <Animated.View style={{ opacity: this.dislikeOpacity, transform: [{ rotate: '30deg' }], position: 'absolute', top: 50, right: 40, zIndex: 1000 }}>
                    <Text style={{ borderWidth: 1, borderColor: 'red', color: 'red', fontSize: 32, fontWeight: '800', padding: 10 }}>--</Text>
                  </Animated.View>

                <Image
                  style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
                  source={{uri:"http://localhost:5050/"+item.userImage}} />
              </Animated.View>

            )
          }
          else {
            console.log("render users cas 3")
            return (
              <Animated.View
                key={item._id} style={[{
                  opacity: this.nextCardOpacity,
                  transform: [{scale: this.nextCardScale}],
                  height: SCREEN_HEIGHT - 220, width: SCREEN_WIDTH, padding: 10, position: 'absolute' }]}>
                <Image
                  style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20 }}
                  source={item.uri} />

              </Animated.View>
            )
          }
        }).reverse()
      }

      addHisotryUser =  () => {
        let urlHistory2 = urlHistory+this.state.idUser
        console.log(urlHistory2)
        axios({
          method: 'PATCH',
          url: urlHistory2,
          //headers: {authorization: 'Bearer '+this.state.currentToken},
          data: {
            userId: this.infoUserAdverse._id,
          }
        })
        .then((res)=>{
          console.log(res)
        })
        .catch((err)=>{
          console.log(err)
        })
      }

A: I think that this is due to the state being set after you start calling your Axios methods.
In the first Axios query, fetchUsers, the server is contacted first and only after a response has been received does the code look at state.idUser. In the second query, historyUsers, state.idUser is needed immediately to construct a URL, before contacting the server. The delay in fetchUsers would be enough for the state to have been set in the meantime.
Make sure that in your constructor, before you call fetchUsers or historyUsers, you have in fact already set this.state = { idUser: xxx }.


text:
Q: Are all Boolean rings semi-artinian? I'm basically only interested in the above question.  I have played with this a little bit and have not found an obvious way to prove it. However, I am not familiar with ways for proving something is semi-artinian in general (i.e. what seem to be set-theoretic methods, or discussions of the so-called socles).
If this is not generally true, is it likely to be true for the power set of the natural numbers?
Thanks for any help on this.

A: I don't believe it's true for general Boolean rings.  However, for any set $S$, $\mathscr{P}(S)$, the power-set of $S$ (as a Boolean ring) is definitely semi-artinian.  Take some element $s\in S$, and look at the image of the submodule $\{\{s\},\emptyset\}$ under any $\mathscr{P}(S)$-module homomorphism.  Its image is clearly a minimal submodule.


text:
Q: Что означается параметр isBestMatch на Binance? https://binance-docs.github.io/apidocs/spot/en/#recent-trades-list
isBuyerMaker я так понял если true то это покупка, а вот что означает isBestMatch?
GET /api/v3/trades

[
  {
    "id": 28457,
    "price": "4.00000100",
    "qty": "12.00000000",
    "quoteQty": "48.000012",
    "time": 1499865549590,
    "isBuyerMaker": true,
    "isBestMatch": true
  }
]

A: isBestMatch просто означает, что цена покупателя была согласована с продавцом
Источник: https://github.com/sammchardy/python-binance/issues/374