text:
Q: how can i use this find array and match in array in javascript? This is my data - how can I find itemId in the array.
let itemId=['001', '002', '003']
const data = [
  { id: 1, itemId: '001' },
  { id: 2, itemId: '002' },
  { id: 3, itemId: '003' },
];

This is my function in lodash but it does not work.
  _.find(data, ['itemId',{$in: itemId}])

A: Use _.intersectionWith() to get all items from data, which id appears in the itemId array:

const itemId=['001', '003'];
const data = [
  { id: 1, itemId: '001' },
  { id: 2, itemId: '002' },
  { id: 3, itemId: '003' },
];

const result = _.intersectionWith(data, itemId, ({ itemId }, id) => itemId === id);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

A: If you want to filter all the item in data array that have itemId included in Ids array, you can try available supported filter method without using lodash
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const itemIds=['001', '003'];
const data = [
  { id: 1, itemId: '001' },
  { id: 2, itemId: '002' },
  { id: 3, itemId: '003' },
];

console.log(data.filter(item=> itemIds.includes(item.itemId)));


text:
Q: Flooring a unix timestamp with timezone support I have a table, where each row has a timestamp. The timestamp is a unix timestamp. I'd like to do some reporting using this data, which requires me to group this data by a specific period (for now, let's just say day: so 86400 seconds). This can be achieved by flooring the timestamp, i.e:
mysql> set time_zone='+00:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select NOW(), FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP()/86400)*86400);
+---------------------+----------------------------------------------------+
| NOW()               | FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP()/86400)*86400) |
+---------------------+----------------------------------------------------+
| 2013-01-17 06:06:37 | 2013-01-17 00:00:00                                |
+---------------------+----------------------------------------------------+
1 row in set (0.01 sec)

This allows me to do the following data rollup:
select FROM_UNIXTIME(FLOOR(timestamp/86400)*86400) groupts, count(some_id) from table group by groupts order by groupts;

All of this works perfectly, now I'd like to compare the data with some other report, where I only have the data in a specific timezone, let's say its EST.
Unfortunately (and obviously), flooring doesn't work anymore:
mysql> set time_zone='-05:00';
Query OK, 0 rows affected (0.00 sec)

mysql> select NOW(), FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP()/86400)*86400);
+---------------------+----------------------------------------------------+
| NOW()               | FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP()/86400)*86400) |
+---------------------+----------------------------------------------------+
| 2013-01-17 01:10:38 | 2013-01-16 19:00:00                                |
+---------------------+----------------------------------------------------+
1 row in set (0.00 sec)

Which finally brings me to my question:
Is there any way to floor the timestamp based on a specific timezone? i.e, flooring will ensure all values from 00:00-23:59 in that timezone end up in a specific group?
Thanks!

A: You need to convert the time zone offset from UTC into seconds; you then need to add or subtract that offset from the Unix timestamp before dividing and multiplying, and then add it back again.
For example:
We can establish the range of UTC values for the date 2012-01-17 in timezone UTC-05:00 (US/Eastern, or America/New_York):
$ timestamp -Z -z -05:00 1358398800 1358485200
1358398800 = Thu Jan 17 00:00:00 2013 -05:00
1358485200 = Fri Jan 18 00:00:00 2013 -05:00
$ timestamp -Z -z 00:00 1358398800 1358485200
1358398800 = Thu Jan 17 05:00:00 2013 +00:00
1358485200 = Fri Jan 18 05:00:00 2013 +00:00
$

The time zone offset is -18,000 seconds from UTC (5 * 3,600), and there are 86,400 seconds in a day, of course.
We can then show with bc that the computation should be:

*

*((utc_time + tz_offset) / secs_per_day) * secs_per_day - tz_offset

For example, we can use bc to do the calculation:
$ bc
scale=0
a=1358398800
b=a+86400
c=-18000
d=86400
((a+c)/d)*d-c
1358398800
((b-1+c)/d)*d-c
1358398800
((b+c)/d)*d-c
1358485200
b
1358485200
quit
$

As you can see, the times during 2012-01-17 in the US/Eastern time zone are all grouped into the same group (demonstrated using the extreme time values).
So, as long as you can compute the offset of the time zone from UTC in seconds, with negative values for time zones west of the Greenwich Meridian and positive values for time zones east of it, then you can use the calculation shown.
SELECT NOW(), FROM_UNIXTIME(FLOOR((UNIX_TIMESTAMP() + (-18000))/86400)*86400 - (-18000));

To generalize:
FLOOR((timestamp + (offset_in_seconds))/86400)*86400 - (offset_in_seconds)

Where offset_in_seconds can be positive or negative.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Acquiring MODIS data? I am trying to figure out how to use INLA without any formal instruction and I have visited the INLA website (www.r-inla.org) to view some examples.  I have also been reading through the book Spatial and Spatio-temporal Bayesian Models with R - INLA 1st Edition by Marta Blangiardo and Michela Cameletti.  My trouble is that my questions are just too simple to get answers there and the INLA package seems too new to have thorough discussions on any programming forums that I can find.  I should also mention I am new to mapping in R.
I have seen some examples of using the MODISTools package to download subsets of data but it seems like this will download the requested data only at the point locations I specify using the lat and lon arguments of the MODISSubset command.  For the intended analysis, I will need the data available over a shape that spans a couple different tiles.  Is there a way to use a shapefile to specify the data that I would like to download in MODISTools?  The vignette didn't allude to this but maybe I misunderstood something.
Specifically, I am looking to download as much available data from the MOD13A2, MOD44W and MOD11A2 data sets as possible from the years 2011-2015.  I need this for a shapefile that would fit into a box with an upper left corner of (lat:13.891715, lon:34.957847) and a lower right corner of (lat:8.670194, lon:40.308822) which is Eastern Africa.

A: I have used the MODIS package for this task before.  Here is a sketch of the process (download, reproject, stitch):
library(raster)
library(MODIS)

# Set MODIS options: data directories, projection, resolution, etc.
dir.create(file.path("path", "to", "modis", "raw"), showWarnings = FALSE)
dir.create(file.path("path", "to", "modis", "processed"), showWarnings = FALSE)

MODIS::MODISoptions(
  localArcPath = file.path("path", "to", "modis", "raw"),
  outDirPath = file.path("path", "to", "modis", "processed"),
  outProj = "+proj=longlat +datum=WGS84 +ellps=WGS84",
  pixelSize = 1,
  dlmethod = "wget"
)

# Downloading data requires authentication and registration at https://urs.earthdata.nasa.gov/home
# Run the following command once to generate a .netrc file for EarthData (LPDAAC) login credentials
MODIS::lpdaacLogin(server = "LPDAAC")

# Download and process (stitch, reproject, dis / aggregate)
MODIS::runGdal(
  product = "MOD(13A2|44W|11A2)",
  begin = "2011-01-01",
  end = "2015-12-31",
  extent = list(xmin = 34.957847, xmax = 40.308822, ymin = 8.670194, ymax = 13.891715)
)

# list stitched MODIS products
modis.fp <- list.files(
  path = file.path("path", "to", "modis", "processed"),
  pattern = "tif$",
  recursive = TRUE,
  full.names = TRUE
)

# loading the first processed raster for demonstration
r <- raster::raster(x = modis.fp[1])


text:
Q: Htaccess mod rewrite seo url setup I have a site it was runing without seo, I changed links to seo urls.
I create seo links and save them in db.
and usaqe is : seo_url, all fine with php part but having problem with htaccess setup.
I read tons of articles and questions about htaccess setup, and after all I came to this solution which is not working correctly.
need some help espacially in Upanel pagination part. Upanel is a folder.
closest answer was that one :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^home/?$ index.php [NC,L]

RewriteRule ^contact/?$ contact.php [NC,L]

RewriteRule ^Upanel/?$ Upanel/account.php [NC,L]

RewriteRule ^Upanel/page/?$ Upanel/account.php?page=$1[L]

RewriteRule ^reset-password/?$ forgot.php [NC,L]

RewriteRule ^change-password/?$ resetpass.php [NC,L]

RewriteRule ^user/?$ login.php [NC,L]

RewriteRule ^search/?$ search.php [NC,L]

RewriteRule ^hr-search/?$ ik.php [NC,L]

RewriteRule ^sitemap/?$ rss.php [NC,L]

RewriteRule ^([a-zA-Z0-9_-]+)/?$ detail.php?p=$1 [NC,L]

RewriteRule ^category/([a-zA-Z0-9_-]+)/?$ categories.php?q=$1 [NC,L]

Thanks for helps

A: For all your listed rules, Rewrite condition (RewriteCond) is not needed.
read the comments in the example below.
RewriteEngine On
# ^home index.php :request "starts with home"(^home) redirected to index.php,
# [NC,L] search is case insensitive(ie it also matches Home,hOme etc.
# [L] stop processing after this rule.
RewriteRule ^home index.php [NC, L]
# ^Upanel/page/ request starts with Upanel/page/
# (.*)$  "everything"(.*) after it "upto end"($) is stored in $1
RewriteRule ^Upanel/page/(.*)$ Upanel/account.php?page=$1 [L]

just modified your rules.
RewriteEngine On

RewriteRule ^home/ index.php [NC,L]
RewriteRule ^contact/ contact.php [NC,L]
RewriteRule ^Upanel/$ Upanel/account.php [NC,L]
RewriteRule ^Upanel/page/(.*)$ Upanel/account.php?page=$1 [L]
RewriteRule ^reset-password/ forgot.php [NC,L]
RewriteRule ^change-password/ resetpass.php [NC,L]
RewriteRule ^user/$ login.php [NC,L]
RewriteRule ^search/$ search.php [NC,L]
RewriteRule ^hr-search/$ ik.php [NC,L]
RewriteRule ^sitemap/$ rss.php [NC,L]
RewriteRule ^([a-zA-Z0-9_-]+)/ detail.php?p=$1 [NC,L]
RewriteRule ^category/([a-zA-Z0-9_-]+) categories.php?q=$1 [NC,L]

See this.
RewriteRule ^Upanel/ Upanel/account.php [NC,L]
RewriteRule ^Upanel/page/(.*)$ Upanel/account.php?page=$1 [L]

here the second rewriteRule never work because every request which matches second condition also matched by first condition and L flag make sure it stops there at first condition. there for either of the following will work, choose with respect to your requirements.
RewriteRule ^Upanel/$ Upanel/account.php [NC,L]
RewriteRule ^Upanel/page/(.*)$ Upanel/account.php?page=$1 [L]

OR
RewriteRule ^Upanel/page/(.*)$ Upanel/account.php?page=$1 [L]
RewriteRule ^Upanel/ Upanel/account.php [NC,L]

see rewrite rule flags and answrers for order of rewrite rules


text:
Q: FileHelpers: using ReadStream bypass two records at each iteration I have a file defined like this
ID  TEXT
1   XXXX
2   XXXX
3   XXXX
4   XXXX
5   XXXX
6   XXXX
7   XXXX
8   XXXX
9   XXXX
10  XXXX

And the class for the filehelper defined like this
[DelimitedRecord("\t")]
    public class TestItem
    {
        public int Id;
        public string Text;
    }

I read the file with the following code
FileHelperEngine<TestItem> eng = new FileHelperEngine<TestItem>();
            using (var file = new FileStream("FILEPATH", FileMode.Open, FileAccess.Read))
            {
                //I've declared like this because filehelper close the reader after each iteration
                StreamReader reader = new StreamReader(file, Encoding.UTF8, false, 1024, true);
                eng.Options.IgnoreFirstLines = 1;

                TestItem[] content = null;
                bool headerRead = false;
                do
                {
                    content = eng.ReadStream(reader, 2);
                    if (!headerRead)
                    {
                        headerRead = true;
                        eng.Options.IgnoreFirstLines = 0;
                    }
                }
                while (!reader.EndOfStream);
            }

read, as you can see, 2 record each time, and ignore the firl line at the first iteration.
But at the second iteration, i'm expecting to obtain record 3 and record 4, but, instead, i receive back record 5 and 6. Why this?
How to solve this?

A: The problem is with your usage of the ReadStream function.  It is designed to read a file for the maximum number of records and then be closed.  As such, it recreates a ForwardReader on every call.
The way ForwardReader.ReadNextLine() works is to pass the current value back, and read in the next line read for processing.  So what happens is this:

*

*First call to ReadStream, first line is already read in by ForwardReader as it is created.

*currentLine is set by ForwardReader.ReadNextLine() which is the header record

*IgnoreFirst is set, so it calls ReadNextLine which in turns returns the line previously read, the updates its cache with the next line.  Thus current line becomes line 2 (ID 1) since we skipped line 1.

*We loop through each line, adding the currentLine to the arrow before updating it via ForwardReader.ReadNextLine().

*Once the maximum records is reached, we exit. At this point, currentLine is row 4 (ID 3), and the cache already has row 5 (ID 4).

So, if you were only making the one call, everything would be fine and this would be as expected.  However, because you make another call, this happens:

*

*StreamReader is already at the beginning of Line 6 since we read the rest above.

*Calling ReadStream creates a brand new ForwardReader, which in turn automatically reads the next record into its buffer, thus has row 6 (ID 5)

*Maximum records is two, so we also get row 7 (ID 6)

*At this point, we now have row 8 in the current buffer, row 9 in the cache and the streamreader is waiting at row 10.

In some regards this is a bug, but in others its your usage of ReadStream that's not really correct.  The better way would be to ditch the maximum number of records to read, and instead make use of the INotifyRead/INotifyWrite functionality if you need to process on a per record basis.


text:
Q: What character is this black cat figurine in Guardians of the Galaxy? I have a picture of Yondu's figurine collection from Guardians of the Galaxy. The black cat figurine (second from the right) is quite familiar to me, but I can't place it.
I'm pretty sure it is from an anime, a well-known one. I think the jewel in the cat's forehead was red. Can anyone recognize this guy?

A: It reminds me of this fellow from Cardcaptor Sakura, Dash:

It's colored a faint blue, this image kinda washes out that detail.

A: Eevee from Pokemon has several varieties that could match:

Espeon matches your description of a reddish gem in the forehead, while Umbreon better fits the color of the figurine (and has red eyes).  The ear shape fits Espeon better, it would seem, although who knows how accurate they're being about such things.  Each has diagonally-oriented eyes, though, rather than the horizontally-oriented eyes of that statue.
It could also be a stylized, somewhat cartoony version of an Egyptian black cat, many of which are portrayed with a third eye or a scarab on their forehead.  It's somewhat hard to tell, but this brightened GIF seems to show a golden necklace hanging just below the figure's neck:

To my eye, it seems to be a generic cat figurine which resembles several things, rather than being an actual representation of some specific character.  The other toys seem similarly generic, and it's worth noting that Yondu seeks them out for their kitschy, aesthetic quality, not because he's a fan of any particular franchise, so they don't necessarily represent anything at all.

A: It could be that you're thinking of Ryo Ohki from the Tenchi series

or a Carbuncle from the Final Fantasy series

Both of whom appear in multiple entries in their respective series (Ryo-Ohki was in every show within the Tenchi universe, and even had an eponymous series of OVAs, while Carbuncle has been a recurring summon in multiple Final Fantasy games, as well as appearing as a card, an enemy, and the name of an Airship, just to name a few). These are two takes on a common style of mythical creature, which appears to be based on the Carbuncle, which is a cat-like creature with a gemstone embedded in its forehead. This myth started with Spanish Conquistadors when they were first exploring the Americas. Versions of this creature tend to have some sort of mystical or psychic power, as legends tell that any man who tried to capture a Carbuncle for it's gem out of greed would be blinded by a ray of light from the creature or otherwise attack them, but one who has no greed and approaches the Carbuncle peacefully will be rewarded by the creature willingly handing over their gem.


text:
Q: LinQ to collection a basic question This may be too simple.Please help.
 List<Line> listLines = new List<Line>();
 foreach (Point p in currentPointsLines)
        {
            Line l = new Line();

            l.Tag = p;
            l.X1 = AnotherList[(int)p.X].CenterX;   //AnotherList is of type Rectangle
            l.Y1 = AnotherList[(int)p.X].CenterY;
            l.X2 = AnotherList[(int)p.Y].CenterX;
            l.Y2 = AnotherList[(int)p.Y].CenterY;
            listLines.Add(l);
        }

Now I would like to query this listLines collection to get another collection of lines having x co-ordinate of Tag property =1

A: Simply:
var query = listLines.Where(l => ((Point) l.Tag).X == 1);

If that's not what you're after, please clarify.


text:
Q: My Custom JTextField covered by super.paintComponent(g) method I have create a custom JTextField by extending JtextField Class and overiding paintComponent(Graphics g) method.
When I compiled and drag into a JFrame, it work normally.
But when I run it, the result is different.
My custom JTextField covered by white square that I suspect that's result of super.paintComponent(g); method.
This is my code on paintComponent() method;
@Override
protected void paintComponent(Graphics g) {
    Graphics2D gd = (Graphics2D) g.create();
    gd.setPaint(new GradientPaint(0, 0, Color.BLUE, getWidth(), 0, Color.BLACK));
    gd.fillRoundRect(0, 0, getWidth(), getHeight(), getWidth() / 2, getHeight() / 2);
    gd.dispose();
    super.paintComponent(g);
}

A: Move super.paintComponent(g) to the top of your paintComponent. This way you make sure that your custom painting is done after the superclass paintComponent has executed.

A: //Here is a example for Custom JTextfeild

1. This supports highlighting Jtextfeild with Icons.

2. This custom Jtextfeild with different fonts.

  Header Section
---------------------
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
import javax.swing.border.Border;

//Main class section

    public class CustomJTextFeild extends JTextField implements FocusListener,KeyListener{
          private Color color;
          private ImageIcon normal_icon;
          private ImageIcon hover_icon;
          private ImageIcon icon_Label;
          private boolean start_action=false;
          private String Matchtext;
          private int x0 ;

 //Constructor with input parameters
 //icon ->  normal icon
 //icon 1-> hover icon
 //text ->  initial text

     public  CustomJTextFeild(ImageIcon icon,ImageIcon icon1, String text) {

        this.normal_icon=icon;
            this.hover_icon=icon1;
            this.icon_Label=normal_icon;
            this.Matchtext=text;

            Font myFont = new Font("Segoe UI", Font.BOLD,12);
            setFont(myFont);
            Border border = UIManager.getBorder("TextField.border");
            x0 = border.getBorderInsets(new JTextField()).left;
            Border Textborder = BorderFactory.createLineBorder(new Color(0xd4d4d4 , false), 2 );
            setBorder(BorderFactory.createCompoundBorder(Textborder,
            BorderFactory.createEmptyBorder(0,5 + icon_Label.getIconWidth(), 0, 0)));
            setText(text);
            addFocusListener(this) ;
            addKeyListener(this) ;

        }

    @Override
    public void paintComponent(Graphics g) {

       int y = (this.getHeight() - icon_Label.getIconHeight())/2;
       super.paintComponent(g);
       g.drawImage(icon_Label.getImage(), x0, y, this);

    }

    @Override
    public void focusGained(FocusEvent e) {
        // TODO Auto-generated method stub
        if(e.getSource() == this && !this.start_action)
            this.setText("");

         this.icon_Label=hover_icon;
         this.repaint();
         this.revalidate();

    }
    @Override
    public void focusLost(FocusEvent arg0) {
        // TODO Auto-generated method stub
        if(!this.start_action || this.getText().length()==0)
           this.setText(this.Matchtext);

         this.icon_Label=normal_icon;
         this.repaint();
         this.revalidate();
    }
    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }
    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub
        this.start_action=true;
    }

    }

/* Output */

 JtextFeild name_Value=new CustomJTextFeild(   new ImageIcon(getClass().getResource("filename1")).getImage(), new ImageIcon(getClass().getResource("filename")).getImage(),"Name");

A: I know this question is quite old but I stumbled upon it while looking for something else and thought I would add my two cents for others who come across it.
The CAUSE: The cause of the OPs reported issue is exactly as he postulates... i.e. the behavior in the super.paintComponent(g) effectively paints over his custom painting code.
However... there is nothing really wrong with the code that he posted.  It does/will work and I must respecfully disagree with the DanD's suggested answer. Unfortunately, the OP does not include more example code so his exact issue can only be speculated.
Huh? you ask.  Then what's going on?
The FIX: Quite simply, if you want to customize the appearance of JTextField using this approach, then you must effectively tell the superclass not to paint over your custom painting. This is accomplished by setting the following property values on your component:
text.setOpaque(false);
text.setBorder(null);

In this manner, you can leave all code as-is and you are effectively telling the original paintComponent() method not to draw a background color nor draw a border.
I offer the following SSCCE as an example and solution.
Note the following:

*

*I created a static boolean 'FIXIT'. Hopefully, it goes without saying that you would not include this in "production" code; it is being used within the example to allow you to observe both behaviors.  Simply toggle its value to see "BEFORE" and "AFTER".

*More importantly (IMO), notice that I set the mentioned property values OUTSIDE of the custom code class.  I did this to more align with the way that the OP asked the question and this approach would not require a change to his custom class. However, as the comment in the code states, a more robust solution would set these values in the custom class constructor to ensure their correctness.

*I also offer a slightly more visually appealing paint method.  While it is almost identical to the original, see the comments for the tweaks made.  This is, of course, just my opinion but it is offered as an example nonetheless.
package misc;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 * An SSCCE in response to the following StackOverflow question:
 * https://stackoverflow.com/questions/13109638/my-custom-jtextfield-covered-by-super-paintcomponentg-method
 *
 * @author kansasSamurai
 *
 */
@SuppressWarnings("serial")
public class CustomTextField extends JTextField {

    private static boolean FIXIT = true;

    public static void main(String args[]) {

        SwingUtilities.invokeLater( new Runnable() {
            @Override public void run() { createAndShowGUI(); }
        } );

    }

    protected static void createAndShowGUI() {
        JFrame frame = new JFrame("SSCCE - CustomTextField");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridBagLayout());

        CustomTextField text = new CustomTextField();
        text.setText("  Ipsum Lorem  ");
            if (FIXIT) {
                // These two lines are NECESSARY...
                text.setOpaque(false);
                text.setBorder(null);
                // or!!! ... they could/should be added to the constructor(s) of your custom class

                // These two lines are OPTIONAL
                text.setForeground(Color.white);
                text.setCaretColor(Color.white);
            }
        frame.getContentPane().add(text);

        frame.pack();
        frame.setSize(330, 100); // these dimensions are "arbitrary"
        frame.setLocationRelativeTo(null); // centers the frame on screen
        frame.setVisible(true);
    }

    @Override
    protected void paintComponent(Graphics g) {
        if (FIXIT) {
            this.betterPaint(g);
            return;
        }

        final Graphics2D gd = (Graphics2D) g.create();
        gd.setPaint(new GradientPaint(0, 0, Color.BLUE, getWidth(), 0, Color.BLACK));
        gd.fillRoundRect(0, 0, getWidth(), getHeight(), getWidth() / 2, getHeight() / 2);
        gd.dispose();

        super.paintComponent(g);
    }

    protected void betterPaint(Graphics g) {
        final Graphics2D gd = (Graphics2D) g.create();

        // Improve appearance by enabling antialiasing
        gd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        gd.setPaint(new GradientPaint(0, 0, Color.BLUE, getWidth(), 0, Color.BLACK));

        // Fully rounded ends (not strictly required to fixit... just an example)
        gd.fillRoundRect(0, 0, getWidth(), getHeight(), getHeight(), getHeight());

        gd.dispose();

        super.paintComponent(g);
    }

}


text:
Q: can't add a new key into hash during iteration Can anyone explain to me what exactly mean this runtime exception?
can't add a new key into hash during iteration

I have this error in this piece of code (Im using Mongoid):
new_item_entries = []

item.entries.each do |entry|
  new_item_entries << ItemEntry.new(name: entry.field) # exception here
end

self.entries = new_item_entries
self.save

But this exception burns in NOT any cases! In my Rspec test I have 3 of 70 test fails with this exception. Most of tests use code above.


text:
Q: Need more information on xml object returned from ajax jquery call I'm using Jquery to make a call to the Weather Underground XML api. Below the function I have defined when document is ready in the browser. Pretty simple stuff. One thing I'm curious about is the xml object returned when I use the dataType set to "xml". I see a lot of examples where people call functions like returned_xml.find( ) to locate specific elements in the xml. I can't seem to locate very good documentation on the api of the xml object. Any pointers ? Thx
$(document).ready(function () {
          jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
        $.ajax(
                   {     url : "http://api.wunderground.com/api/0787878787878/geolookup/conditions/q/IA/Cedar_Rapids.xml",
                    dataType : "xml",
                    success : function(returned_xml)
                    { alert("Data is " + returned_xml.xml );
                        },
                    error  : function(failed_data)
                    {
                        alert("failed with " + failed_data);
                    }
                   });
});

A: Try this API from jquery jQuery.parseXML


text:
Q: Sort sections of a Map alphabetically I've read about sorting list alphabetically such as: Hashmap sorting, Sorting Maps
I have a Map<String, Integer> with values such as
Tarantulas, 6
Lions, 5
Snakes, 2
Zoopies, 2
Zappin, 2
Chapas, 1
Zong Zwing, 1
Chingos, 1
Chapis, 1
Grouches, 0

I need to (ONLY) sort the sections that have the same points alphabetically. This is sample data so will not know the actual values in the Map therefore need to sort based on whatever values are present. I have already grouped/sorted by values using:
 public <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
        Comparator<K> valueComparator = new Comparator<K>() {
            public int compare(K k1, K k2) {
                int compare = map.get(k2).compareTo(map.get(k1));
                if (compare == 0) {
                    return 1;
                } else {
                    return compare;
                }
            }
        };
        Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }

This is the expected result:
Tarantulas, 6
Lions, 5
Snakes, 2
Zappin, 2
Zoopies, 2
Chapas, 1
Chapis, 1
Chingos, 1
Zong Zwing, 1
Grouches, 0

So question is: How do I sort only those sections of the Map that have the same points (Integer values), and leave the rest as is?
I'm using Java 7.

A: Here is a example of how to use a comparator. After sorting you could put all the entries from the set into a LinkedHashMap to preserve the order of the elements.
public static void main(String[] args) {

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

    map.put("Tarantulas", 6);
    map.put("Lions", 5);
    map.put("Snakes", 2);
    map.put("Zoopies", 2);
    map.put("Zappin", 2);
    map.put("Chapas", 1);
    map.put("Zong Zwing", 1);
    map.put("Chingos", 1);
    map.put("Chapis", 1);
    map.put("Grouches", 0);

    SortedSet<Map.Entry<String, Integer>> sortedSet = new TreeSet<>(new Comparator<Map.Entry<String,Integer>>() {
        @Override
        public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {

            int result = o1.getValue().compareTo(o2.getValue());
            result*=-1;
            if(result==0)
                result = o1.getKey().compareTo(o2.getKey());

            return result;
        }
    });

    sortedSet.addAll(map.entrySet());

    for(Entry<String, Integer> entry:sortedSet)
        System.out.println(entry.getKey()+"="+entry.getValue());

}

A: Try:
public <K  extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
    Comparator<K> valueComparator = new Comparator<K>() {
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) {
                return k1.compareTo(k2); // <- To sort alphabetically
            } else {
                return compare;
            }
        }
    };
    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}


text:
Q: How to add Input Field Inside Data table I'm using the following method to show multiple mat-cell using *ngFor:
columns = [
    { columnDef: 'qty', header: 'Qty', cell: (row: SaleItem) => `${row.quantity}` },
    { columnDef: 'discount', header: 'Discount', cell: (row: SaleItem) => `${row.discount}` }
  ];

  salesItemsDisplayedColumns = this.columns.map(x => x.columnDef);

html file :
<mat-table [dataSource]="salesItemsDataSource">
    <ng-container *ngFor="let column of columns" [matColumnDef]="column.columnDef">
              <mat-header-cell *matHeaderCellDef>{{ column.header }}</mat-header-cell>
              <mat-cell *matCellDef="let row">
                {{column.cell(row)}}
              </mat-cell>
    </ng-container>
<mat-header-row *matHeaderRowDef="salesItemsDisplayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns:salesItemsDisplayedColumns"></mat-row>

</mat-table>

Now inside the mat-cell I dont' want to display the object properties but I want to include an <input> like follows :
<mat-cell *matCellDef="let row">
    <input type="text" [(ngModel)]="column.cell(row)">
</mat-cell>

I want to have something like this but where the inputs are mapped with my objects.


text:
Q: Derivation of telegrapher's equations I'm currently going over the derivation of the telegrapher's equations shown here, but there's a step that I'm not fully grasping.
I think I can follow some of how you get from eq.3 to eq.5:
If the current through the inductor is a sinusoid given by:
$$i(t) = Isin(\omega t + \theta)$$
Substituting this into eq.3 gives:
$$j\omega L.I(z)$$
Similarly, $$R.i(z,t)$$ becomes $$R.I(z)$$
Putting this together gives the RHS of eqn. 5:
$$-(R+j\omega L).I(z)$$
However, I simply don't understand how going from eq.3 to eq.5 the other term
gets from:
$$\frac{\partial v(z,t)}{\partial z}$$
to:
$$\frac{dV(z)}{dz} $$
If anyone can help explain in more detail what happens during the "Simplify equations 3 and 4 using Cosine phasors." step that would be much appreciated.

A: A better way to look at it is through the Fourier transform, which is what using phasors does indirectly. Hence
$$\int_{-\infty}^\infty \frac{\partial v}{\partial z} e^{-j\omega t} \ \mathrm{d}t = \frac{\partial}{\partial z} \int_{-\infty}^{\infty} v(z, t) e^{-j\omega t} \ \mathrm{d} t = \frac{\partial V}{\partial z} (z, \omega),$$
where \$V(z, \omega)\$ is the Fourier transform of \$v(z, t)\$. Looking at a single frequency \$\omega_0\$ yields
$$\frac{\partial V}{\partial z}(z, \omega_0) = \frac{\mathrm{d} V_{\omega_0}}{\mathrm{d} z} (z),$$
where \$V_{\omega_0} = V(z, \omega_0)\$ is a single variable function that depends only on \$z\$.

A: The idea of Phasors is that we can represent sines and cosines in terms of exponentials (\$e^{jx}\$) by using the relation given in Euler's formula:
$$
cos(x) + \textbf{j}sin(x) = e^{jx}
$$
Where:
$$
Im\left\{ e^{jx} \right\} = sin(x)
$$
and:
$$
Re\left\{ e^{jx} \right\} = cos(x)
$$
When they say using "cosine phasors" they imply a cosine convention where it is assumed you are taking the Real part of the function as done above.
For example if we have a co-sinusoidal time varying voltage represented by:
$$
V(t,z) = V_ocos(\omega t + \beta z)
$$
We can represent that as:
$$
V(t,z) = Re\left\{V_o e^{j(\omega t + \beta z)}  \right\} = Re\left\{V_oe^{j \beta z} e^{j\omega t}  \right\}
$$
Where:
$$
V_oe^{j\beta z} = V_o\angle \theta \ \ _{(\beta z = \theta)}
$$
is the phasor, which as you can see only varies with respect to \$z\$. The background assumption of course, is that you can add, subtract, multiply, or divide this phasor with any other phasors derived with the same "cosine convention" and plug that resulting phasor back into the template:
$$
Re\left\{[\ \ \ \ \ ] e^{j\omega t}  \right\}
$$
and you would get back the proper time varying non-phasor function.
So since the whole idea behind phasors is that we can get rid of the time varying component, do whatever operations we need, and re-introduce the time component at any point if needed, it makes sense that time \$t\$ is no longer a variable in the phasor representation.
Edit: did I misinterpret the question or state something incorrect in my answer? I wish people would leave suggestions with their downvotes.


text:
Q: Which Wine DLLs should I *not* overwrite with the real thing? I have a legit installation of Windows XP and dual boot with Ubuntu (currently Karmic).  WineHQ says it's possible to use DLLs from a real installation of Windows in place of "DLLs that Wine does not currently implement very well".
So I'd like to just create softlinks that point to all of the DLLs in my real Windows System32 folder, under the theory that this would help things function better and behave in a less buggy, more native way.
But should I go as far as replacing the Wine DLLs with the real ones?  If so, are there any DLLs that need to remain the way they are for compatibility with the Linux world?  Which ones are safe to replace?
Also, how would this conflict/intersect with running Winetricks?

A: While you probably could replace the WINE dlls, there really is no way to determine which you can replace unless you are a developer for the Wine project.  In most cases the DLLs will run just fine, by shaking up the system you are more likely to solve bugs than to solve your problems.
If you notice a particular program is having difficulty then you may want to determine where in the program the problem is happening then try to figure out WHICH dll it is that could be possibly related to the problem, then try a soft link and see if it fixes the issue.
I would stick with what Wine explicitly recommends, if replacing the dlls worked and made an improvement Wine would recommend it themselves.

A: gdi32.dll, kernel32.dll, and user32.dll are the lowest-level Windows libraries, and as such should not be used to replace the equivalents in wine since they will be the ones to primarily talk with the underlying OS.
wsock32.dll does TCP/IP handling, so should be left alone as well.

A: http://appdb.winehq.org/
The AppDB lists out modifications required for every program that works under Wine. So, for the application which isn't running natively, just check with AppDB and replace DLLs accordingly..


text:
Q: Android: Send e-mail with attachment automatically in the background I am making an app that allows the user to take a picture and send it automatically via email to the email he chooses. So far I was able to take a picture and store in the SD card. Now I only need functions that get the picture from the folder (/sdcard/Pictures/PhotoSender/) and send automatically to the e-mail the user has requested. How can I do this?
I have the picture in that folder. I just need some functions to generate the e-mail, put the picture (.jpg) as an attachment and send (all this on background). When the e-mail gets totally sent, a toast should pop up saying "Upload Done". Meanwhile the user should be free to take more pictures, so the uploading requests should be put on a queue. The user shouldn't login with his e-mail account to send. If needed, I can create an e-mail account for my app to be the "sender". Please help me!

A: Assuming your device of emualtor has a email application, the below code can be used to sent a mail. You can use any email application installed on your emualtor or device be it yahoomail or google. If you want tp run the same in background use a service.
Intent i = new Intent(Intent.ACTION_SEND);
//i.setType("text/plain"); //use this line for testing in the emulator
i.setType("message/rfc822") ; // use from live device
i.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail");//sending email via gmail
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"test@gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT,"subject goes here");
i.putExtra(Intent.EXTRA_TEXT,"body goes here");
startActivity(i);

A: Below is a complete class that supports sending emails with attachments in Android
And here is a utility function to send mail with attachment where the attachment in your case is simply the picture(s) file complete path
public static boolean sendEmail(String to, String from, String subject,
                               String message,String[] attachements) throws Exception {
    Mail mail = new Mail();
    if (subject != null && subject.length() > 0) {
        mail.setSubject(subject);
    } else {
        mail.setSubject("Subject");
    }

    if (message != null && message.length() > 0) {
        mail.setBody(message);
    } else {
        mail.setBody("Message");
    }

    mail.setTo(new String[] {to});

    if (attachements != null) {
        for (String attachement : attachements) {
            mail.addAttachment(attachement);
        }
    }
    return mail.send();
}

Here is the complete Mail class that is used in the above function
import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Mail extends javax.mail.Authenticator {
private String user;
private String password;

private String[] to;
private String from;

private String port;
private String sport;

private String host;

private String subject;
private String body;

private boolean _auth;

private boolean _debuggable;

private Multipart multipart;

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String[] getTo() {
    return to;
}

public void setTo(String[] to) {
    this.to = to;
}

public String getFrom() {
    return from;
}

public void setFrom(String from) {
    this.from = from;
}

public String getHost() {
    return host;
}

public void setHost(String host) {
    this.host = host;
}

public String getSubject() {
    return subject;
}

public void setSubject(String subject) {
    this.subject = subject;
}

public Multipart getMultipart() {
    return multipart;
}

public void setMultipart(Multipart multipart) {
    this.multipart = multipart;
}

public Mail() {
    host = "smtp.googlemail.com"; // default smtp server
    port = "465"; // default smtp port
    sport = "465"; // default socketfactory port

    user = ""; // username
    password = ""; // password
    from = ""; // email sent from
    subject = ""; // email subject
    body = ""; // email body

    _debuggable = false; // debug mode on or off - default off
    _auth = true; // smtp authentication - default on

    multipart = new MimeMultipart();

    // There is something wrong with MailCap, javamail can not find a
    // handler for the multipart/mixed part, so this bit needs to be added.
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap
            .getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);
}

public Mail(String user, String pass) {
    this();

    this.user = user;
    password = pass;
}

public boolean send() throws Exception {
    Properties props = _setProperties();

    if (!user.equals("") && !password.equals("") && to.length > 0
            && !from.equals("") && !subject.equals("") && !body.equals("")) {
        Session session = Session.getInstance(props, this);

        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(from));

        InternetAddress[] addressTo = new InternetAddress[to.length];
        for (int i = 0; i < to.length; i++) {
            addressTo[i] = new InternetAddress(to[i]);
        }
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

        msg.setSubject(subject);
        msg.setSentDate(new Date());

        // setup message body
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body);
        multipart.addBodyPart(messageBodyPart);

        // Put parts in message
        msg.setContent(multipart);

        // send email
        Transport.send(msg);

        return true;
    } else {
        return false;
    }
}

public void addAttachment(String filename) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(new File(filename).getName());

    multipart.addBodyPart(messageBodyPart);
}

@Override
public PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(user, password);
}

private Properties _setProperties() {
    Properties props = new Properties();

    props.put("mail.smtp.host", host);

    if (_debuggable) {
        props.put("mail.debug", "true");
    }

    if (_auth) {
        props.put("mail.smtp.auth", "true");
    }

    props.put("mail.smtp.port", port);
    props.put("mail.smtp.socketFactory.port", sport);
    props.put("mail.smtp.socketFactory.class",
            "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    return props;
}

// the getters and setters
public String getBody() {
    return body;
}

public void setBody(String _body) {
    this.body = _body;
}
}

Note:

*

*You will need activiation.jar and mail.jar in your classpath i.e. JavaMail API

*The code should run from AsynchTask or dedicated Thread


text:
Q: Wordpress REST API calls that depend on the Wordpress User I have a Wordpress site, and I have another server.
People login into the wordpress site, then at a later stage browse the other server. On the other server page, there are JS fetch requests getting information from the Wordpress REST API. I wish for the Wordpress server to return different results depending on which Wordpress user they are.
I can hook into wp_login, e.g.
<?php
function login_server_aswell( $user_login, $user ) {
    // tell server user loggin in, get session token back
    // Now can't store the session token in a place where when they browse to the server webpage it can see the cookie
}
add_action('wp_login', 'login_server_aswell', 10, 2);
?>

The problem I have, is after I login, I could tell the other server, this user logged in, give me a sessions token. But then I could only store that session token in a cookie under the wordpress site, not under the servers site, because cookies are not cross site.
Any concepts or overall guidance that can point me in the right direction?

A: You could hook into the login process in the WP site and create a unique token (stored in meta) for that user on login. The token can then be sent to the other server, that could query the WP API with that token.
You would have to create a custom endpoint that validates the user token. Probably best to have some hash for the userid also.
Furthermore, on logout from the WP site or in some token validation cronjob, this token has to be invalidated for security purpose. Even better, if it's just one request from the 'other' server, invalidate immediately and if on the WP server again, create a new token. So in effect, it's a CSRF token (nonce) over multiple servers.


text:
Q: MonoTouch: Application windows are expected to have a root view controller at the end of application launch Please note, unlike similar questions in the past, this issue is for IOS 6 and I am not calling window.AddSubview (navigation.View) which was documented in past answers.
When I launch my app in the simulator it opens and the message below is displayed in the Application Output window.  I am running: Monotouch: 6.0.10, xcode 4.6

Application windows are expected to have a root view controller at the
  end of application launch

    [Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
    UIWindow window;
    ProductXchangeViewController viewController;
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        window = new UIWindow (UIScreen.MainScreen.Bounds);
        viewController = new ProductXchangeViewController ();
        window.RootViewController = viewController;
        window.MakeKeyAndVisible ();
        return true;
    }

}

A: Are you sure this completes in a timely manner? You have iirc 17 seconds to return from FinishedLunching.

A: I re-implmented my user interface in a new UIViewController xib and did not change FinishedLaunching() or any other code and it worked.
XCode must have introduced a problem in the xib file.


text:
Q: Spring data JPA - Map object returned from native query to a POJO I have scenario where I want to mapped data fetched from native query in a JPA repository to custom object.
My repository code is as follows:
@Query(nativeQuery = true,name = "TopCouponOffer")
List<TopCouponOffer> findTodayTopOffer(@Param("date") String date, @Param("time") String time);

My custom class code is as follows:
@NamedNativeQuery(
    name = "TopCouponOffer",
    query =
           "SELECT c.id,c.code\n" +
                   " FROM COUPON c \n" +
                   "JOIN CLICK cl\n" +
                   "ON cl.coupon_id = c.id\n" +
                   "JOIN COUPONS_STATUS cs\n" +
                   "ON cs.id= c.coupons_status_id\n" +
                   "JOIN COUPONS_OFFER_TYPE ct\n" +
                   " ON ct.id= c.coupons_offer_types_id\n" +
                   "WHERE\n" +
                   " c.ongoing_offer = 1 AND\n" +
                   " c.coupons_status_id != 4 AND\n" +
                   "IF(:date < c.end_date,\n" +
                   "             IF(:date < c.start_date,\n" +
                   "                 0,\n" +
                   "                 IF(:date = c.start_date,\n" +
                   "                     IF(:time < c.start_time,\n" +
                   "                         0,\n" +
                   "                         1),\n" +
                   "                     1)),\n" +
                   "             IF(:date = c.end_date || :date = c.start_date, \n" +
                   "                IF(:time > c.end_time || :time < c.start_time,\n" +
                   "                         0,\n" +
                   "                         1), 0)) = 1 ORDER BY cl.count DESC LIMIT 2",
    resultSetMapping = "TopCouponOffer",
    resultClass = TopCouponOffer.class
)
@SqlResultSetMapping(name="TopCouponOffer",
        classes = {
        @ConstructorResult(targetClass = TopCouponOffer.class,columns = {
                @ColumnResult(name = "id"),
                @ColumnResult(name = "code")
        })
        }
)
public class TopCouponOffer {
    Integer id;
    String code;
    public TopCouponOffer(Integer id, String code){
       this.id=id;
       this.code=code;
   }
}

But I am getting the following error when running the application

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findTodayTopOffer found for type Coupon!

Should I moved name query and sqlresultmapping to my entity class? Thing is that I don't wanna pollute my entity class is there any way I can achieve that with adding more code to my entity class?

A: I believe your functionname in the repository should be renamed to findByDateAndTime.


text:
Q: Express Invalid CSRF Token Inside Table Actions Button I'm having issues with CSRF token on Handlebars each loop. I generated a data table with each loop but i can't submit delete button. The CSRF only work on submit for new data(POST) and submit for update data(PUT). Here is my setup:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var passport = require('passport');
var flash = require('connect-flash');
var validator = require('express-validator');
var override = require('method-override');

var routes = require('./routes/index');
var userRoutes = require('./routes/user');
var itemRoutes = require('./routes/item');

var app = express();

// connect to mongodb
mongoose.Promise = global.Promise;
mongoose.connect('localhost:27017/toolswatcher');
require('./config/passport');

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
app.engine('.hbs', expressHbs({
    defaultLayout: 'layout',
    extname: '.hbs',
    helpers: {
        counter: function(index) {
            return index + 1;
        }
    }
}));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(validator());
app.use(session({
    secret: '234234sda',
    resave: false,
    saveUninitialized: false,
    store: new MongoStore({
        mongooseConnection: mongoose.connection
    }),
    cookie: { maxAge: 100 * 60 * 1000 } // minutes * seconds * milis
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(override(function (req, res) {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        // look in urlencoded POST bodies and delete it
        var method = req.body._method;
        delete req.body._method;
        return method;
    }
}));
app.use(express.static(path.join(__dirname, 'public')));

[...]

Route item.js
    var express = require('express');
    var router = express.Router();
    /*CSRF protection*/
    var csrf = require('csurf');
    var csrfProtection = csrf();
    router.use(csrfProtection);

    var Item = require('../models/item/item');

    /* GET items listing */
    router.get('/', isLoggedIn, function(req, res, next) {
        session_store = req.user.username;
        Item.find({}, function (err, item) {
            if (err) return console.error(err, res);
            res.render('item/index', {items: item, csrfToken: req.csrfToken()});
        }).select('item_id item_name description stock image_path');
    });

    /* Delete item by ID*/
    router.delete('/delete/:id', isLoggedIn, function (req, res, next) {
        Item.findById(req.params.id, function (err, item) {
            item.remove(function (err, item) {
                if(err) return console.error(res, err);
                console.log('DELETE removing ID: ' + item._id);
                res.redirect('/item');
            });
        });
    });

And my view:

Data Items

             New Item

            <input type="text" class="form-control" id="searchItem" onkeyup="searchTableItem()" placeholder="Search item name..">

                No.
                Item ID
                Item Name
                Descriptions
                Stock
                Action

                {{#each items as |item key|}}

                    {{ counter @key }}
                    {{ item.item_id }}
                    {{ item.item_name }}
                    {{ item.description }}
                    {{ item.stock }}

                            <form action="/item/delete/{{item._id}}" method="post">
                                <input type="hidden" name="_csrf" value="{{ csrfToken }}">
                                <input type="hidden" name="_method" value="DELETE">
                                <button class="btn btn-danger btn-xs" type="submit">

                                </button>
                            </form>

               {{/each }}

I've added the hidden input field for the csrfToken but it doesn't work, it's always showing invalid csrf token every time i click delete button. I don't know why the token not accessible inside the loop, but if i print the csrfToken outside the loop, it works, the token printed on the page.

A: Your csrfToken is currently being passed as " ".... nothing. In order to fix this instead of {{csrfToken}} type in {{../csrfToken}}.
Answer Edited Reason: Easier solution found.


text:
Q: use oracle extract regular expression match the last appeared year in result I have some record like these:

1995,no.4-6;1996,no.1,4
1977,no.1-2;1978,no.1-3;1979,no.1-4

I want to extract last appeared year in those record. eg. 1996 in first record, 1979 in second record. I use

regexp_substr(record, '\d{4}')

but I only get the first appeared year in each record. How could I get the last appeared year?

A: [0-9]{4}[^;]*$

You can try this regex.you can extract the the \d{4} from this.See demo.
http://regex101.com/r/yA5iD9/2

A: It should be a simple SUBSTR and INSTR implementation.
SQL> WITH DATA AS
  2    ( SELECT q'[1995,no.4-6;1996,no.1,4]' str FROM dual
  3    UNION ALL
  4    SELECT q'[1977,no.1-2;1978,no.1-3;1979,no.1-4]' FROM dual
  5    )
  6  SELECT SUBSTR(str, instr(str, ';', -1, 1)+1, 4) lst_yr
  7  FROM DATA
  8  /

LST_
----
1996
1979

SQL>


text:
Q: rlimit64 integer overflow I'm currently trying to limit the memory resources of the process. Before to do so, I prepare the rlimit64 structure calling getrlimit64. When compiling the following code
    rlimit64 as_limit;
    if (getrlimit64(RLIMIT_AS, &as_limit) == 0)
    {
        std::cerr << as_limit.rlim_cur << std::endl;
        std::cerr << as_limit.rlim_max << std::endl;

        as_limit.rlim_cur = 0x040000000 * 16;

        std::cerr << as_limit.rlim_cur << std::endl;
        std::cerr << as_limit.rlim_max << std::endl;
    }

I'm getting a warning about integer overflow for the line with an assigment of as_limit.rlim_cur. Hovever, as an output I get:
    18446744073709551615
    18446744073709551615
    0
    18446744073709551615

How is this possible?

A: The hex literal is being interpretted as an int.
Try using:
0x040000000LL * 16;

So that the compiler treats the literal as a long long.
Since a long long literal (the LL suffix) is C99, you're likely better off casting to whatever the type of the struct member is (though I would imagine any recent compiler would have support for LL -- gcc definitely does).  For example, you could cast to long long.


text:
Q: asp.net cache within httpcontext I want to cache objects being pulled from a database that do not often get modified, because every time the page loads nearly 2000 items are selected, causing a noticable performance issue during page load.
After review  here   and a few MSDN articles (most relevant is  here) it seems that these are solutions to prevent a single user from making multiple roundtrips to the database, and that this cache will expire once the httprequest is closed.
Can any one clear the confusion, providing an applicable reference if found?

A: You want to store the items in HttpRuntime.Cache items will exist in here for the duration of your app domain, they expire, or are scavenged. Which ever happens first. Note this is exactly the same as HttpContext.Current.Cache which points to HttpRuntime.Cache. Invoking the later is easier to work with in service layers since you don't have to be concerned about whether a context exists or not. The cache always exists.
Items stored in HttpContext.Current.Request.Items will only exist for the duration of that request. This is useful for storing single request information that could be read / wrote through multiple layers of your application.


text:
Q: Xcode constraints for iPhone5 messing me up I'm trying to do a thing that seems easy but since the new auto layout in xcode I having a hard time to understand what's going on with the constraints.
The thing I want to do is 2 subviews in a main view
basically one scrollview at the top and one uiview at the bottom with no space in between
on iPhone 5 I want it to be
400px
148px
and on iPhone 4 :
358px
112px
Each time I'm adding a constraint one other disappear or an other one doesn't allows me to change the height
I don't know if this is explainable or what but any help is welcome

A: I hate the new AutoLayout in Interface Builder. The first thing I do is disable it. Just disable it by clicking on File's Owner > Show File Inspector, then untick Use AutoLayout.

A: The problem I found about Auto Resizing and Size Classes is that the purpose of them is to handle complex UI layouts, so:

*

*If the UI you're building is as simple as the apps that shipped by Apple, you don't have to use them to get things work on all devices;

*If the UI is really complicated, you'll end up with so many constraints that in the end no one is able to figure out what is what. It is fine until there's some huge requirement change to be made with a tight deadline, then the only solution will be work over time.

It is quite pleasant to build something using Auto Layout with fixed design, it's such an elegant way that everything seems to be in the right place, and totally under your control, and you don't need to write any code at all. But as long as changes have to be made, figuring out the relations between all the constraints is harder than reading code.
For some really complicated layout for multiple devices, the new technology may be a must, but I suppose there's still room for a lot of useful apps that only uses autoresizing mask and code. It may be a bit shameful to say so, but basically, I hate auto layout.

A: If you want fixed heights for the constraints. Just select your elements in the interfacebuilder, and add height-constraints manually. (The little plus-sign at the bottom, and then height).
Just make outlets to these constraints and manipulate their constant-values if you want fixed heights.


text:
Q: Controlling the submit behaviour of an ImageButton in ASP.NET I have a image button in a page which can be triggered on mouse click, by default it gets triggered on enter press also which i want to disable.
how to make the submit behaviour of the aspx:image button false

A: try this:
 $(function(){
        $('#<%=imgBtn.ClientID%>').keydown(function(e){
            if(e.which==13)
            {
                 return false;
            }
        });
    });


text:
Q: Bad Gateway 502 Connection Refused Nginx, Docker Compose and Keycloak I'm having trouble configuring Nginx and Keycloak together with docker-compose. I keep receiving 502 Bad Gateway error when trying to access the Keycloak dashboard behind Nginx reverse proxy.
Here is my docker-compose.yaml file
# Docker Compose file Reference (https://docs.docker.com/compose/compose-file/)

version: '3.8'

services:

  nginx:
    image: my-nginx-image
    ports:
      - "80:80"
    depends_on:
      - db-keycloak
      - keycloak
    restart:
      always
    networks: # join the backend and frontend network
      - backend
      - frontend

  # Keycloak Service (Auth Server)
  keycloak:
    image: jboss/keycloak:15.0.0
    restart: always
    depends_on:
      - db-keycloak
    environment:
      DB_VENDOR: postgres
      DB_ADDR: db-keycloak
      DB_DATABASE: keycloak
      DB_USER: ${KEYCLOAK_DB_USER}
      DB_PASSWORD: ${KEYCLOAK_DB_PASSWORD}
      KEYCLOAK_USER: ${KEYCLOAK_ADMIN_USER}
      KEYCLOAK_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD}
      PROXY_ADDRESS_FORWARDING: "true"
    command: ["-Djboss.http.port=8100"]
    ports:
      - 8100:8100
    networks: # join the backend and frontend network
      - backend
      - frontend # commenting out this line somehow resolves my issue

  # Keycloak Database Service
  db-keycloak:
    image: postgres:latest
    ports:
      - "5432:5432"
    restart: always
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: ${KEYCLOAK_DB_USER}
      POSTGRES_PASSWORD: ${KEYCLOAK_DB_PASSWORD}
    networks:
      - backend # join the backend network only
    volumes:
      - db-keycloak-data:/var/lib/postgres # persist keycloak db data

# Volumes
volumes:
  db-keycloak-data:

# Networks for the backend and frontend
networks:
  backend:
  frontend:

I'm using a custom Nginx image built from the following Dockerfile:
FROM nginx

expose 80

COPY ./default.conf /etc/nginx/conf.d/default.conf

CMD ["nginx", "-g", "daemon off;"]

The default.conf file is:
upstream keycloak {
    server keycloak:8100;
}

server {
    listen 80;

    # keycloak
    location /auth {
        proxy_pass http://keycloak/auth;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }

    location /auth/admin {
        proxy_pass http://keycloak/auth/admin;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $server_name;
    }

}

I've disabled SSL in Keycloak, and I'm running keycloak on port 8100 because another container is using 8080 (I've excluded some of the irrelevant config for my other images, just note that I have other services running on the backend and frontend networks). The problem I'm having is that when I try to access the Keycloak dashboard at /auth I am greeted with a 502 Bad Gateway page. However, if I remove the keycloak service from the frontend network, I can access the dashboard just fine (like the following):
networks: # only join the backend network
   - backend

This is the output from the Nginx when I try to navigate to the page:
2022/01/07 17:27:52 [error] 31#31: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 94.10.13.254, server: , request: "GET /auth HTTP/1.1", upstream: "http://172.18.0.4:8100/auth", host: "my-ec2-instance.eu-west-2.compute.amazonaws.com"

Running docker container inspect on the Keycloak container I can see that the IP 172.18.0.4 does match so it seems to be forwarding the request to the correct container address, and Nginx and Keycloak are both on the same network. Could this be an issue with my docker compose file configuration or maybe with Keycloak refusing the connection for another reason? Is there something I'm missing. Let me know if there is any other info I should include.


text:
Q: Grabbing all files in a query using Python I'm processing a large amount of files using Python. Data related to each other through their file names.
If I was to perform CMD command to perform this (in windoes) it would look something like:
DIR filePrefix_??.txt

And this would return all the file names I would need for that group.
Is there a similar function that I can use in Python?

A: Have a look at the glob module.
glob.glob("filePrefix_??.txt")

returns a list of matching file names.


text:
Q: Understanding how spark applications use dependencies Let's say that we have spark application that write/read to/from HDFS and we have some additional dependency, let's call it dep.
Now, let's do spark-submit on our jar built with sbt. I know that spark-submit send some jars (known as spark-libs).  However, my questions are:
(1) How does version of spark influence on sent dependencies? I mean a difference between spark-with-hadoop/bin/spark-submit and spark-without-hadopo/bin/spark-submit?
(2) How does version of hadoop installed on cluster (hadoop cluster) influence on dependencies?
(3) Who is responsible for providing my dependency dep? Should I build fat-jar (assembly) ?
Please note that both first questions are about from what HDFS calls come from (I mean calls done by my spark application like write/read).
Thanks in advance

A: spark-without-hadoop refers only to the downloaded package, not application development.
The more correct phrasing is "Bring your own Hadoop," meaning you still are required to have the base Hadoop dependencies for any Spark application.

Should I build fat-jar (assembly) ?

If you have libraries that are outside of hadoop-client and those provided by Spark (core, mllib, streaming), then yes


text:
Q: How do I make an animation not reset the position of the object? I was trying to make an animation in which the object at hand moves to the right a certain amount. However I discovered that if I animate the object at -3 and make it move to -1.5, whenever the animation is executed, the object flies back to -3 and goes to -1.5, instead of moving 1.5 units to the right (that's probably how it's supposed to work). How do I make an object move 1.5 units to the right using the Unity animation system, regardless of current position?

A: The simplest way to make animation do "relative" motions is to attach your object to a parent object. This way the object animates relative to its parent's transform.


text:
Q: How exception-safe is std::tie? std::tie returns a tuple of references, so you can do the following:
int foo, bar, baz;
std::tie(foo, bar, baz) = std::make_tuple(1, 2, 3);

This is similar to foo, bar, baz = (1, 2, 3) in Python.
What is supposed to happen if one of the assignments throws, as in the following example?
int foo = 1337;
struct Bar {
    Bar& operator=(Bar) { throw std::exception{}; }
} bar;
try {
    std::tie(foo, bar) = std::make_tuple(42, Bar{});
} catch (std::exception const&) {
    std::cout << foo << '\n';
}

Will it print 1337 or 42, or is this unspecified?

A: The Standard speaks of tuple assignment art §20.4.2.2 [tuple.assign], the only mention of exception is that the assignment should not throw unless one of the elements assigned to throws.
Since there is no mention of the order in which elements are assigned to, it is thus unspecified.


text:
Q: twig: take an api and print it in html i am using grav, and with twig i have an html file like this:

            01

            title

            date

            author

then I have this API: https://5efc440acf235d0016ad72be.mockapi.io/api/floating-point/floating-point
I want to take the data from that api (date, author etc) and print it inside the corresponding html div

A: Fetch the data and transform the JSON to an array, then pass it to your view, e.g.
$api_data = json_decode(file_get_contents('https://5efc440acf235d0016ad72be.mockapi.io/api/floating-point/floating-point'), true);

title

date

author

{% for row in api_data %}

{{ row.title }}

{{ row.date }}

{{ row.author }}

{% endfor %}


text:
Q: Golang: Multidimensional array using slice of slice strategy resulting in strange output I am using following simple code for 2d array in golang, where APPEND function is resulting in Duplicate values rather than appending.
package main

import "fmt"

func main() {
    var n int
    fmt.Scanf("%d", &n)
    array := [][]int{}
    row := make([]int, n)
    for _, _ = range row {
        for j, _ := range row {
            fmt.Scanf("%d", &row[j])
        }
        fmt.Println("Printing current Row", row)
        array = append(array, row)
        fmt.Println("Printing curent Array", array)
    }
    fmt.Println("Final Array", array)
}

But Strangely this are not going unexpectedly.
If suppose i want this thing to happen(input)
2
1 2
3 4

and i run this program i get this in return
2     //Dimension for matrix
1     //Iteration one begins
2
Printing current Row [1 2]
Printing curent Array [[1 2]]
3     //Iteration two begins
4
Printing current Row [3 4]
Printing curent Array [[3 4] [3 4]]
Final Array [[3 4] [3 4]]

I am not getting reason that why APPEND function is resulting in duplicating entries .
There by want to know how to correct this also underlying CONCEPT

A: This behaviour is occurring because you are not adding a new row slice to your array. Each iteration simply reads into the same row slice overriding previous values. Try below:
func main() {
    var n int
    fmt.Scanf("%d", &n)
    array := [][]int{}

    for i := 0; i < n; i++ {
        row := make([]int, n) // create a new slice to add next row values
        for j, _ := range row {
            fmt.Scanf("%d", &row[j])
        }
        fmt.Println("Printing current Row", row)
        array = append(array, row)
        fmt.Println("Printing curent Array", array)
    }
    fmt.Println("Final Array", array)
}

A: use new slice for each iteration of the first loop, and check for the errors:
you read new data to the old same slice, this is why you have duplicated data.
if you want to use append first create array with zero length and cap n:
array := make([][]int, 0, n)
then change your first loop to: for i := 0; i < n; i++ {
and inside this loop make new slice: row := make([]int, n)
2 way:
using append (without fmt.Scan error checking):
package main

import "fmt"

func main() {
    n := 0
    fmt.Scan(&n)
    slice := make([][]int, 0, n)
    for i := 0; i < n; i++ {
        row := make([]int, n)
        for j, _ := range row {
            fmt.Scan(&row[j])
        }
        slice = append(slice, row)
    }
    fmt.Println(slice)
}

without using append  read to s[i][j] (with error checking):
package main

import "fmt"

func main() {
    var n int
    if m, err := fmt.Scan(&n); m != 1 {
        panic(err)
    }
    s := make([][]int, n)
    for i := 0; i < n; i++ {
        s[i] = make([]int, n)
        for j := 0; j < n; j++ {
            if m, err := fmt.Scan(&s[i][j]); m != 1 {
                panic(err)
            }
        }
    }
    fmt.Println(s)
}

input:
2
1 2
3 4

output:
[[1 2] [3 4]]

I think this test sample code is clear enough to
show how slice of slice works (with commented output):
package main

import "fmt"

func main() {
    s1 := [][]int{}
    s2 := []int{1, 2}
    s1 = append(s1, s2)
    fmt.Println(s1) // [[1 2]]

    s2[0], s2[1] = 3, 4
    fmt.Println(s1) // [[3 4]]

    s1 = append(s1, s2)

    fmt.Println(s1) // [[3 4] [3 4]]

    s2[0], s2[1] = 30, 40
    fmt.Println(s1) // [[30 40] [30 40]]

    fmt.Println(len(s2), cap(s2)) // 2 2

    s3 := [][]int{
        []int{1, 2},
        []int{3, 4},
        s2,
        s2,
    }
    fmt.Println(s3) // [[1 2] [3 4] [30 40] [30 40]]
    s2[0] = 100
    fmt.Println(s3) // [[1 2] [3 4] [100 40] [100 40]]
}

you created slice of slice s1 like this :
array [0] =    row[0], row[1]
array [1] =    row[0], row[1]
so when you change row it will seen twice.


text:
Q: Get coordinates from multiple taps and return them in an array for use in another function I have set up an empty UIView on my app. I would like to be able to tap two points on the view, get the coordinates of the taps, and append them to an array. Then I would like to pass this array to another function for use (to draw a line between them). I know how to access the locations, but I do not know how I can return them to another function for use. Here is what I have so far:
var coordinates = [CGPoint]()
override func touchesBegan (_ touches: Set <UITouch>, with event: UIEvent?){
let touch = touches.first!
let location= touch.locaition(in:self)
coordinates.append(location)
}

I am not able to modify the touchesBegan function so that it can return the array. If I try to, it will no longer be overriding UIKit's touchesBegan function and Xcode will be reading it as my own function. Thanks!

A: You don't need to return them at all I think. Your coordinates array is a property on your class and you should be able to access that anywhere inside your class, or even by your superclass. If it needs to be private or fileprivate, then you can use delegates to pass information backwards/upwards as needed.


text:
Q: Inserting row with foreign key relation in same transaction as primary row I have a 2 tables where one has a foreign key relation to the other
CREATE TABLE foo (
  id INT NOT NULL PRIMARY KEY IDENTITY,
  value VARCHAR(50) DEFAULT NULL,
);

CREATE TABLE bar (
  id INT NOT NULL PRIMARY KEY IDENTITY,
  foo_key INT NOT NULL
  value VARCHAR(50) DEFAULT NULL,
);

I'm using parameterized ADO.NET ExecuteReader to Insert new rows. My pickle is, if I want to insert 2 rows in different tables in the same transaction, i.e. before commit, I cannot insert rows in bar since I don't know the value that has been given foo.id yet. How would you go about doing that? i.e. How do I make sure that bar.foo_key get assigned the right value? Trying to select on it brings nothing, since I guess it is not actually there yet. Should I use a stored procedure to try and generate the key on the fly, or maybe there is an internal variable that can be used. Or is there a way to have the insert return the new id? Do I need a foreign key declaration, though I'm not sure that would be useful since again I still don't know what id to use?
The reason why I want to do it in one go, is due to error handling, I want to be able to roll everything back in case of an error.

A: You can use scope_identity() to retrieve the newly generated identity:
begin tran;
insert Foo (value) values ('6*7');
declare @fk int = scope_identity();
insert bar (foo_key, value) values (@fk, '42');
commit tran;

Per HLGEM's comment, to return the value of the newly generated identity to the client, you can use output:
insert Foo (value) output inserted.ID values ('6*7');

Note that for a transaction to span two sessions, you need a distributed transaction, which is very expensive.

A: I figured out I can return scope_identity() on the insert
INSERT INTO [foo] ([value]) VALUES (@0) SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY];


text:
Q: Get folder's permissions (short version) I'm using the following code to return detailed folder permissions

return (from permissionName in Enum.GetNames(typeof(FileSystemRights))
            let val =
                Convert.ToInt32(
                    Enum.Parse(typeof(FileSystemRights), permissionName), CultureInfo.InvariantCulture)
            where
                (val != 0x1f01ff) && (val != 0x301bf) && (val != 0x20089) && (val != 0x200a9) && (val != 0x116)
            where ((int)this.FileSystemRule.FileSystemRights & val) > 0
            select permissionName).ToList();

How can i get the short version which is:

In Other words, i want to return only

*

*Full Control

*Modify

*Read & Execute

*List Folder Contents

*Read

*Write

*Special (for any other combination)

A: You can simplify your logic quite a bit by just listing those permissions you want. For example:
private readonly FileSystemRights[] namesIWant = new FileSystemRights[]
{
    FileSystemRights.FullControl,
    FileSystemRights.Modify,
    FileSystemRights.ReadAndExecute,
    FileSystemRights.ListDirectory,
    FileSystemRights.Read,
    FileSystemRights.Write
};

Then, your LINQ expression becomes:
return (from perm in namesIWant
        where (this.FileSystemRule.FileSystemRights & perm) != 0
        select perm.ToString()).ToList();

A: I thought to share this with you,
In order to make it work for me, i had to change the > singe to ==
The code of @Jim Mischel is modified to:
return (from perm in namesIWant
        where (this.FileSystemRule.FileSystemRights & perm) == perm
        select perm.ToString()).ToList();

also remove FileSystemRights.ListDirectory, from NamesIWant because it includes Read, and ReadData, if you keep it you will have duplicated values.


text:
Q: OWL axiom: Given an individual of a particular class, enforce an existence of an Object Property relation with another individual In OWL, is there a way to state that an individual of a particular class must be related to another individual via a specific object property?
For example, I would like to state that:
forall(x) Object(x) -> exists(y) Shape(y) ^ hasShape(x, y)

i.e., "For all objects, there exists a shape that is the shape of the object."
so that if there is an individual of the type Object that has no shape associated with it, a reasoner would find it to be inconsistent.
I tried an axiom:
Object SubClassOf hasShape min 1 Shape

but it's not working.
It seems like the issue is because Object Property in OWL has no identity, but is there a workaround for this issue?
(I'm using Protege 5.2.0)

A: You are correct that the meaning of Object SubClassOf hasShape min 1 Shape is that every individual of Object is associated with an individual of Shape via the hasShape property.
So if you create an individual x of type Object without x being associated with an individual of Shape, why does the reasoner not determine that your ontology is inconsistent? The reason for this is due to the open world assumption. Informally it means that the only inferences that the reasoner can make from an ontology is based on explicit information stated in the ontology or what can derived from explicit stated information.
When you state x is an Object, there is no explicit information  in the ontology that states that x is not associated with an individual of Shape via the hasShape property. To make explicit that x is not is such a relation, you have to define x as follows:
Individual: x
  Types:
    Object,
    hasShape max 0 owl:Thing

Btw, this problem has nothing to do with identity as you stated.

A: One solution I found was to make the ontology "closed world", by making owl:Thing equivalent to the set of all individuals defined so far.


text:
Q: Method for generating a random bitset of uniform distribution How can I generate a bitset whose length is a multiple of 8 (corresponding to a standard data type) wherein each bit is 0 or 1 with equal probability?

A: The following works.

*

*Choose a PRNG with good statistical properties

*Seed it well

*Generate integers over an inclusive range including the minimum and maximum of the integer type.

*Since the integers are uniformly distributed across their entire range, each bit representation must be equally probable. Since all bit representations are present, each bit is equally like to be on or off.

The following code accomplishes this:
#include <cstdint>
#include <iostream>
#include <random>
#include <algorithm>
#include <functional>
#include <bitset>

//Generate the goodness
template<class T>
T uniform_bits(std::mt19937& g){
  std::uniform_int_distribution<T> dist(std::numeric_limits<T>::lowest(),std::numeric_limits<T>::max());
  return dist( g );
}

int main(){
  //std::default_random_engine can be anything, including an engine with short
  //periods and bad statistical properties. Rather than cross my finers and pray
  //that it'll somehow be okay, I'm going to rely on an engine whose strengths
  //and weaknesses I know.
  std::mt19937 engine;

  //You'll see a lot of people write `engine.seed(std::random_device{}())`. This
  //is bad. The Mersenne Twister has an internal state of 624 bytes. A single
  //call to std::random_device() will give us 4 bytes: woefully inadequate. The
  //following method should be slightly better, though, sadly,
  //std::random_device may still return deterministic, poorly distributed
  //numbers.
  std::uint_fast32_t seed_data[std::mt19937::state_size];
  std::random_device r;
  std::generate_n(seed_data, std::mt19937::state_size, std::ref(r));
  std::seed_seq q(std::begin(seed_data), std::end(seed_data));
  engine.seed(q);

  //Use bitset to print the numbers for analysis
  for(int i=0;i<50000;i++)
    std::cout<<std::bitset<64>(uniform_bits<uint64_t>(engine))<<std::endl;

  return 0;
}

We can test the output by compiling (g++ -O3 test.cpp) and doing some stats with:
./a.out | sed -E 's/(.)/ \1/g' | sed 's/^ //' | numsum -c | tr " " "\n" | awk '{print $1/25000}' | tr "\n" " "

The result is:
1.00368 1.00788 1.00416 1.0036 0.99224 1.00632 1.00532 0.99336 0.99768 0.99952 0.99424 1.00276 1.00272 0.99636 0.99728 0.99524 0.99464 0.99424 0.99644 1.0076 0.99548 0.99732 1.00348 1.00268 1.00656 0.99748 0.99404 0.99888 0.99832 0.99204 0.99832 1.00196 1.005 0.99796 1.00612 1.00112 0.997 0.99988 0.99396 0.9946 1.00032 0.99824 1.00196 1.00612 0.99372 1.00064 0.99848 1.00008 0.99848 0.9914 1.00008 1.00416 0.99716 1.00868 0.993 1.00468 0.99908 1.003 1.00384 1.00296 1.0034 0.99264 1 1.00036

Since all of the values are "close" to one, we conclude that our mission is accomplished.

A: Here is a nice function to achieve this:
template<typename T, std::size_t N = sizeof(T) * CHAR_BIT> //CHAR_BIT is 8 on most
                                                           //architectures
auto randomBitset() {
    std::uniform_int_distribution<int> dis(0, 1);
    std::mt19937 mt{ std::random_device{}() };

    std::string values;
    for (std::size_t i = 0; i < N; ++i)
        values += dis(mt) + '0';

    return std::bitset<N>{ values };
}


text:
Q: Grpc-java multiple channel management I am using grpc-java (netty) for my client-server communication. Currently, I am using NettyChannelBuilder to create a single channel (which is backed by a single http2 connection i believe) and I use the channel to create all my GRPC stubs.
Since the RPS is quite high, I see the a saturation of the grpc channel and requests are starting to queue up. I would like to create more channel (hence naturally more connections). Is there a way to achieve that?
In addition is my assumption that a grpc channel is backed by a single http2 connection?

A: I think you should make client channel's thread pool more bigger.
The channel can have many subchannel, and a subchannel has one or many transport, a transport represent a connection. And a server address usually has one connection.
 ManagedChannelBuilder.forAddress("127.0.0.1", 9091)
                      .executor(Executors.newCachedThreadPool())
                      .usePlaintext()
                      .build()

A: A gRPC channel is backed by one or more sub-channels; each sub-channel being a connection. Having more connections helps when you have multiple servers (backends) so each connection goes to a different backend. If you have a single server (backend) you should ensure that creating multiple connections to the same server will actually help which would be the case if the server is not the bottleneck and is able to process high network throughput.
The creation of multiple sub-channels in a channel happens using a RoundRobinLoadBalancer and something called EquivalentAddressGroup. To create multiple sub-channels to the same server you have to be able to create multiple EquivalentAddressGroups for the same server. A custom  NameResolver (or DnsNameResolver) will be needed to do this.


text:
Q: Условие CHECK при создании таблицы в MySql Создаю таблицу

CREATE TABLE MBank.Activity (
activity_id bigint AUTO_INCREMENT PRIMARY KEY,
client_id bigint,
amount double,
activity_date DATE,
commission double,
description text NOT NULL,
FOREIGN KEY (client_id) REFERENCES MBank.Clients(client_id),
CHECK(amount > 0),
CHECK(description IN
('withdraw', 'deposit', 'account closing', 'deposit ending', 'deposit pre-opening'))
);

По идее условие CHECK(amount > 0) должно гарантировать мне, что в столбец amount нельзя будет добавить отрицательное значение (командой INSERT). Но на деле оно просто не выполняется. В чём проблема?
установлена последняя версия MySql.
A: The CHECK clause is parsed but ignored by all storage engines. - Предложение ПРОВЕРКА распознается, но игнорируется всеми механизмами хранения.
Cмотрим тут.


text:
Q: ColdFusion server instance is taking too long to start I am using ColdFusion 2016 development edition. I have 3 instances configured and 3 applications in it. One of the applications is a big one, which uses multiple frameworks like ColdSpring, FW/1, FuseBox, MXUnit etc.
After a few days since I set up all these applications and started working, the instance which is configured for the large application is taking a long time to start. At first it was starting normally. But after a few days it is taking a very long time to start and even multiple tries to start the same.
I reinstalled ColdFusion and configured everything again. After a few days the same thing happens. Is there anything I can try to speed up the server start? Like clearing cache or anything like that? Because this keeps happening after a few days of working with the application.

A: This should help you. If you do not wish to save the class files, you can disable this feature in ColdFusion Administrator from Server Settings>>Caching


text:
Q: Should I use 'did' or 'were'? I have these 2 sentences:

*

*

I wonder what went through their mind when they cried. Were they remembering all the good memories?

*

I wonder what went through their mind when they cried. Did they remember all the good memories?

Should I be using 'were' or 'did'? which one is grammatically correct?


text:
Q: Python turtle library error relating to variable which doesn't seem to have any problems I'm following a tutorial for making pong in the turtle API & for some reason I'm getting an error which seems to stop "paddle_a" from colliding. It errors out every time I close the window. The paddle a collision detection seems identical to the paddle b collision detection other than numbers being tweaked.
I'm not that great at debugging but I know it's at line 69 and it seems to affect just the collision detection with the ball of paddle_a but not the nearly identical code of paddle_b.

Traceback (most recent call last):
File "c:\Users\harba\OneDrive\Desktop\New folder\Personal Projects\Games\Pong.py", line 69, in
ball.setx(ball.xcor() + ball_dx)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 1809, in setx
self._goto(Vec2D(x, self._position[1]))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 3160, in _goto
screen._pointlist(self.currentLineItem),
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 754, in _pointlist
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 1809, in setx
self._goto(Vec2D(x, self._position[1]))  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 3160, in _goto
screen._pointlist(self.currentLineItem),
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\turtle.py", line 754, in pointlist
cl = self.cv.coords(item)
File "", line 1, in coords
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\tkinter_init.py", line 2795, in coords_tkinter.TclError: invalid command name ".!canvas"

import turtle

window = turtle.Screen()
window.title("Pong but cool")
window.bgcolor("black")
window.setup(width=800,height=600)
window.tracer(0)

#Padles
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("white")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350, 0)

paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("white")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350, 0)

#Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.05
ball.dy = 0.05

#kooky Functions
def paddle_a_up():
    y = paddle_a.ycor()
    y += 20
    paddle_a.sety(y)

def paddle_a_down():
    y = paddle_a.ycor()
    y -= 20
    paddle_a.sety(y)

def paddle_b_up():
    y = paddle_b.ycor()
    y += 20
    paddle_b.sety(y)

def paddle_b_down():
    y = paddle_b.ycor()
    y -= 20
    paddle_b.sety(y)

#keyboard binding
window.listen()
window.onkeypress(paddle_a_up, "w")
window.onkeypress(paddle_a_down, "s")
window.onkeypress(paddle_b_up, "Up")
window.onkeypress(paddle_b_down, "Down")

while True:
    window.update()

    #balls
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)

    #border checking
    if ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1
    if ball.ycor() < -290:
        ball.sety(-290)
        ball.dy *= -1

    if ball.xcor() > 390:
        ball.goto(0, 0)
        ball.dx *= -1
    if ball.xcor() < -390:
        ball.goto(0, 0)
        ball.dx *= -1

    #collisions
    if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 50 and ball.ycor() > paddle_b.ycor() - 50):
        ball.setx(340)
        ball.dx *= -1
    if (ball.xcor() > -340 and ball.xcor() < -350) and (ball.ycor() < paddle_a.ycor() + 50 and ball.ycor() > paddle_a.ycor() - 50):
        ball.setx(-340)
        ball.dx *= -1

The final if statement inside the game loop doesn't seem to work & in the balls section is where the error seems to originate.

A: This can never be true:
ball.xcor() > -340 and ball.xcor() < -350

You have to reverse your geometric thinking when working with negative coordinates:
-340 > ball.xcor() > -350

My rework of your code:
from turtle import Screen, Turtle

def paddle_a_up():
    paddle_a.sety(paddle_a.ycor() + 20)

def paddle_a_down():
    paddle_a.sety(paddle_a.ycor() - 20)

def paddle_b_up():
    paddle_b.sety(paddle_b.ycor() + 20)

def paddle_b_down():
    paddle_b.sety(paddle_b.ycor() - 20)

def play():
    x, y = ball.position()
    ball.setposition(x + ball.dx, y + ball.dy)

    # border checking
    if ball.ycor() > 290:
        ball.sety(290)
        ball.dy *= -1
    elif ball.ycor() < -290:
        ball.sety(-290)
        ball.dy *= -1

    if ball.xcor() > 390:
        ball.goto(0, 0)
        ball.dx *= -1
    elif ball.xcor() < -390:
        ball.goto(0, 0)
        ball.dx *= -1

    # collisions
    if 340 < ball.xcor() < 350 and paddle_b.ycor() - 50 < ball.ycor() < paddle_b.ycor() + 50:
        ball.setx(340)
        ball.dx *= -1
    elif -340 > ball.xcor() > -350 and paddle_a.ycor() - 50 < ball.ycor() < paddle_a.ycor() + 50:
        ball.setx(-340)
        ball.dx *= -1

    screen.update()
    screen.ontimer(play, 10)

screen = Screen()
screen.title("Pong but cool")
screen.bgcolor('black')
screen.setup(width=800, height=600)
screen.tracer(0)

# Padles
paddle_a = Turtle()
paddle_a.shape('square')
paddle_a.color('white')
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.setx(-350)

paddle_b = paddle_a.clone()
paddle_b.setx(350)

# Ball
ball = Turtle()
ball.shape('square')
ball.color('white')
ball.penup()

ball.dx = 2.0  # user-defined properties
ball.dy = 2.0

# keyboard binding
screen.onkeypress(paddle_a_up, 'w')
screen.onkeypress(paddle_a_down, 's')
screen.onkeypress(paddle_b_up, 'Up')
screen.onkeypress(paddle_b_down, 'Down')
screen.listen()

play()

screen.mainloop()


text:
Q: How to properly scope a lock Let's say I have a ReentrantLock,
ReentrantLock foo = new ReentrantLock();

and a method bar that uses the lock,
public void bar()
{
    foo.lock();

    try
    {
        methodOne();
    }
    finally
    {
        foo.unlock();
    }
}

and methodOne calls a method methodTwo that also uses the lock,
public void methodTwo()
{
    foo.lock();

    try
    {
        // do something
    }
    finally
    {
        foo.unlock();
    }
}

is it better to release the lock in bar before I call methodOne? In general, is it good practice to release the lock before calling another method?

A: No, you should not do that. If you do it, any concurrent thread could acquire the lock in the middle of the bar() method, which is precisely what you want to avoid by using a lock.
It's called ReentrantLock precisely because it allows acquiring the lock multiple times in the same thread. A counter is incremented each time lock() is called, and decremented each time unlock() is called, so you just need to make sure unlock() is always called in a finally block.
Note that the code would be less fragile by simply using synchronized blocks, because it's impossible to forget closing a synchronized block.

A: Release the lock when the critical operations the lock "protects" are done.  No sooner.


text:
Q: Inverse optimization problem This may seem like a weird question, but it's something which has been intriguing me for quite a while. In the Calculus of Variations we are told to find the extrema of a functional defined over a certain set, but has nobody tried to solve the inverse problem? That is: given a curve find the functional(s) for which it is the extrema.
Consider, for example, that the catenary solves the suspended chain problem but it is also the solution for the Minimal Surface of Revolution problem. Could there be other variational problems for which it's the solution?
On Scopus searching for "inverse problem" AND "calculus of variations" in Article Title, Abstract, Keywords gives me 113 results, almost all relating to the Inverse problem for Lagrangian mechanics

A: This is not so interesting. We can build a million functionals having optimum on the given curve. It is like if you have some function $f(x)$ to minimize and get say solution $x=1$. Now the question what function $g(x)$ will have $x=1$ as a minimum?  Does it make sense? IMHO it does not.


text:
Q: Why can logic gate connect together with each logic gate behave the same way when it's by itself? Why can logic gates connected together behave the same as single logic gates?
For example:

When inputs A and B are high, the AND gate output is high when it's by itself.
But when it is connected to an OR gate (inputs A, B, and C are high) and the gate is still the same, does this OR input affect the AND gate's output impedance?
Or does the OR gate not disturb the AND gate?

A: Logic is designed with suitable input and output characteristics that yes, the input of a driven gate does not disturb the output of a driving gate, at least, up to a point.
There is a parameter known as 'fan-out', which specifies how many gates a driving gate is guaranteed to be able to drive. Often it's at least 10. Different logic families may have different fanouts.
For the details of how this works, you need to go into the analogue detail of how the gates are built, what the logic threshold voltages and current requirements are at the input, what voltages the outputs can reach at what current. But if you stay within one logic family, and observe the fan-out limits, timing limits, supply and ground cleanliness limits, then it all 'just works'.
If you want to mix logic families, drive logic from 'analogue' sources, drive logic from slow edges, use logic to drive other things, then you need to read the data sheets and ensure that voltage levels,  current requirements, edge rates, are compatible.

A: The logic gate output stage used in nearly all gates is the push-pull driver, shown below.
There are other output stages, such a three-state push-pull drivers and open-drain, but their use is a tiny minority within the vast number of logic gates manufactured and deployed.
The push-pull driver connects its output to a supply rail or a ground rail through one of the two low-impedance FETs. In either state, the output impedance is low, with a very high source or sink current compared to the tiny load currents taken by the driven logic gate inputs.
For example, the drive current capability may be 10 mA source or sink, while the five loading gates might take 25 uA which is 1/400th of the available drive current.
So the output drive behaviour seen at a logic gate when off-load or when driving five gate inputs is almost identical.
This ignores the transmission line effects between the gates, as the connections and speeds will vary greatly across all the different circuit designs. But it explains a nominal case.
Note that this considers the logic families since the mid-80's or so. If you go back far enough, you'll find gates that had weak drives and took large input currents. But their percentage of the circuits in use out in the world is now almost zero.