text:
Q: Problem determining if input is integer C++ I am writing a function that determines if input corresponds to a desired type (int, double, float)
Here is my code so far:
My problem comes when I test for int input. Input as 4.0, where all the decimals are equal to 0 are not accepted.
How can I get around this?
#include<iostream>
#include<string>
#include<sstream>

template <typename T>
bool is_type(std::string Input)
{
    std::stringstream ss(Input);
    T test;
        std::string remainder;
    if (ss >> test)
    {
        ss >> remainder;
        return (remainder.size() == 0) ? true : false;
    }
    else return false;
}

   int main(void)
{
    std::string Input;;
    std::getline(std::cin, Input);

    if (is_type<int>(Input)) std::cout << "It is valid input.\n";

    return 0;
}

A: "4.0" is a valid representation of an integer, namely, the digit character "4", followed by some other stuff. When you read that text into an int you get a valid value, and the rest of the input is left behind.
If you want to interpret the entire string as a numeric value, and treat the result as an integer when it has no fractional part, you have to read the entire input as a floating-point value. If the result is an integer value, then you have an integer; otherwise, you don't.
double d;
std::cin >> d;
if (d == (int)d)
    std::cout << "got an integer value.\n";
else
    std::cout << "didn't get an integer value.\n";


text:
Q: Help with Search bar scope buttons I have a UI that displays data from a user table like FirstName, LastName, Email,etc. Now i want to create a search bar along with scope buttons that filters data depending on the scope button clicked. I have 2 scope buttons, FirstName and LastName. By default FirstName button is selected. Below is how I add my data to a mutablearray,
userData = [[NSMutableArray alloc] init];

    for (NSDictionary *tmpDic in response) {
        [userData addObject: [NSString stringWithFormat: @"%@ %@",
                                [tmpDic valueForKey: @"FirstName"],[tmpDic valueForKey: @"LastName"]]];
    }

My search code,
- (void) searchTableView {

    NSString *searchText = theSearchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    for (NSString *sTemp in userData)
    {
        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
            [copyuserData addObject:sTemp];
    }

    NSLog(@"Copied data is:%@", copyuserData);

    [searchArray release];
    searchArray = nil;
}

The above code works well for searching the userData array, but i am not sure how will i change the code so that depending on FirstName, LastName scope buttons it will display the result. how i will hook up the buttons to the search bar so that it only display result depending on what scope bar button is clicked. Thanks in advance..

A: You need to do two things:
 1. Look at the value of the searchBar.selectedScopeButtonIndex - this will tell you if you need to search first names or last names.
 2. Depending on the scope button, you want to search either the first part of each array item or the second part.  There are lots of ways to do this.  Probably the easiest is to keep 2 parallel arrays, firstNames and lastNames, which you populate from tmpDic.  Then for the actual search, you could either loop through firstNames or lastNames, or do a for(int j=0;j<[firstNames count]; j++)   and get [firstNames objectAtIndex:j] and compare that to your temp string.  If any string matches, add it to your results array.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw bitmap in shape like this? enter image description here
how to draw bitmap in shape like this?
here is my code:
fun generateTwoCombined(originBitmap: Bitmap?): Bitmap? {
    val combineBm = Bitmap.createBitmap(originBitmap!!.width, originBitmap.height + 100, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(combineBm)
    val matrix = Matrix()

    // {x1, y1, x2, y2, x3, y3, x4, y4}
    val src2 = floatArrayOf(0f, 0f, originBitmap.width.toFloat() / 2, 0f, originBitmap.width.toFloat() / 2, originBitmap.height.toFloat(), 0f, originBitmap.height.toFloat())
    val dst2 = floatArrayOf(0f, -basicFisheyeEffectModel.currentDistort, originBitmap.width.toFloat() / 2, 0f, originBitmap.width.toFloat() / 2, originBitmap.height.toFloat(), 0f, originBitmap.height.toFloat() + basicFisheyeEffectModel.currentDistort)
    canvas.save()
    matrix.setPolyToPoly(src2, 0, dst2, 0, src2.size shr 1)
    canvas.clipRect(Rect(0, (-basicFisheyeEffectModel.currentDistort).toInt(), originBitmap.width, (originBitmap.height + basicFisheyeEffectModel.currentDistort).toInt()))
    canvas.concat(matrix)
    canvas.drawBitmap(originBitmap, 0f, 0f, Paint())
    canvas.restore()

    // {x1, y1, x2, y2, x3, y3, x4, y4}
    val src = floatArrayOf(originBitmap.width.toFloat() / 2, 0f, originBitmap.width.toFloat(), 0f, originBitmap.width.toFloat(), originBitmap.height.toFloat(), originBitmap.width.toFloat() / 2, originBitmap.height.toFloat())
    val dst = floatArrayOf(originBitmap.width.toFloat() / 2, 0f, originBitmap.width.toFloat(), -basicFisheyeEffectModel.currentDistort, originBitmap.width.toFloat(), originBitmap.height.toFloat() + basicFisheyeEffectModel.currentDistort, originBitmap.width.toFloat() / 2, originBitmap.height.toFloat())
    canvas.save()
    matrix.setPolyToPoly(src, 0, dst, 0, src.size shr 1)
    canvas.clipRect(Rect(originBitmap.width / 2, 0, originBitmap.width, (originBitmap.height + basicFisheyeEffectModel.currentDistort).toInt()))
    canvas.concat(matrix)
    canvas.drawBitmap(originBitmap, 0f, 0f, Paint())
    canvas.restore()

    return combineBm
}


text:
Q: How to remove '.do' prefix from url in Struts1? I have written a web-application in Struts 1 framework. Everything works fine but on form submission when user is forwarded to next page URL which is shown is actionname.do. I don't want this Struts 1 default suffix on URL. Instead of it I would like to see page's name in URL. How to do it?
Note : I have tried editing servlet mapping in web.xml. Have replaced /*.do . But In that case even my index page doesn't open.

A: In your web.xml, replace url pattern *.do with /
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

A: *

*Open /WEB-INF/web.xml

*You will have to find the servlet-name of the org.apache.struts.action.ActionServlet and the servlet-mapping that corresponds to the servlet-name.

For example:
<servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

Finally, simply change the url-pattern to what you desire and redeploy the application.

A: Modify  in web.xml and change *.do
<servlet-mapping>
  <servlet-name>myapp</servlet-name>
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

A: You can use this mapping
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>/c/*</url-pattern>
</servlet-mapping>

Then use Tuckey URL rewriter rule to change this to /*
<rule>
  <from>^/(\w+)*/$</from>
  <to>/c/$1</to>
</rule>


text:
Q: Why do we prepend the "A" in "API"? I'm writing some pedagogic material and when I started explaining what an API is I realized I didn't know why we say "application programming interface" instead of just "programming interface". Does anyone know the history?

A: The reason why is because an API more often than not isn't a general machine-code type interface, but is an interface to a software module that performs a particular function, i.e. a particular application.
Libraries to perform image processing, to compress files, to schedule dentist appointments, to auto-tune signers, are all modules that provide an application of software to solve a particular problem. Much of the API choices going into auto-tune are different than for scheduling dentist appointments, and the data structures and manipulation processes are different.
If you just said "programming interface", myself and I suspect many others would think of a very low-level function of e.g. loading executable code from disk into memory, loading code onto a flash chip, etc.
A "programming interface" would be something compiler writers and chip designers would be concerned about, whereas an "application programming interface" is a higher up level of abstraction.

A: The "application" refers to software programming; as opposed to programming for a hardware interface (such as a device driver) or a human interface (such as a mouse).
From SmartyStreets:

APIs allow one program, or part of a program, to interface with another.

Similarly, from Wikipedia:

In general terms, it is a set of clearly defined methods of communication between various software components.

API Evangelist defines an API as:

The principal of a well documented set of publicly addressable "entry points" that allow an application to interact with another system....

A: Sometimes a distinction between application software and systems software is drawn. Application software is software to address specific problems or to interact with users. In contrast, system software provides services to other software. Operating systems and software libraries are examples of systems software.
The application programming interface is the interface exposed by systems software through which it provides services for application software.
Nowadays, distinction between applications and systems software is almost entirely useless and unclear. Many programs are both application-like and platform-like (e.g. a web browser not only offers a user interface for the web, but also a runtime environment for web applications). Additionally, multiple layers of system-like software are often layered on top of each other, which must also communicate through some interface
Therefore, the term "application programming interface" effectively refers to any software–software interface.

A: *

*api (application programming interface) is for applications that want to use a lib

*spi (service provider interface) is a kind of "os-device driver" or plugin or protocol or callback-function that you must implement to allow the (operating-) system to use your code.

the program flow is like this
yourApp -> api -> os -> spi -> device driver

Examples

*

*your app uses the file-api to read/write a config file. there are different spi implementations for filesystems cdrom, vfat, ntfs, .....

*firefox-webbrowser -> spi -> firefox-plugin ( -> api -> ... )

*in java/c/c++/c# the function main() is the spi that you have to implement when you want to write a console applicatoin.


text:
Q: "Mechanically generated" java source files in the Java source code As I was looking through the Java source code, I found some unusual files, mostly related to ByteBuffers in the java.nio package which had a very messy source code and were labelled This file was mechanically generated: Do not edit!.
These files also contained large portions of blank lines (some even in the middle of javadocs (!!?)), presumably to prevent the line numbers from changing. I have also seen a few java decompilers, such as procyon-decompiler, which have an option to keep line numbers, but I doubt that's the case, because putting blank lines before the final accolade changes nothing.
Here are a few of these files (I couldn't find any links to them online and didn't pastebin them because I don't want to break any copyright, but you can find them in the src.zip folder at the root of your JDK installation folder):

*

*java.nio.ByteBuffer

*java.nio.DirectByteBufferR

*java.nio.Bits

*java.nio.BufferOverflowException

I'd be curious to know:

*

*Which tool generated these files?

*Why does the tool keep the line numbers the same? Is it to make debugging (stacktraces) easier?

*Why would a tool be used to generate them, while all other classes are programmed by humans?

*Why would the tool put blank lines randomly inside parentheses, before the final accolade, or even in javadocs?

A: I can probably not answer all of the questions, but some background is:
In the Makefile at http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/make/java/nio/Makefile, they are generating different java source files from the same template file through some preprocessor:
...
$(BUF_GEN)/CharBuffer.java: $(X_BUF_TEMPLATE) $(GEN_BUFFER_SH)
    $(prep-target)
    @$(RM) $@.temp
    TYPE=char SRC=$< DST=$@.temp $(GEN_BUFFER_CMD)
    $(MV) $@.temp $@
$(BUF_GEN)/ShortBuffer.java: $(X_BUF_TEMPLATE) $(GEN_BUFFER_SH)
    $(prep-target)
    @$(RM) $@.temp
    TYPE=short SRC=$< DST=$@.temp $(GEN_BUFFER_CMD)
    $(MV) $@.temp $@
...

$(X_BUF_TEMPLATE) refers to X-Buffer.java.template, which is the source for typed buffers like CharBuffer, ShortBuffer and some more.
Note: The URLs might change in the future. Also sorry for referring to Java 7 - in Java 8 they have modified the build system, I did not find the corresponding Makefiles so far.

Which tool generated these files?

GEN_BUFFER_SH / GEN_BUFFER_CMD finally refers to genBuffer.sh, so the script which creates these files is http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/make/java/nio/genBuffer.sh.

Why would a tool be used to generate them, while all other classes are programmed by humans?

I don't have an authoritative answer for this specific case, but usually you are using code generation tools

*

*if you need to create a lot of similar classes/methods which only differ in some detail, but which is subtle enough so that you can not use established mechanisms like generics or method parameters (probably the case here, since the buffers are generated for primitive types which can not be used with Generics)

*if you need to create complex algorithms from a much simpler representation (like generating parsers from a grammar).

Why does the tool keep the line numbers the same? Is it to make debugging (stacktraces) easier?

I am guessing: yes, its to retain the line numbers in stack traces so that they match the template files. Other tools like the C preprocessor work similar.


text:
Q: How to make Wordpress category IDs sequential? I've noticed when I create a new category in one of my Wordpress 2.9.2 installations that the new category ID isn't sequential.
I have created five categories and the id's so far are: 15, 23, 34, 36, and now the newest one, 54.
This isn't really a problem, but is kind of annoying! And I haven't seen it before on other installations.
Any ideas would be appreciated.
Thanks!

A: The IDs are based on MySQL auto-incremental indexes.
Did you add or delete tags, custom terms or other categories in-between adding the ones you've mentioned?


text:
Q: Deja-dup losing its mind every few days on 19.10 I was using deja-dup on 16.04 with no problems. I recently upgraded to 19.10, and now I'm having problems with it losing its mind every few days.
I set it up initially and it worked fine for a week or two, then prompted me again about whether I wanted to password protect my backups and started a new "initial backup". The older backups are still in the target directory, but it doesn't recognize them as valid backups.
At this point, it seems to do the same thing every 3-5 days. There don't seem to be any useful messages in syslog (or anywhere else in /var/log) based on grepping for deja-dup.
Any suggestions for troubleshooting or fixing will be greatly appreciated.

A: I was backing up to a flash drive and Deja Dup was having a lot of problems recently.
Not really sure what's going on if its some dependency and Deja Dup getting the short end from that or Deja Dup itself.
It did get worse for me after Deja Dup was updated so it feels like its Deja Dup at fault but I didn't really try to narrow it down. its difficult to say if I will though should the problem not go away with my new full backup and format of the drive then I probably will.


text:
Q: Discriminator in InheritanceType.JOINED Is it possible to force hibernate to use discriminator column for inheritance type joined?
According to JPA2.0 specification this should be possible but i can't achieve it in hibernate.
Example:
@Inheritance(strategy = InheritanceType.JOINED)
@ForceDiscriminator
@DiscriminatorColumn(name="TYPE")
@Entity
public class Parent

@Entity
@DiscriminatorValue("C")
public class Child extends Parent

This doesn't even create column TYPE in the table PARENT when using hibernate.hbm2ddl.auto create.
I know that InheritanceType.JOINED works without defining discriminator column but it's quite ineffective because then hibernate needs to create joins between parent and all children instead of just parent and one child when using information in discriminator column.

A: I've used SINGLE_TABLE with a Discriminator and a SecondaryTable on the subclass to do this very thing.  I.E.
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
@Entity
public class Parent

@Entity
@DiscriminatorValue("C")
@SecondaryTable(name = "child", pkJoinColumns = {@PrimaryKeyJoinColumn(name="id", referencedColumnName = "id")})
public class Child extends Parent

When you add a new sub class you add a new table with the relevant extended data fields in it.

A: Do you want to use @Inheritance(strategy=InheritanceType.SINGLE_TABLE)?


text:
Q: How to tell Entity Framework that my ID column is auto-incremented (AspNet Core 2.0 + PostgreSQL)? Code is simple.
Tag.cs entity:
public partial class Tag
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

HomeController.cs class:
public async Task<IActionResult> Index()
{
   tagRepository.Insert(new Tag
               {
                   Name = "name",
                   Description = "description"
               });
   await UnitOfWork.SaveChangesAsync();  // calls dbContext.SaveChangesAsync()

   return View();
}

TagRepository.cs class:
    // Context it's a usual DBContext injected via Repository's constructor
    public virtual void Insert(TEntity item)
                => Context.Entry(item).State = EntityState.Added;

Tag table was created by running:
CREATE TABLE Tag (
    ID SERIAL PRIMARY KEY,
    Name text NOT NULL,
    Description text NULL
);

When run my application I get an error:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (28ms) [Parameters=[@p0='?', @p1='?', @p2='?'], CommandType='Text', CommandTimeout='30']
      INSERT INTO "tag" ("id", "description", "name")
      VALUES (@p0, @p1, @p2);
Npgsql.PostgresException (0x80004005): 23505: duplicate key value violates unique constraint "tag_pkey"
   at Npgsql.NpgsqlConnector.<DoReadMessage>d__157.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Npgsql.NpgsqlConnector.<ReadMessage>d__156.MoveNext()

As you can see Entity Framework tries to send id=0 value to the DB, but there is already a record with id=0 in my DB and that's why it throws duplicate key error.
I didn't find any answer so far and my question is: how can I get rid of this error and tell Entity Framework that my id column is auto-incremented and there is no need to update it?

A: According to the Postgre SQL docs here is an example which shows how to achieve the desired result:
protected override void OnModelCreating(ModelBuilder modelBuilder)
   => modelBuilder.Entity<Blog>().Property(b => b.Id).UseIdentityAlwaysColumn();

A: You have to use here "ValueGenerationOnAdd()". As the issue you are getting is already reported on GitHub. Please find the below link.
https://github.com/npgsql/Npgsql.EntityFrameworkCore.PostgreSQL/issues/73
You can find more info regarding Generated Value pattern from following link.
Value generated on add
public classs SampleContext:DBContext{
public DbSet<Tag> Tag { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<Tag>()
        .Property(p => p.ID)
        .ValueGeneratedOnAdd();
 }
public class Tag{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description{get;set;}
  }
}

Source:- https://www.learnentityframeworkcore.com/configuration/fluent-api/valuegeneratedonadd-method
Hope this will help

A: After a lot of wasted time on research I've solved it absolutely unexpected. Actually, the solution to my problem lies on the surface, because the problem is not in EF and not in it's stuff. In my case it was SEQUENCE. I mean, involved table has serial column and related sequence just was changed by some side-effect. In another words - sequence was restarted from 1 and at the same time the table is already having values with 1, 2, 3 ... etc. That's why postgres throws 'duplicate key' error. So, the solution is:
ALTER SEQUENCE "your_table_seq" RESTART WITH your_value;


text:
Q: Why can I click on a hidden JLabel? I'm making a GUI with Java.
I'm using JLabel and with this code i give them some "onclick" events :
myJLabel.addMouseListener(new MouseAdapter(){
    public void mouseClicked(MouseEvent e){
       System.out.println("Yeah !!!!");
    }
});

And it's working, the "Yeah !!!!" is print.
The problem is if i have an other JLabel above "myJLabel", i still can click on "myJLabel".
Here are some images to explain :
"myJLabel" is the red JLabel. When i click on it, the pink JLabel is moving. So everything is ok :D)

But if the pink JLabel is above "myJLabel", i still can click on it :'(.

My question is : How can I prevent it ?

EDIT : Here is my full code :
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;

import java.awt.*;
import java.awt.event.*;

public class Test extends JPanel{
    private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)",   "Red (3)", "Green (4)" };
    private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red, Color.green };

    private JLayeredPane layeredPane;
    private JLabel dukeLabel;

    public Test(){
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

        //Create and set up the layered pane.
        layeredPane = new JLayeredPane();
        layeredPane.setPreferredSize(new Dimension(300, 310));
        layeredPane.setBorder(BorderFactory.createTitledBorder(""));

        JLabel label1 = createColoredLabel(layerStrings[1], layerColors[1], new Point(10, 10));
        JLabel label2 = createColoredLabel(layerStrings[2], layerColors[2], new Point(30, 30));

        label1.addMouseListener(new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
               System.out.println("Yeah !!!!");
            }
       });

        layeredPane.add(label1, new Integer(1));
        layeredPane.add(label2, new Integer(2));

        add(layeredPane);
    }

    //Create and set up a colored label.
    private JLabel createColoredLabel(String text, Color color, Point origin) {
        JLabel label = new JLabel(text);
        label.setVerticalAlignment(JLabel.TOP);
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setOpaque(true);
        label.setBackground(color);
        label.setForeground(Color.black);
        label.setBorder(BorderFactory.createLineBorder(Color.black));
        label.setBounds(origin.x, origin.y, 140, 140);
        return label;
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("LayeredPaneDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new Test();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

A: In the event function add this command. Basically says if it is not showing, doing nothing.
if(!this.isShowing())return;


text:
Q: schedule_interval of airflow job Hi if i want to schedule a airflow dag to run at 12:00 pm and 18:00 pm daily.
How to config the schedule_interval
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2018, 1, 1),
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5),
}

dag = DAG('example_dag_one',
        schedule_interval='0 12 * * *',
        default_args=default_args)

i add 0 12 * * * (it means 12:00 pm) but how to add 0 18 * * * (it means 18:00 pm)
Thanks


text:
Q: How to implement one trait for different primitive types without code duplication? I want to extend primitive numbers in Rust with a floor_nearest method which floors a number to the nearest multiple of another number e.g.:
let x = 3.7.floor_nearest(0.2);
assert_eq!(x, 3.6)

I want to implement this both for all integers and all floats. I have noticed the num_traits crate provides traits Num, Float, and PrimInt. Since the implementation for floats and integers are  different, I then set out to make a trait, Rounder, which I would then implement for each numerical trait:

pub trait Rounder
where
    Self: Num,
{
    fn floor_nearest(self, nearest: Self) -> Self;
}

impl<T> Rounder for T
where
    T: Float,
{
    fn floor_nearest(self, nearest: Self) -> Self {
        (self / nearest).floor() * nearest
    }
}

impl<T> Rounder for T
where
    T: PrimInt,
{
    fn floor_nearest(self, nearest: Self) -> Self {
        (self / nearest) * nearest
    }
}

However, I get the following error:
error[E0119]: conflicting implementations of trait `math::Rounder`
  --> src/math.rs:26:1
   |
17 | / impl<T> Rounder for T
18 | | where
19 | |     T: Float,
20 | | {
...  |
23 | |     }
24 | | }
   | |_- first implementation here
25 |
26 | / impl<T> Rounder for T
27 | | where
28 | |     T: PrimInt,
29 | | {
...  |
32 | |     }
33 | | }
   | |_^ conflicting implementation

I understand the reason for this is technically that a struct could implement both "Float" and "PrimInt", however I know this to not be the case here.
How could I solve this in a sane way that will still allow me to use these implementations as method calls, without duplicating the same code twice for f32 and f64``` and a number of times for the primitive integers?

A: You can use a macro to implement the trait for all number types:
macro_rules! impl_rounder_for_int {
    ($($t:ty),*) => {
        $(
            impl Rounder for $t {
                fn floor_nearest(self, nearest: Self) -> Self {
                    (self / nearest) * nearest
                }
            }
        )*
    };
}
impl_rounder_for_int!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);

macro_rules! impl_rounder_for_float {
    ($($t:ty),*) => {
        $(
            impl Rounder for $t {
                fn floor_nearest(self, nearest: Self) -> Self {
                    (self / nearest).floor() * nearest
                }
            }
        )*
    };
}
impl_rounder_for_float!(f32, f64);

You can make the macro more compact (as @eggyal suggested), however I feel this is a good middle ground between readability and compactness.


text:
Q: Jackson - ObjectMapper rename some field names regarding rules Is it possible, when doing generic serialization, to add some intelligence in the ObjectMapper to rename some Json Fields in the following use case :
byte[] data
...
read(mapper.readValue(data, Map.class)

One rule could be something like " if the field contains the symbol '@', replace @ by 'at_'" ?
EDIT 1:
To give details, let's say I have the following String :
String str = " {'name' : 'foo', '@somefield':'bar'}"
I use a ObjectMapper to translate it to a Map Object like defined above:
 Map<String, String> map =  mapper.readValue(str.bytes(), Map.class)

But I would like to know if it's possible to do some filtering / renaming during the readValue process of the ObjectMapper, for example removing the @ symbol of the fields names.
The result would be a map with the following fields :
'name' : 'foo'
'somefield' : 'bar'

A: You can use StdDesiralizer.
Of course, you'll have to suffer with various options for the data structure (a nested list in one of the fields, numbers, etc.), but at least this is a working option.
P.S. You can use annotation to make code cleaner.
  public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module =
            new SimpleModule("CustomJsonDeserializer", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(Map.class, new CustomJsonDeserializer());
    mapper.registerModule(module);

    String str = " {\"name\" : \"foo\", \"@somefield\":\"bar\"}";
    Map<String, String> map = mapper.readValue(str.getBytes(), Map.class);
    for (Map.Entry<String, String> e : map.entrySet()) {
        System.out.printf("'%s' : '%s'\n", e.getKey(), e.getValue().toString());
    }
}

public static class CustomJsonDeserializer extends StdDeserializer {

    public CustomJsonDeserializer() {
        this(null);
    }

    public CustomJsonDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Map<String, String> deserialize(JsonParser parser, DeserializationContext deserializer)
            throws IOException {
        Map<String, String> map = new HashMap<>();
        ObjectCodec codec = parser.getCodec();
        JsonNode nodes = codec.readTree(parser);
        Iterator<Map.Entry<String, JsonNode>> iterator = nodes.fields();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            String key = entry.getKey();
            if (key.contains("@")) {
                key = key.replace("@", "at_");
            }
            map.put(key, entry.getValue().textValue());
        }
        return map;
    }
}

Output:

'name' : 'foo'
'at_somefield' : 'bar'


text:
Q: JS error uncaught SyntaxError: Unexpected token if I already wrote the code that worked before, after some other additional details on website my script stopped working. I am not sure about reason why i didn't work. I got below error in console:
Uncaught SyntaxError: Unexpected token if
code :

Im also beginner at js, but first time i solved and all worked after some other edits all this scripts stopped work any suggestion?

A: Invalid JavaScript. The if statement is right in the middle of an object declaration. Something more like this might work for you, although I'm not entirely sure what you want the end result to be.
{
  type:'GET',
  url:'process.php',
  context: this,
  data: { "id": id, "task": task },
  success: function(data) {
    console.log(data);
    if(data === "4"){
        window.location.href = '/prijava';
    } else if(data === "1" || data === "2") {
        alert('Doslo je do greske!');
    } else {
      $(this).addClass('active');
      $(this).find('i').removeClass('glyphicon glyphicon-star-empty').addClass('glyphicon glyphicon-star');
      $(this).removeClass('btn-success').addClass('btn-default');
      $(this).removeClass('btnsss').addClass('btnrrr');

      $.blockUI({ message: '

 Ucitavanje. . .
  ' });
      setTimeout($.unblockUI, 500);
    }
  }
}


text:
Q: Multiple autocommands in vim I've got some sections in my .vimrc that look like this:
autocmd Filetype ruby setlocal ts=2
autocmd Filetype ruby setlocal sts=2
autocmd Filetype ruby setlocal sw=2

now it seems I can convert them to this:
autocmd Filetype ruby setlocal ts=2 sts=2 sw=2

but here's my question: is there a vim way to have a structure like this?
<something mentioning Filetype ruby>
  setlocal ts=2
  setlocal sts=2
  ...
<end>

ie, can the autocmd Filetype bit somehow be made to address a group of actions? (this is a simple example, I'm really asking for more complicated situations.)

A: You can call a function, if you like:
autocmd Filetype ruby call SetRubyOptions()
function SetRubyOptions()
    setlocal ts=2
    ...
endfunction

A: You can chain most commands with |:
au Filetype ruby
            \ setlocal ts=2  |
            \ setlocal sts=2 |
            \ ...

Not sure if this syntax is better or worse than writing a function.  Some commands can't be chained like this, but you can use execute to get around that; see :h :bar.
Also see :h line-continuation for an explanation of the weird syntax with the \ at the beginning of the lines.

A: ftplugins are the neat answer to your question.

*

*Ensure your .vimrc has a line such as :filetype plugin on

*Define a file named {rtp}/ftplugin/{thefiletype}.vim or {rtp}/ftplugin/{thefiletype}/whatever.vim (see :h rtp for more details).

*Edit this new file and put your VIM commands in there.  It is probably a good idea to use the  :setlocal command to ensure filetype-specific settings are only for that file (e.g., don't turn all comments purple across all filetypes).

See examples in vim distribution if you plan to override default settings ; or among the many ftplugins I wrote otherwise), just write down your :setlocal, :*map <buffer>, etc. definitions.
It represents some more line to type, but at least, it does scale.


text:
Q: Squares in the Complex plane In the complex plane, $z,$ $z^2,$ $z^3$ form, in some order, three of the vertices of a non-degenerate square. What are all the possible values of the area of the square?
I tried doing $z=a+bi$ so $z^2=a^2-b^2+2ab i$ $\sqrt{(a^2-b^2-a)^2+(2ab-b)^2}=\sqrt{(a^3-3ab^2-a)^2+(3a^2-b^3-b)^2}$ but got nowhere. Help!

A: You have three choices, depending which pair of numbers is on the diagonal. The only two things I will use is that the lengths of sides is the same, and that the length of the diagonal is $\sqrt2$ times the length of the sides. Note that $z$ can't be any real number, since then $z$, $z^2$, and $z^3$ would be on the same line.

*

*Case $z$ and $z^3$ are on the diagonal.
It means $$|z^2-z|=|z^3-z^2|$$I rewrite this as $$|z||z-1|=|z|^2|z-1|$$Since we know that $z$ is not real, $|z|\ne 0$ and $|z-1|\ne 0$. Then $|z|=1$ and therefore $z, z^2, z^3$ will be on the unit circle, so the area of the square is $A=2$.

*Case $z$ and $z^2$ are on the diagonal.
Similar to before $$|z^3-z|=|z^3-z^2|\\|z||z-1||z+1|=|z|^2|z-1|$$
Therefore $$|z+1|=|z|$$
This is not enough, so I will use the length of the diagonal as well:
$$|z^2-z|=\sqrt 2 |z^3-z^2|$$ This yields $$|z|=\frac 1{\sqrt 2}$$
So $z$ is at the intersection of two circles of radius $1/\sqrt 2$, one centered on the origin, the other one on $-1+0i$. It's easy to see that $$z=-\frac 12\pm i\frac 12$$
For $z$ in the upper half, you get $$z^2=-\frac i2\\z^3=\frac 14+i\frac14$$
I've let you verify that the sides are equal, the diagonal is $\sqrt2$ times the sides and that the area is $A=\frac 58$.

*Case $z^3$ and $z^2$ are on the diagonal.
$$|z^3-z|=|z^2-z|\\|z+1|=1$$
For the diagonal $$|z^3-z^2|=\sqrt|z^2-z|\\|z|=\sqrt 2$$
So $z$ is at the intersection of a circle of radius $1$ centered on $-1+0i$, and a circle of radius $\sqrt 2$ centered on the origin. So $$z=-1\pm i$$
Using the $z$ in the upper half of the plane you get $$z^2=-2i$$
Therefore $z^2-z=1-3i$, so the area is $A=10$


text:
Q: Getting current hub in SignalR Is there a good way to call methods in SignalR hub from a controller ?
Right now I have this:
public class StatsHub : Hub
{
    private static readonly Lazy<StatsHub> instance = new Lazy<StatsHub>(() => new StatsHub());
    public static StatsHub Instance { get { return instance.Value; } }

    public StatsHub()
    {
        if (this.Clients == null)
        {
            var hubContext = SignalR.GlobalHost.ConnectionManager.GetHubContext<StatsHub>();
            this.Clients = hubContext.Clients;
            this.Groups = hubContext.Groups;
        }
    }

    // methods here...
}

so in my controller actions I can just say, for example
StatsHub.Instance.SendMessage("blah");

and it's almost good, except that hubContext doesn't have Caller or Context properties of Hub - which are nice to have.
Hopefully, there's a better way to do this ?

A: If you want to broadcast over a hub from outside of the hub, you need GlobalHost.ConnectionManager.GetHubContext<MyHub>() to get ahold of the hub context. You can then use this context to broadcast via the .Clients property.
As indicated in your sample code you already get ahold of the hub context, but doing so inside the hub just doesn't feel right in my opinion. If you're only using the logic in SendMessage() from your controller actions, I'd move the code right into the controller action and use the hub context obtained via GetHubContext<T>() from there.
Please note that the Caller or Context property will always be null in this scenario, because SignalR wasn't involved when making a request to the server and therefore cannot provide the properties.

A: Found a DefaultHubManager, which is what I need, I think.
DefaultHubManager hd = new DefaultHubManager(GlobalHost.DependencyResolver);
var hub = hd.ResolveHub("AdminHub") as AdminHub;
hub.SendMessage("woohoo");

Works. If there's an even better/preferred way - please share.

A: As per the latest documentation, IHubContext can be injected by dependency injection.
documentation : https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-6.0
In service you could do
public class NotificationService : INotificationService
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public NotificationService(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }
}

In controller
public class HomeController : Controller
{
    private readonly IHubContext<NotificationHub> _hubContext;

    public HomeController(IHubContext<NotificationHub> hubContext)
    {
        _hubContext = hubContext;
    }
}

Once you have HubContext you could send message to group/client etc.
public async Task SendMessage()
{
    return await _hubContext.Clients.All.SendAsync("Notify", $"Hello world");
}


text:
Q: Computing connection forms using Cartan's structure equation for torsion forms From $\theta^i = (1-\phi)dx^i$, $d\theta^i \approx \partial_j\phi\;\theta^i\wedge\theta^j$, I'm supposed to obtain $w^i_j = -\partial_j\phi\;\theta^i + \partial_i\phi\;\theta^j$ using $w^i_j \wedge \theta^j = -d\theta^i$.
By comparing the two expressions, I only get the first term. How do I get both?


text:
Q: Pandas pivot table value counts I have a dataframe in format:
 Name     Score    Bin
 John     90       80-100
 Marc     30       20-40
 John     10       0-20
 David    20       0-20

...
I want to create a pivot table that looks like this:
Name    0-20    20-40    40-60    60-80    80-100   Total count   Avg score
John     1       2        nan      nan      2            5         60.53
Marc    nan      2        nan      nan     nan           2         32.13
David   3        2        nan      nan     nan           5         21.80

So I want to have columns that show count of values for each bucket, as well as total count of values and average score.
I have tried
table = pd.pivot_table(df, values=['Score', "Bin"], index=["nAME"],
                   aggfunc={"Score" : np.average, "Bin" : "count"},
                    dropna=True, margins = True)

however I just get overall count and not broken down per bucket

A: Do your task in 3 steps:

*

*Generate a pivot_table:
df2 = pd.pivot_table(df, index='Name', columns='Bin', values='Score', aggfunc='count')\
    .reindex(columns=['0-20', '20-40', '40-60', '60-80', '80-100'])\
    .rename_axis(columns='')

The result, for your source data extended to give roughly your expected
result, is:
       0-20  20-40  40-60  60-80  80-100
Name
David   3.0    2.0    NaN    NaN     NaN
John    1.0    2.0    NaN    NaN     2.0
Marc    NaN    2.0    NaN    NaN     NaN

Note: As NaN is a special case of float, other values are also of
float type.

*Generate Total_count and Avg_score:
df3 = df.groupby('Name')\
    .agg(Total_count=('Score', 'count'), Avg_score=('Score', 'mean'))\
    .rename(columns={'Total_count': 'Total count', 'Avg_score': 'Avg score'})

The result is:
       Total count  Avg score
Name
David            5       21.8
John             5       61.0
Marc             2       32.0

*Join both above tables:
result = df2.join(df3)

The result is:
       0-20  20-40  40-60  60-80  80-100  Total count  Avg score
Name
David   3.0    2.0    NaN    NaN     NaN            5       21.8
John    1.0    2.0    NaN    NaN     2.0            5       61.0
Marc    NaN    2.0    NaN    NaN     NaN            2       32.0


text: Q: Could not connect to any servers in your MongoDB Atlas cluster, error message I've deployed my app onto heroku, but I got the following errors  One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist, so I changed my db settings to allow access from any where, but it's still giving me the same error. Anyone know why?


text:
Q: Solving the system $3a=(b+c+d)^3$, $3b=(c+d+e)^3$, ..., $3e=(a+b+c)^3$ for real $a$, $b$, $c$, $d$, $e$ $$\begin{align}
3a&=(b+c+d)^3 \\
3b&=(c+d+e)^3 \\
3c&=(d+e+a)^3 \\
3d&=(e+a+b)^3 \\
3e&=(a+b+c)^3
\end{align}$$
I tried to use inequality for
$((\sum \alpha)/n)^r\leq \sum \alpha^r/n$ by taking $\alpha=a_1+a_2+a_3$ where $a_1,a_2,a_3\in \{a,b,c,d,e\}$.

A:
Thanks to @CalvinLin for pinpointing that we cannot "assume WLOG" that the five variables are sorted as $a \le b \le c \le d \le e$.

We can still assume that the maximum element among them is $e$ $^{(*)}$. Then, by comparing $\color{red}{\text{red}}$ variables, we observe

*

*$$3d = (\color{red}e + a + b)^3 \ge (a + b + \color{red}c)^3 = 3e \\ \implies d \ge e \overset*\implies \boxed{d=e} \tag{1}$$

*

*$$3a = (b + c + \color{red}d)^3 \ge (\color{red}a + b + c)^3 = 3e \\\implies a \ge e \overset*\implies \boxed{a = e} \tag{2}$$

*

*$$3a = (\color{red}b + c + d)^3  \le  (c + d + \color{red}e)^3 = 3b \\\implies b \ge a = e \overset*\implies \boxed{b = e} \tag{3}$$

*

*$$3c = (d + e + \color{red}a)^3 \ge (\color{red}c + d + e)^3 = 3b \\ \implies c \ge b \implies \boxed{c = b} \tag{4}$$

Finally, $(1)\land(2)\land(3)\land(4) \implies \boxed{a = b = c = d = e}$.

Also, @AlbusDumbledore provided an equivalent solution in AoPS

A: Notice that for all $x,y$ we have $$x^2+xy+y^2 = {1\over 2}(x^2+(x+y)^2+y^2)\geq 0$$
Now we have:
$$3(a-b) = (b-e)\color{red}{\Big(} \underbrace{b+c+d}_x )^2+\underbrace{(b+c+d)(c+d+e)}_{xy}+(
\underbrace{ c+d+e}_y)^2\color{red}{\Big)} $$
so $${\rm sign} (a-b) = {\rm sign} (b-e) $$ and similary for:
\begin{align} {\rm sign} (b-c) &= {\rm sign} (c-a)\;\;\;\;(2) \\
{\rm sign} (c-d) &= {\rm sign} (d-b)\;\;\;\;(3) \\
{\rm sign} (d-e) &= {\rm sign} (e-c) \;\;\;\;(4)\\
{\rm sign} (e-a) &= {\rm sign} (a-d) \;\;\;\;(5)\\
\end{align}

*

*If $a>b$ then $b>e$ so $a>e$ and from $(5)$ we have $d>a$ so $d>e$ and now from $(4)$ we have $e>c$ and now $d>c$ so from $(2)$ we have $b>d$ so $b>c$ and now from $(2)$ we have $c>a$. So we have $$a>b>d>e>c>a$$ A contradiction.

*If $b>a$ we again get a contradiction, so $a=b=c=d=e=:x$ and all we need is to solve $x=9x^3$...


text:
Q: Is a request response always JSON? I'm trying to understand what exactly I'm getting back when I make a POST request using the Requests module — is it always JSON? Seems like every response I get appears to be JSON, but I'm not sure.
Where r is my response object, when I do:
print r.apparent_encoding

It always seems to return ascii
And when I try type():
>>>print type(r)
<class 'requests.models.Response'

I pasted the output from print r.text into a JSON validator, and it reported no errors. So should I assume Requests is providing my with JSON objects here?

A: A response can be anything. If you've posted to a REST endpoint, it will usually respond with JSON. If so, requests will detect that and allow you to decode it via the .json() method.
But it's perfectly possible for you to post to a normal web URL, in effect pretending to be a browser, and unless the server is doing something really clever it will just respond with the standard HTML it would serve to the browser. In that case, doing response.json() will raise a ValueError.

A: No, the response text for a POST request is totally up to the web service. A good REST API will always respond with JSON, but you will not always get that.
Example
A common pattern in PHP is
<?php

$successful_whatever = false;

if (isset($_POST['whatever'])) {
    # put $_POST['whatever'] in a database
    $successful_whatever = true;
}

echo $twig->render('gallery.twig',
                   array('successful_whatever' => $successful_whatever));

?>

As you can see the response text will be a rendered template (HTML). I'm not saying it is good, just that it is common.


text:
Q: How to add values to column using loop Pandas I would like to know how I can change the values of a column dynamically as I grab the information from a web scrape.
Currently, I have something like this:
number     name
12          NA
13          NA
14          NA
15          NA

and I would like to receive something like this:
number     name
12          Mike
13          Bob
14          Bobby
15          Mark

I have tried using this:

for number in phone_book:
    name = get_name()
    phonebook['names'][number] = name

and
phonebook.loc[phonebook.index[number], 'name'] = name

but it just sets the name of the last number for all:
number     name
12          Mark
13          Mark
14          Mark
15          Mark

How could I get it to add each name to its respective number?
Thanks

A: From your web scrape you could build a dict that looks like this:

name = {12: 'Mike', 13: 'Bob', 14: 'Bobby', 15: 'Mark'}

Then you can map to your existing frame:
df['name']=df['number'].map(name)
df = df.set_index('number')
print(df)

number   name
12       Mike
13        Bob
14      Bobby
15       Mark

A: You have several way to do it, first like @Quang Hoang comment :
phonebook.loc[phonebook.number == number, 'names'] = name

You can also do like this :
for number in phone_book:
    name = get_name()
    phonebook[phonebook["number"] == number] = name

or like this :
names = []
for number in phone_book:
    names.append(get_name())
phonebook["name"] = names

Note that the prefered method is the first one.


text:
Q: How to configure linux routing to send packets out through the same interface they were received on? I have the following routing table
10.0.1.0/24 dev eth0  proto kernel  scope link  src 10.0.1.151
10.0.10.0/24 dev eth1  proto kernel  scope link  src 10.0.10.151
default via 10.0.1.1 dev eth0

I have two links, one goes through a LAN and, through 10.0.1.1 out to the Internet. The other is a ADSL router (10.0.10.1) directly attached to eth1.
If I connect from the outside to the external IP address of 10.0.10.1 I get a timeout. If I change the default route to 10.0.10.1, connecting from the outside to the external IP address of 10.0.10.1 works. So this looks like a routing problem (packets come from 10.0.10.1, but go out of 10.0.1.1, being the default route), but I'm not sure how to solve it.
I actually want the default route to be 10.0.1.1, I just want to answer requests to the external IP of 10.0.10.1 via the same interface.

A: you need to use advanced routing tables offered by iproute2.
You set up 2 tables and send all traffic coming from an ip to a specific table, in this table you can set a default gateway.
To set the global default route you just prefer one interface over the other via metrics.
an example:

*

*adding the default gateways to the tables:

ip route add default via 10.0.1.1 table 101
ip route add default via 10.0.10.1 table 102

*

*add a rule that every traffic coming from a specific ip is send to the table:

ip rule add from 10.0.1.151 lookup 101
ip rule add from 10.0.10.151 lookup 102

*

*add the metric which gateway to prefer:

ip route add default via 10.0.1.151 metric 1000
ip route add default via 10.0.10.151 metric 2000
i hope this helps to get you started :)


text:
Q: TSaveDialog file extension and [ofOverwritePromt] issue There is a simple question already about the idea of the TSaveDialog and [ofOverwritePromt] at Delphi overwrite existing file on save dialog.
So my issue/scenario is following:

*

*I have a TSaveDialog

*I set the [ofOverwritePromt] in Options

*I set the filter to "PDF (*.pdf)|*.pdf"

*Filter index is set to 1

So now I execute the program and call the dialog. If the file I select WITH MOUSE or KEYBOARD (without typing) exists then save dialog asks me to overwrite with the message:

But if I do the same actions but type the filename like 'Test' without specifying the extension the save dialog does not confirm overwrite.
I know that actually it returns another filename "C:\Users\xxx\Desktop\Test" instead of "C:\Users\xxx\Desktop\Test.pdf". It is kind of not nice if the dialog asks you to save the file, but you need to type the extension..
So usually I handle it like this:
repeat
  { Ask for the file if not silent }
  if not dlgSave.Execute then
    Exit;

  { Read the filename from the save dialog }
  LTempFile := dlgSave.FileName;
  if not SameText(ExtractFileExt(LTempFile), '.pdf') then
    begin
      { Add the extension }
      LTempFile := LTempFile + '.pdf';

      { As we bypassed the overwrite check in dialog do it now }
      if FileExists(LTempFile) then
        if MsgWarn(Format('%s already exists. Replace?', [ExtractFileName(LTempFile)]), mbOKCancel) <> mrOk then
          Continue;
    end;

  Break;
until False;

Is there a way to do that more elegant without customizing the standard dialog?

A: My guess is that you do not set DefaultExt, which is why you get a blank extension returned. Use this property and you won't get the problem. If you use multiple filters, use the OnFilterChange event. Here is one way to do it:
procedure TFormMain.SigSaveDialogMainTypeChange(Sender: TObject);
begin
  case (Sender as TSaveDialog).FilterIndex of
    0: (Sender as TSaveDialog).DefaultExt := 'pdf';
    1: (Sender as TSaveDialog).DefaultExt := 'txt';
  end;
end;

It also means you don't have to check for the extension and change it!


text:
Q: React app - 404 page not appearing when typing incorrect url manually post deployment on heroku I successfully deployed my react app on heroku.com. I am able to navigate to pages only by clicking on the NavLinks that are available on the page.
Problem - the moment I enter anything manually in the url e.g. /contact or /product it does not work and gives the error
"Cannot GET /Contact" or Cannot GET /product. Nor this is show the 404 page available in the app
                   <Suspense fallback={<Loader />}>
                        <Routes>
                            <Route path="/" exact element={<Home/>} />
                            <Route path="/*" element={<PageNotFound />} />
                        </Routes>
                    </Suspense>

I noticed the same issue for some users on netlify. however, the same fix for SPAs did not work with Heroku.
please advise if there is any solution to this?
I tried this but did not get the expected results
"build": "react-scripts build && echo '/\* /index.html 200' | cat \>build/\_redirects",

A: If I understand your problem correct, you have two different options on fixing this.
The first and easiest is to use HashRouter instead of BrowserRouter. With this component a # is inserted in the urls so that the full url isn't sent to the server but instead managed by React.
The second option is to tell Heroku to let /index.html receive all requests, instead of trying to find /Contact when you request /Contact. I'm not familiar with Heroku so I don't know how to do this.


text:
Q: Based on query parameter open related components in angular I want to know that when we open localhost:4200/signin?url=login at that time I want to open login component and when we open localhost:4200/signin?url=register at that time I have to load register component. So what is the best way to achieve this functionality.

A: You haven't provided full details of your code, I have no clue where your router-outlet is or what /xyz path's component is doing. But if it was me, then, I would simple add the query param logic to whatever component /xyz path maps to and check the query param inside ngOnInit()
Example:
constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute
  ) {

  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe(val => {
      const param = val['url'];
      switch (param) {
        case 'login':
          this.router.navigate(['login']);
          break;
        case 'register':
          this.router.navigate(['register']);
          break;
      }
    });
  }

Stackblitz demo
Note: if you want a solution using Promise and route guard, then add full details of your code in the qeustion.
Happy coding!

A: you can add login and register route in your app-routing.module.ts or add children in you signin route
const routes: Routes = [
    {
        path: 'signin',
        component: SigninComponent
    },
    {
        path: 'signin/register',
        component: RegisterComponent
    },
    {
        path: 'signin/login',
        component: LoginComponent
    },
];

then navigate based on the parameters by using activatedRoute
constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
){}

ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
        switch (params['url']) {
           case 'login':
              this.router.navigate(['signin/login']);
              break;
           case 'register':
              this.router.navigate(['signin/register']);
              break;
}

    });

}


text:
Q: Python inherited class behaviour I have a question about python inherited class method, in the following code.
class B(object):
    def test(self):
        self.call()
    def call(self):
        print("Call from B")

if __name__ == "__main__":
    b = B()
    b.test()

from b import B

class C(B):
    def call(self):
        print("Call from C")

if __name__ == "__main__":
    c = C()
    c.test()

When I run this code, the result is
Call from C

The parent class method will call children's method. I want to know if it is an expected and stable behaviour? Because I also try the same logic in C++, it will print
Call from B

A: Yes, this is expected. c is an instance of C, but since C.test is not defined, c.test resolves to B.test. However, the corresponding call to self.call() invokes C.call because the runtime type of self is C, not B, and C.call is defined. Think of all Python methods as being virtual methods.

A: As a complement to chepner's answer, this C++ code exhibits the exact same behaviour as you have in Python:
#include <iostream>

class B {
public:
    void test() {
        call();
    }
    virtual void call() {
        std::cout << "Called from B" << std::endl;
    }
};

class C: public B {
public:
    void call() {
        std::cout << "Called from C" << std::endl;
    }
};

int main() {
   C c;
   c.test();        // will print Called from C
   return 0;
}

If you come from C++ think that all members are public, and all methods virtual.


text:
Q: How do I use the preposition for? I was seeking for a funny pun because it was for a grade.
I'm confused because I think the sentence is correct, but Grammarly says the for between seeking and a is unnecessary. Is this true? Why is that?

A:
I was seeking for a funny pun because it was for a grade.

The first 'for' is wrong. We say "looking for", but not "seeking for". This is because you can look at something, look in something etc, but the relationship to the object is already tacit in the meaning of 'seeking' so it does not need the preposition.
You should instead say either:

*

*I was seeking a funny pun

*I was looking for a funny pun


text:
Q: Проверка $_GET Как сделать проверку GET, нужно чтобы кроме цифр в диапазоне 1,20 не проходили, и фильтровать от инъекций, так число будет заносится в бд
A: Не особо люблю регулярки, да и с условием проще вам будет для понимания, все просто как 2x2 :)
if (is_numeric($_GET['id']) && $_GET['id'] <= 20 && $_GET['id'] >= 1) {
    echo 'okay';
} else {
    echo 'false';
}

тут проверяем являеется ли id числом, ставим в условие что для true id должен быть меньше или равнятся 20 и больше или равнятся 1.
A: if (in_array($_GET['num'], range(1,20))) echo "OK";

A: Вот так можно.
$num = $_GET['num'];
if ( $num >= 1 && $num <= 20 ) {
  echo true;
} else {
  echo false;
}

Вообще есть много вариантов, это один из них.

preg_match("/^[0-9]{1,22}$/",$book)

{1,22} — указывает на длину чисел, а не на их диапазон.
A: Вы будете (не)приятно удивлены:
$num='14"ddfdfd';

if($num>=1 && $num<=20) echo 'true';

:)))
Например можно сделать так:
$num=intval($num)%21;
if($num){
 /*все ок*/}

A: Вижу что вопрос из прошлого, но у меня есть свое решение. Я использую ДВЕ функции, потому что Я так использую в своем коде. И диапазоны значений у меня разные. И проверять нужно отдельно длину числа и длину строк. Поэтому у меня две функции.
Я подправил код именно под этот конкретный вопрос.
function is_numb($numb) {
  if (!preg_match('#^[1-9]+[0-9]*$#', $numb) or ! cl($numb, 1, 2) or $numb > 20) {
  return(false);
  } else {
  return(true);
  }
}

function cl($str, $min, $max) {
//проверяется длина переменной
  if (mb_strlen($str, 'utf-8') < $min or mb_strlen($str, 'utf-8') > $max) {
  return(FALSE);
  } else {
  return(TRUE);
  }
}

A: Я думаю, Вам надо использовать и почитать про регулярные выражения. Я сам их плохо знаю, но вроде в данном случае надо применить такое: [1-20].
Функции preg_match
A: Ну и как вариант жёсткое сравнение.
<?php
if(isset($_GET['num']))
    if(($_GET['num'] >== 0) && ($_GET['num'] <== 20))
echo 'Ok';


text:
Q: Why are placeholders used in python? a = "hello"
b = 32
print('%s %d' % (a, b))
print(a,b)

Both print statement will give out same output i.e hello 32.
But using print(a,b) is much easier then the other method so why the concept of placeholders exist in python.

A: Because sometimes you want to put things other than spaces between items.  What if I wanted to take a name, email address, and employer and generate some formatted result?
d = { "first": "Patrick",
      "last": "Haugh",
      "email": "Patrick.Haugh@example.com",
      "job": "My Job"}

print("{first} {last} <{email}> {job}".format(**d))
# Patrick Haugh <Patrick.Haugh@example.com> My Job

print("{last}, {first}: {job} <{email}>".format(**d))
# Haugh, Patrick: My Job <Patrick.Haugh@example.com>

You can then write code that accepts a format string, so the code itself doesn't have to change if you want to change how you format your output.  I recommend you read the documentation of the Format String Syntax to get more of an idea of what is possible.


text:
Q: Is there a way to count accesing threads to a primitive variable? I have a variable in my code, a simple primitive boolean x. Because of code complexity, I am not sure about the number of threads accessing it. Maybe it is never shared, or is used by only one thread, maybe not. If it is shared between threads, I need to use AtomicBoolean instead.
Is there a way to count threads accessing boolean x?
Until now I did a review of the code but it is very complex and not written by me.

A: If this is just for testing/debugging purpose, you could maybe do it this way:
If not yet the case, expose the boolean via a getter and count the threads in the getter. Here is a simple example where I make a list of all the threads accessing the getter:
class MyClass {

    private boolean myAttribute = false;

    private Set<String> threads = new HashSet<>();
    public Set<String> getThreadsSet() {
        return threads;
    }

    public boolean isMyAttribute() {
        synchronized (threads) {
            threads.add(Thread.currentThread().getName());
        }
        return myAttribute;
    }

}

Then you can test
MyClass c = new MyClass();

Runnable runnable = c::isMyAttribute;

Thread thread1 = new Thread(runnable, "t1");
Thread thread2 = new Thread(runnable, "t2");
Thread thread3 = new Thread(runnable, "t3");

thread1.start();
thread2.start();
thread3.start();

thread1.join();
thread2.join();
thread3.join();

System.out.println(c.getThreadsSet());

This outputs:
[t1, t2, t3]

EDIT:
Just saw that you added that the attribute is accessed via setter, you can adapt the solution and log Threads in the setter

A: Always access the variable with a getter and write down a logic to obtain the thread id whenever a new thread tries to get the primitive value . whenever the thread terminates , use shutdown hook to remove that threadId from that list. The list will contain the Ids of all the threads currently holding the reference to that variable.
 getVar(){
countLogic();
return var;}

countLogic(){
if(!list.contains(Thread.getCurrentThread().getId)){
list.add(Thread.getCurrentThread().getId);
Runtime.getRuntime().addShutdownHook(//logic to remove thread id from the list);
}

Hope it helps


text:
Q: "npm init" does not create node_module folder and other files sorry for novice question.
I have already node in my system.
node -v
 v4.4.0
npm -v
2.14.20

To make a new node project i have run the command npm init, but it only creates a pacakage.json file which contains general information.
Meanwhile I expect it to create basic essential files (a set of files and folder including node_module and index.js)
What should i do?

A: After "npm init" you want to install the modules you need by running "npm install  --save<-dev>". This will create a node_modules directory with the relevant modules and will add them to the package.json file so that executing "npm install" will auto' download and install them.
Regarding auto generating files, some IDEs will do that for you.


text:
Q: Как прочесть запись функции с указателем Изучаю указатели и в одном учебнике нашел вот такое объявление функций:

*

*void (*(*p)(void))(int);

*int (*f(void))();
Мне не совсем понятно, как эту запись прочесть. Предполагаю, что в первом случае это "указатель на функцию, принимающую void, результат которой - указатель на функцию, принимающую int. Подскажите кто-нибудь, как правильно?

A: Можно использовать сервис https://cdecl.org/.
Тогда:

*

*void (*(*p)(void))(int); <=> declare p as pointer to function (void) returning pointer to function (int) returning void.

*int (*f(void))(); <=> declare f as function (void) returning pointer to function returning int.

A: Да, (1) расшифровали правильно.
Объявления нужно начинать читать с середины, с имени переменной или функции. (В ситуациях, когда имени нет, например у безымянного параметра функции, то нужно найти то место, где могло бы быть имя. Проще всего найти на глазок.)
Дальше нужно двигаться сначала до упора вправо (до конца или до закрывающей скобки), потом до упора влево (до начала или до парной открывающей скобки). Если мы были внутри скобок, то повторить оба шага снаружи скобок, столько раз сколько нужно.
         p               // p - это
                                     // Смотрим вправо - там пусто. Смотрим влево.
        *p               // указатель на
       (*p)                          // Пропускаем скобки. Опять смотрим вправо.
       (*p)(void)        // функцию с параметрами (void), возвращающую
                                     // Теперь влево.
      *(*p)(void)        // указатель на
     (*(*p)(void))                   // Пропускаем скобки. Опять смотрим вправо.
     (*(*p)(void))(int)  // функцию с параметрами (int), возвращающую
                                     // Теперь влево.
void (*(*p)(void))(int)  // void

Домашнее задание - повторить то же самое для (2).


text:
Q: CSS Class Visible Only On Hover Only - Not Working So the final result I am trying to achieve is only show  .panel-text  when user hovers over panel. In this case I tried the overlay CSS class, since it covers the entire div. Yet whatever I do either the text doesn't show at all no matter hovering or idle or the text is displayed always. Below is what I have tried.
.panel-text {
    display: none
}

.panel-overlay:hover .panel-text {
     display: block
}

 The above only hides .panel-text always. Another attempt at it is below:
.panel-text { opacity: 0; }

.panel-overlay:hover panel-text { opacity: 1; }

Now I have attempted to try  .panel-title  as well  .panel-button .
Any help is greatly appreciated, all other posts shown display what I have been using. Even if we have to display an icon when  .panel-text  is hidden could work out.
Somwthing link this is what should happen

Link

A: Do it in this way.
.panel-text {
     visibility: hidden;
}

.panel-overlay:hover .panel-text {
     visibility: visible;
}

A: So for some reason nothing was working when trying to use with .panel-overlay, so trying the image wrapper did the trick. Using visibility or display will not perform correctly still. Below CSS worked out, works exactly example provided (link) except icon, will work on that later.

panel-text { opacity: 0; }
panel-mainimage-wrapper:hover .panel-text {opacity: 1; }


text:
Q: If you have designed (and implemented) a programming language, what to do to make it gain attention/popularity? Let's say you have created a programming language, maybe because there was a problem which was unfeasible to try to solve using existing languages, what would you do to market it (and so on) in order to make it gain attention in the software engineering (or academic etc. depending on the purpose of the language) industry?

A: Unfortunately there's not a whole lot you can do to MAKE something popular.  Take for example the popular game for the apple platform Angry Birds.  The company that made that game had created many many games prior that were only marginally used in comparison.  Then there was just something about Angry Birds that just struck with people... then they told their friends who told their friends to the point that it seems like almost everyone owns/has played/knows about it.  The same thing is true of programming languages.  You make it... then its either a success in time or its not.  The only real things you can do is try to promote it with friends, colleagues, etc.  Certain things will influence its success such as speed, ease of use, functionality, versatility, etc.  Its these areas that are most worth your time and effort.
EDIT:  Well I actually just thought of something... volume might be with in your control.  If you're extremely creative you could just start pumping out hundreds of different programming languages... eventually the odds would get very good that one of them would become popular...

A: Flip this around and ask yourself why someone would want to use your new language?

*

*What does it provide that existing languages don't provide?  Are the advantages big enough to warrant someone taking the plunge ...

*Is the language specified?  Is the specification complete?  Is it stable?

*Are the runtime libraries available?

*Is there a decent tool chain?  Compilers, debuggers, IDE support.

*Are there real people using it to do real projects?

*Are there examples?  Case studies?  Tutorials?
If the answer to many of these questions is "err ... no", then it is too soon to market your language.

A: make it fun to use. Besides that have really great documentation! That is always the first thing I look at when trying to evaluate something new.
Actually the thing a new language needs to get picked up by a lot of people is going to be a Book, By O'Reilly or the Prags

A: Use it.
Use it as your primary development tool. When you run into its failings, address them, because you can afford to change basically whatever you want about it before it becomes popular. The language will improve and solidify over time. As you produce more and more great applications written in your language, people will take notice of it and begin to take it seriously as a tool, and they might start using it. That's step one.
Step two is to keep using it, and make it as easy as possible for the people who might want to use it. That means top-notch documentation and examples, actively promoting the language to everyone you can, and getting your users to actively promote it by making it good enough to use as a primary tool.
But it all starts with using it yourself for real tasks. If you never get to that point, neither will anyone else.

A: The same as any other thing you've invented, create lots of examples of useful stuff you've built using it.

A: Why would you create another programming language? Unless you want to learn some fundamental CS concepts to improve your day to day programming writing a programming language in order to make it popular seems like a waste of time. Then again if you're really set on creating a popular programming language then targeting the JVM or the CLR or LLVM is probably the way to go.

A: Marketing.
That and assuming the this problem that people have affect enough people. I know Ruby got really popular cause of the MVC framework rails. They also had a huge marketing team. Microsoft C# is very popular because they would try to push it on everything. XNA framework uses C# and to do games on their platform (PC, ZUNE, 360, what have you), you got this neat XNA framework that uses C#.
So yeah, it seems like you have to be proactive and push for it or have something so significant that you don't have to do marketing (scala for example). Google Go language for example isn't taking off. I think only time will tell.


text:
Q: Why server-side script is better when making a contact form? I searched over the web and I found that a lot of people say that server-side script is better when making a contact form for a website... Can someone tell me why, please?
In my little experience I appreciate when a contact form is able to hightlight istantly when I wrote a wrong email, or a field is missing, rather than waiting for the answer of the server after processing the input in a php page. Maybe is better to implement both jquery validating and server-side validating?

A: They must be talking about the form validation. Client side validation is usually done with JavaScript/jQuery which can be easily manipulated using tools like Firebug. If user disables his JavaScript, the validation will fail and wrong data will be posted, inorder to prevent that, Server Side Validation is used for example, PHP, ASP.
The data is posted to the server, server validates the data, if it's incorrect, it will throw back the error to the user, and the most important is that server side validation cannot be manipulated/modified easily.

Now you may ask why to validate Client Side if it can be modified/broken easily? Well, not everyone is intelligent to fool your validation, home/normal users often forget some fields to fill up which are compulsory, if you do not keep a client side check at all, your server will get more and more requests directly, thus increasing the load, inorder to prevent that, you need to keep a client side check as well, which will prevent the form details to be posted to the server directly, thus decreasing the server load.
Also, it will save the time for your users, JavaScript validations are very quick, the users are responded with the related error messages when they are typing, or they move to the next field or very soon after the submit button is pressed. Where as server validation will make the process lengthy as forms will be submitted first, server will validate, and than it will return the message. Not much friendly for an user huh?

So the bottom line is validate both, Client Side and Server Side, but make sure you DO VALIDATE Server Side.

A: If you use client side languges like javascript or jquery for validation then modern browsers have the option to turn off or disable javscript and if they do so then validations will not work.But its not applicable in the case of server side validations.You can refer these links for more
http://www.dzyngiri.com/client-side-vs-server-side-validation/
JavaScript: client-side vs. server-side validation

A: You can perform sending and validating on server side but you can also provide basic validation on client side. Thanks to that you can notify user when something is wrong instantly. But also you will be sure that all data is correct (because of server side validation).


text:
Q: SELECT DISTINCT ON expressions must match initial ORDER BY expressions in typeorm query I have a query that I want get rows with unique item_id and sort them according to timestamp.
But I get this error everytime from this code
    const boxPreviewActivities = await this.activityLogEntryRepository

      .createQueryBuilder('activityLogEntry')
      .where("activityLogEntry.activity = 'BOX_PREVIEW'")
      .andWhere('activityLogEntry.projectId = :projectId', { projectId })
      .andWhere('activityLogEntry.userSub = :userSub', { userSub: user?.sub })
      .andWhere((qb) => {
        const subQuery = qb
          .subQuery()
          .select(
            "DISTINCT activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'"
          )
          .from(ActivityLogEntryEntity, 'activityLogEntry')
          .where("activityLogEntry.activity = 'BOX_DELETE'")
          .getQuery();
        return `activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' NOT IN (${subQuery})`;
      })
      .distinctOn([
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' ",
      ])

      .orderBy('activityLogEntry.timestamp', 'DESC')
      .limit(limitNumber)
      .getMany();

    return boxPreviewActivities;
  }

** ERROR [ExceptionsHandler] SELECT DISTINCT ON expressions must match initial ORDER BY expressions
QueryFailedError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions**
if I add this two order functions at the and, I dont get error but my query not sorting according to timestamp, instead sort only with item_id. Actually I only want to sort according to timestamp. How can I refactor my query to make it working ?
  .orderBy(
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'",
        'DESC'
      )
      .addOrderBy('activityLogEntry.timestamp', 'DESC')


text:
Q: ngrok having issues starting - X509 certificate signed by unknown authority I'm using ngrok 3.1.1 and trying to open up port 8000 so I can do some local testing. However, I keep running into some issues.
First off, I've downloaded and installed ngrok from the official site, and then added by authorisation token using:

ngrok config add-authtoken blahblahblahcrazywordsmoustache

So far so good. Then, trying to open ngrok using:

ngrok http 8000

Yields the following errors:

reconnecting (x509: certificate signed by unknown authority)

Followed by:

reconnecting (jsonHTTP.Lookup: No such host: tunnel.ngrok.com)

And...

reconnecting (resolved tunnel.ngrok.com has no records)

The ngrok.yml looks like this:
root_cas: trusted
version: "2"
authtoken: ohlooksomelettersarenttheynice

Any idea what I can do? This is on a corporate network, with various firewalls etc. I'm told that ngrok will create a url that I can use in my code tests, but we can't whitelist that url until we know what it is, and we don't know what it is until ngrok starts and generates it.

A: Okay, not quite a solution but more of a work-around.
Disconnected my computer from the corporate network, used a wifi dongle and hotspotted to my phone.
Got an error saying that my account wasn't authorised to use custom CAs. Wracked my head for a bit until I remembered that I had seen cas before, in the yml file. Removed the

root_cas: trusted

from the yml, and all working fine and dandy.


text:
Q: Create a DLL from a TLB Assembly I am having some performance problems when calling a COM TLB methods from C# using the dynamic keyword (more information here). Scince I have not had any luck trying to optimise such call I am now looking at a way to convert my TLB library to a native wrapper DLL which I can use directly in my C# project (at this stage I am not even sure that this will help, but instead abstract the performance problems down a layer).
I have used tlbimp.exe to create a .dll from my COM .tlb file (which is registered) using the VS2013 command prompt and the command
tlbimp F:\SomeDir\GrpSvr.tlb /out:F\SomeDir\GrpSvr.dll

This has produced a managed wrapper C# .dll that I can inspect this using dotPeek. It contains the expected namespace
namespace GRPSVR
{
    [TypeLibType(TypeLibTypeFlags.FCanCreate)]
    [Guid("FFB54BC4-B15E-11D1-99BC-0000E803C444")]
    [ClassInterface(ClassInterfaceType.None)]
    [ComImport]
    public class GrpCallClass : IGrpCall, GrpCall { /*Expected Methods et al.*/ }
}

and the two interfaces IGrpCall containing the full template for the generated class and and empty interface GrpCall. I register this .dll using regasm.exe and
regasm F:\SomeDir\GrpSvr.dll

Now, I include a reference to this .dll in my project and attempt to instantiate the GrpCallClass class via
private GRPSVR.GrpCallClass grpSvr = new GRPSVR.GrpCallClass();

But this give the compile time error:

Interop type 'GRPSVR.GrpCallClass' cannot be embedded. Use the applicable interface instead.

So then I try
private GRPSVR.IGrpCall grpSvr = new GRPSVR.GrpCall();

and this works at compile time but at run time I get a

Additional information: Retrieving the COM class factory for component with CLSID {FFB54BC4-B15E-11D1-99BC-0000E803C444} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

But I have registered the .dll.

*

*Will this approach help increase the performance of calling method in the initial COM TLB assembly?

*Can someone explain what I am doing wrong and how I can convert my COM .tlb library into a native wrapper .dll?
Thanks for your time.

A:
I register this .dll using regasm.exe

That was a fatal mistake.  That overwrote the registry keys for the native COM server.  Regasm should only ever be used when the server was written in a .NET language.  You will have to re-install the server to repair the damage.  Be sure to run Regasm /unregister first to clean up the registry.

and empty interface GrpCall

That you see an empty interface is the reason you have to use the dynamic keyword in your C# code.  The author of the COM server only permits you to use it late-bound.  The equivalent of [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] in .NET.  This is not uncommon, it avoids a lot of DLL Hell misery.  But sure, late-binding isn't very fast since an extra call is needed at runtime to find the dispid of the method you are calling.  Setting up the stack frame to make the call is slow as well, every argument has to be converted to a VARIANT.  A x10 slowdown compared to a early-bound call is pretty normal, could be several orders of magnitude for a simple property.
There isn't anything you can do to avoid this, you'll have to work with the server author to get ahead.  A pretty-please-with-cheese-on-top is the way to go about it, ask for a dual interface.  Expect a "no", you may get a "yes".


text:
Q: С# (Новичок) 2 строки переписать в 1ну С#
Всем привет!) Есть строки вводимые пользователем (с одинак-м кол-м символов и только цифры без пробелов)
koordShipr1  (например он ввел- 026)
koordShipr2  (например он ввел- 147)
Нужно их переписать в новую строку koordShipr3 таким образом (012467)
//Отметил жирными чтобы было понятней)

A:   var str1 = "026";
  var str2 = "147";
  var builder = new StringBuilder();
  for (var index = 0; index < str1.Length; index++)
  {
    builder.Append(str1[index]);
    builder.Append(str2[index]);
  }
  Console.WriteLine(builder.ToString());


text:
Q: Coping with Lagging Enum Support The Entity Framework will not support enum's until EF 5.0 (scheduled to ship soon).
Entity Framework 4.2 enum support
http://blogs.msdn.com/b/efdesign/archive/2011/06/29/enumeration-support-in-entity-framework.aspx
http://visualstudiomagazine.com/blogs/data-driver/2012/01/entity-framework-4-3-gets-final-tune-up.aspx
WCF Data Services (and the oData standard) to not support enums

We understand that enums are common, unfortunately they never met tha
  bar so far. They are rather high on our list of things to do next
  though

(See: https://stackoverflow.com/a/3571378/141172)
I have begun a new project and am replacing enum's with something like:
public static class MyEnum
{
    public const int MyValue = 0;
    public const int AnotherValue = 1;
}

I'm sacrificing the guarantee that enum's provide that only defined values will be assigned in order to utilize important (and at this point fairly mature) infrastructure services.
Is there a better way to handle lagging enum support?  Once EF and WCF Data Services add enum support, is there likely to be another important framework on the horizon that will introduce enum support as slowly as these two have?

A: Well better than your example would be using an enum to hold the constant values and casting to int everytime. That way you can at least use the enum whereever it is possible rather than loosing everything.
enums never provide inescapable type-safety. But by extending the usage of enums as far as you can into the applications code and business logic, you get more and more safety against subtle usage errors.

A: Could you use a struct with a private constructor that defines a public static member for each value:
public struct FakeEnum
    {
        public static readonly FakeEnum MyValue = new FakeEnum(0);
        public static readonly FakeEnum AnotherValue = new FakeEnum(1);

        private readonly int _value;

        private FakeEnum(int value)
        {
            _value = value;
        }

        public int Value { get { return _value; } }

        // TODO: Equals and GetHasCode and Operators Oh My!
    }

Note: I haven't actually tried this out.


text:
Q: Importing Pillow module in Lambda I am trying to install a lambda function as shown on this blog...
https://www.obytes.com/blog/image-resizing-on-the-fly-with-aws-lambda-api-gateway-and-s3-storage
I followed these steps, uploaded the zip file and getting an error.
git clone https://github.com/obytes/resize_s3_images.git

cd resize_s3_images/

wget https://pypi.fcio.net/packages/14/41/db6dec65ddbc176a59b89485e8cc136a433ed9c6397b6bfe2cd38412051e/Pillow-6.1.0-cp36-cp36m-manylinux1_x86_64.whl

unzip Pillow-6.1.0-cp36-cp36m-manylinux1_x86_64.whl && rm Pillow-6.1.0-cp36-cp36m-manylinux1_x86_64.whl

zip -r resize_s3_images.zip .

When I try to test the function:

{   "errorMessage": "Unable to import module 'resize_s3_images':
  cannot import name '_imaging' from 'PIL' (/var/task/PIL/init.py)",
  "errorType": "Runtime.ImportModuleError" }

A: Install pillow package with pip at this directory like this.
pip install Pillow -t .

Then remove existig zip and make again.
rm -rf resize_s3_images.zip

zip -r resize_s3_images.zip .

Import Image from pil like this
from PIL import Image

If you still have problem then use lambda layers or move code into '/tmp/dependencies/' directory using os.system('cp <folder_name> /tmp/dependencies/)


text:
Q: Firebase crashlytics is not catching exceptions I have followed all the steps and installed the Firebase Crashlytics in my react native successfully. It is capturing the crashlytics().crash() but not js exceptions. My firebase.json is as follows:
{
    "react-native": {
      "crashlytics_disable_auto_disabler": true,
      "crashlytics_debug_enabled": true
    }
}

When i use try-catch block, and log the error using crashlytics().recordError(error) it gets recorded but the js errors aren't. How can i do that
EDIT: I have tried with release mode and it captures the error but not in the debug mode.


text:
Q: A compact set, which is not closed. I'm looking for a compact set, which is not closed.
I read somewhere that $Z^+$ are compact and not closed, but I don't understand why.
Are there any other examples of compact sets that are not closed and could you please explain?
I know that we can't look in the reals because every compact set in the reals is closed and bounded correct?

A: Let $X$ be an infinite set, and equip it with the cofinite topology (i.e., $F \subset X$ is closed iff $F=X$ or $F$ is finite). Then every subset of $X$ is compact: if $(U_{\alpha})_{\alpha \in I}$ is any open covering of $E$, then for any fixed $\bar{\alpha} \in I$ the set $U_{\bar{\alpha}}$ contains all but finitely many points of $E$, so fix $U_{\alpha_1}, \dots, U_{\alpha_n}$ that cover these remaining points.
I like this example because $X$ is a $T_1$ space, so in a sense it is "almost" Hausdorff.

A: In any metric space, all compact sets are closed.  To see this, let $(X,d)$ be a metric space, and $Y \subset X$ a non-closed set.  Since $Y$ is not closed, it does not contain all of its limit points, so there exists a point $y \not\in Y$ which is an accumulation point of $Y$.  Then, the collection
$$\mathscr{U} = \{U_\varepsilon\}_{\varepsilon > 0},$$
where $U_\varepsilon = \{x \in X : d(x,y) > \varepsilon\}$, is an open cover of $Y$.  However, any finite subset of $\mathscr{U}$, for example
$$\mathscr{V} = \{U_{\varepsilon_1}, \cdots, U_{\varepsilon_n}\}$$
is not a cover of $Y$.  To see this, let $\varepsilon = \min\limits_{i\in\{1, \cdots, n\}}\varepsilon_i$.  Then, the ball around $y$ of radius $\varepsilon$ is disjoint from every set in $\mathscr{V}$ and contains a point of $Y$ (since $y$ was assumed to be a limit point of $Y$).  It follows that $Y$ is not compact.
As Prism mentioned in the comments, we can show that any compact subset of a Hausdorff space (a class of topological spaces which includes metric spaces) must be closed.  So we have to look for a non-Hausdorff (non-metric) counterexample.  One such example is the set $X = \{x_1, x_2, x_3\}$ with the trivial topology $\tau = \{\emptyset, X\}$, where the set $Y = \{x_1\}$ is compact (since any open cover of $Y$ is finite), but $Y$ is not closed.

A: A typical example is $X=\{a, b\}$, with the topology ${\mathscr{T}}=\{ \varnothing, \{a\}, X \}$. Then the subset $\{a\}$

*

*is compact: every open cover of $\{a\}$ admits a finite cover;

*is not closed, since its complement is not in the topology ${\mathscr{T}}$.

*is actually open.
So a compact set can be open and not closed.


text:
Q: Type of PayPal button Im developing web application with credit system. It means that users can change money for credits. I just want to ask someone more experienced, what type of PayPal button is the best solution for this kind of application.
Thank for any hints.

A: Use a regular "Buy Now" button. You are selling a sort of prepaid service.


text:
Q: PQgetvalue() gets EXC_BAD_ACCESS I've called my SQL query like so (ommited error checking for post)
PGresult *result = PQexec(self.connection, "SELECT * FROM \"getNewPaths\"()");
const int numRows = PQntuples(result);

int row = 0;
for (int i = 0; i < numRows; i++) {
    char *path = PQgetvalue(result, row, 0);

As soon as I hit the PQgetvalue call I get the exception.  If I run that same SQL command inside of psql I do get back exactly what I'd expect to see.  The getNewPaths() function has a return type of:  TABLE(fullpath varchar, uuid uuid)
Since I'm asking for the first column of the first row, I'm not sure why I'm getting this error.
My mac PostgreSQL server is running 9.2.1, and my client is running 9.1.5

A: Just figured this out.  A macro was calling PQclear(result) before I was actually using the results.  Removing that fixed the problem.


text:
Q: How to stop logs from displaying in the terminal When I open an application from the terminal like jDeveloper, how do I stop the exception stacktrace within jdev from being displayed on the terminal?

A: Assuming that you are using bash as your shell and that jdev is your executable
jdev  &> /dev/null

will not show anything in the terminal. If you just want to redirect stderr then you could do
jdev 2> /dev/null


text:
Q: Why does my Google Apps script take so long to run when called with UrlFetchApp from a Google Spreadsheet? I am using a custom function to keep modify a sheet's row count as data from another sheet changes. To do this, I had to put the script that does the modification into a standalone Google Apps script, since custom functions called directly from spreadsheets do not have write permission. I then call UrlFetchApp.fetch from the custom function.
Everything works as I'd expect, but the problem is for some unknown reason the script runs as if each each expression that modifies the spreadsheet waits about 10 seconds before it executes. When I call it directly from my browser using the same URL I used in UrlFetchApp.fetch, the changes happen instantaneously.
Let's say I have the following:
var sheet = SpreadsheetApp.openById(...).getSheetByName(...);
sheet.getRange(1, 1).setValue(1);
sheet.getRange(2, 1).setValue(2);

If I were to run the script from the browser, the script finishes immediately. However, when invoked from my spreadsheet, it seems to wait about 10 to 15 seconds before each setValue expression runs. Any idea why that is and how I could make it run faster?


text:
Q: Simple Excel Macro Needed: Copy/Paste Data to a Specific Location Based on Multiple Criteria CONTEXT:
I have an empty database set up in Excel which I plan to use to keep track of my monthly expenses for budgeting purposes. What I would like to be able to do is open my spreadsheet, enter in the data from my receipt (date of purchase, type of purchase 'code', and the amount of purchase) and click my "Post Data" macro button to run this macro. I know how to set all of that up, I am just having trouble with writing the macro itself.
THIS IS WHAT I AM LOOKING FOR:
A macro that:

*

*Finds the correct row which has the date in cell C2 in column E (i.e. row 8 in my example)

*Finds the correct column based on the expense code in cell C2 within the range F2:M2 (i.e. column G in my example)

*Pastes the value I have input in cell C4 into the intersection of the aforementioned row and column (i.e. Cell G8 in my example)

WHAT HAS NOT WORKED:
I am able to get the desired result by generating the IF statement (in each of the data cells):
=IFERROR(IF(AND(E5=$C$2,F$2=$C$3),$C$4,""),"")

I was able to record this macro which copies and pastes this statement to all of my data fields (I have an entire year on my spreadsheet). After that, the macro copies and pastes values over the statements. The only problem is that this macro overwrites data previously entered, which is why I felt I needed a more complex macro.
Please point me in the right direction or where I can find out how to do this.
Screenshot (what I am trying to do):

Macro:
Sub CopyPasteData()
'
' CopyPasteData Macro
'

'
    Range("F5").Select
    ActiveCell.FormulaR1C1 = "=IFERROR(IF(AND(RC5=R2C3,R2C=R3C3),R4C3,""""),"""")"
    Range("F5").Select
    Selection.Copy
    Range("F5:M32").Select
    ActiveWindow.SmallScroll Down:=24
    Range("F5:M32,F36:M66").Select
    Range("F36").Activate
    ActiveWindow.SmallScroll Down:=27
    Range("F5:M32,F36:M66,F70:M99").Select
    Range("F70").Activate
    ActiveWindow.SmallScroll Down:=21
    Range("F5:M32,F36:M66,F70:M99,F103:M133").Select
    Range("F103").Activate
    ActiveWindow.SmallScroll Down:=21
    Range("F5:M32,F36:M66,F70:M99,F103:M133,F137:M166").Select
    Range("F137").Activate
    ActiveWindow.SmallScroll Down:=24
    Range("F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200").Select
    Range("F170").Activate
    ActiveWindow.SmallScroll Down:=21
    Range("F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200,F204:M234").Select
    Range("F204").Activate
    ActiveWindow.SmallScroll Down:=24
    Range( _
        "F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200,F204:M234,F238:M267"). _
        Select
    Range("F238").Activate
    ActiveWindow.SmallScroll Down:=21
    Range( _
        "F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200,F204:M234,F238:M267,F271:M301" _
        ).Select
    Range("F271").Activate
    ActiveWindow.SmallScroll Down:=21
    Range( _
        "F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200,F204:M234,F238:M267,F271:M301,F305:M334" _
        ).Select
    Range("F305").Activate
    ActiveWindow.SmallScroll Down:=24
    Range( _
        "F5:M32,F36:M66,F70:M99,F103:M133,F137:M166,F170:M200,F204:M234,F238:M267,F271:M301,F305:M334,F338:M368" _
        ).Select
    Range("F338").Activate
    Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
        SkipBlanks:=False, Transpose:=False
    ActiveWindow.ScrollRow = 344
    'deleted many lines...
    ActiveWindow.ScrollRow = 5
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Application.CutCopyMode = False
    Range("F5:M32").Select
    ActiveWindow.SmallScroll Down:=-9
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=18
    Range("F36:M66").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-15
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F70:M99").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F103:M133").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-9
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F137:M166").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-9
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F170:M200").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=24
    Range("F204:M234").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-15
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=36
    Range("F238:M267").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-6
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F271:M301").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=33
    Range("F305:M334").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.SmallScroll Down:=27
    Range("F338:M368").Select
    Application.CutCopyMode = False
    Selection.Copy
    ActiveWindow.SmallScroll Down:=-12
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveWindow.ScrollRow = 332
    'deleted many lines
    ActiveWindow.ScrollRow = 7
    ActiveWindow.ScrollRow = 5
    Range("A1").Select
End Sub

A: You need to use Find() to locate the correct column and row:
Sub Test()

    Dim sht As Worksheet
    Dim fD As Range, fT As Range, dt

    Set sht = ActiveSheet
    dt = CDate(sht.Range("C2").Value)
    Set fD = sht.Range("E5:E1000").Find(dt)
    Set fT = sht.Range("F2:M2").Find(sht.Range("C3").Value, lookat:=xlWhole)

    If Not fD Is Nothing And Not fT Is Nothing Then
        With sht.Cells(fD.Row, fT.Column)
        .Value = .Value + sht.Range("C4").Value
        End With
    End If

End Sub