text:
Q: What algorithm should be used when matching hobby? I have tens of thousands of user data in dating app. Each user has 5 non-overlapping hobbies.
need to list them by connecting the couples with the most matching hobbies.
example
user1: {
  name: sam
  hobbies: ["A", "B", "C", "E", "H"]
}
user2: {
  name: sam
  hobbies: ["E", "B", "C", "Z", "H"]
}
user3: {
  name: sam
  hobbies: ["A", "B", "C", "E", "J"]
}
result :
user1 - user3
if user1, user2, user3 hobby is same result is
user1 - user2,
user1 - user3,
user2 - user3
I would like to know some algorithms or hints

A: First observation if total distinct hobbies fits into 64-bit integer range, then we can store each user data as an integer whose binary representation represents a hobbies. For example:
0th bit -> hobby A
1st bit -> hobby B
2nd bit -> hobby C
and so on ...

If user-1 has hobby  ["A", "B", "C", "E", "H"] then its binary representation will be:
           H  E CBA
           10010111
Integer =  151

If user-2 has hobby  ["A", "B", "C", "E", "J"]  then its binary representation will be:
           J    E CBA
           1000010111
Integer =  535

Then, total matching hobbies in between user-1 and user-2 can be obtained simply finding total one bits in an integer obtained by performing bitwise AND operation of these two integers.
Bitwise AND of (151 & 535) = 23 (10111) which has 4 ones in binary representation.

      151 = 0010010111
      535 = 1000010111
----------------------
and_a_b   = 0000010111

Basically, Bitwise AND will keep 1 bit only if both bit position are 1s.
Here, total hobbies match is = 4 which is total 1 bits in and_a_b.

In c++, We can obtain this value simply applying __builtin_popcount(and_a_b).
We can get this in constant time in modern on modern hardware, since it provides POPCNT processor instruction for counting number of 1s bits (Link).
In order to find most matching score, we can simply iterate over every pairs of user and calculate matching hobbies by simply finding total 1s bit in bitwise AND of two numbers and maximize that score. Now, in order to find list of most matching pairs, we can perform same thing and compare with most matching score and put them in our list.

A: *

*create table hobby of hobbies
so create a list of all distinct hobbies you got in your data.

*convert your hobby strings in your data to numbers
simply take each hobby string and look for it in your new hobby table. When found the index you found it on is the number you looking for. If not found add new entry to hobby and use its index.
steps #1 and #2 can be done together. They might be speeded up by hashing and index sorting by the hash.

*brute force check of hobbies
now do 2 nested for loops to check each entriy agains each other entry in your data like:
for (i=0;i<entries-1;i++)
 for (j=i+1;j<entries;j++)
  ...

and inside count the number of identical numbers (hobbies). So again 2 for loops but counting to 5 instead of up to entries.


text:
Q: Architecture for stream analytics. Which broker I need? for research purpose I'm studying an architecture to do real-time (and also offline) data analytics and semantic annotation.
I've attached a basic schema:
I have some sensors linked to a raspberry pi 3. I suppose can handle this link with a mqqt broker like mosquitto.
However, I want to collect data on raspberry, do something, and forward them to a cluster of commodity hardware to perform real time reasoning with Spark or Storm (any hint about which?).
Then these data have to be stored in a NoSql db (Cassandra or HBase probably) accessible to an Hadoop cluster to execute batch reasoning, semantic data enrichment on them and re-store on same db. Therefore clients can query system to extract useful informations.
Which technology should I use in the red block?
My idea is for MQQT but Kafka maybe could fit better my purposes?

A: Spark vs Storm
Spark is the clear winner right now between Spark and Storm.  At least one reason is that Spark is much more capable of handling large data volumes in a performant way.  Storm struggles with processing large volumnes of data at a high velocity.  For the most part the Big data community has embraced Spark, at least for now.  Other technologies like Apex, and Kafka Streams are making waves in the Stream Processing space.
Kafka Producing to Raspberry Pi
If you choose the Kafka path keep in mind that the Java client for Kafka is by far, in my experience, most reliable implementation.  However, I would do a proof of concept to ensure that there won't be any memory issues since the Rasberry Pi doesn't have a lot of RAM on it.
Kafka At the Heart
Keeping Kafka in your RED box will give you a very flexible architecture moving forward because any process: Storm, Spark, Apex, Kafka Streams, Kafka Consumer can connect to Kafka and quickly read the data.  Having Kafka at the heart of your architecture provides you with a "distribution" point for all your data since its very fast but also allows for data to be permanently stored there.  Keep in mind that you can't query Kafka, so using it will require you to simply read the messages as fast as you can to populate other datastores or to perform streaming calculations.

A: You can evaluate Apache Apex for your use case as most of your requirements could be satisfied with it. Apache Apex also comes with Apache Malhar project which serves operator library for Apache Apex. Since you are deciding to use MQTT protocol, Apache Malhar also has prebuilt in AbstractMQTTInputOperator/AbstractMQTTOnputOperator which you can extend and it can serve as input broker. Malhar also comes with various operators which can connect to different NoSQL Dbs as well dumping to HDFS. Apache Apex may not require kafka in your proposed architecture. As you want to push data to Hadoop, being Hadoop native Apex actually can reduce our deployment efforts significantly.
Another interesting project I had come across is Apache Edgent which can help you to perform some real-time analytics at edge devices.
PS: I am a contributor to Apache Apex/Malhar project.

A: What about using Apache Nifi?
There is an article describing the use case very similar to yours. To output your data to HDFS you can use PutHDFS or PutHiveQL, then use Hive LLAP to provide the access to the data for your clients.
Using Apache Nifi you can deliver working prototype very fast with zero (or maybe almost zero) development.
Probably you will spend more time for performance tuning, deployment, and customization on productization step of your system, but this part is mandatory for any open source tool.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get a png file in a directory and rename it to a specific name python have only a single file in  dir with a png extension :  htp_nyaguwbf_1568431.png
how to fetch the file using python and not inputting file name. But by getting the file name using extension .png and change its name to  test.png
this code will fetch the file and store it in file variable.
import glob, os

for file in glob.glob("*.png"):
    print(file)

how to change the name of the file

A: import glob
import os

filename = glob.glob('*.png')[0]
os.rename(filename, 'test.png')

A: Here is how you can rename each file with numbers 1 to the amount of files:
import glob, os

for n,file in enumerate(glob.glob("*.png")):
    os.rename(file, f'file{n+1}.png')


text:
Q: Checking for a draw in Tic Tac Toe [Python] I have this Python program that plays tic tac toe between two human players. If Player A or Player B ever wins, it is announced and the program terminates. However, if the program ends in a draw, it will keep requesting user input.
I'm not sure how to check for a draw. Does it have to be within the while loop or does it require it's own separate function?
import sys

## Define and create tic tac toe gameboard
board = range(0,9)

def show_board():
    print board[0], '|', board[1], '|', board[2]
    print '---------'
    print board[3], '|', board[4], '|', board[5]
    print '---------'
    print board[6], '|', board[7], '|', board[8]

# Function used to check for winner
def line(char, box1, box2, box3):
    if board[box1] == char and board[box2] == char and board[box3] == char:
        return True

# Function used to automate process for checking every possible way to win
def all(char):
    # Horizontal check
    if line(char, 0, 1, 2):
        return True
    if line(char, 3, 4, 5):
        return True
    if line(char, 6, 7, 8):
        return True
    # Vertical check
    if line(char, 0, 3, 6):
        return True
    if line(char, 1, 4, 7):
        return True
    if line(char, 2, 5, 8):
        return True
    # Diagnol check
    if line(char, 0, 4, 8):
        return True
    if line(char, 2, 4, 6):
        return True

show_board()

# Initial while loop will ask for player A input and show the board as well
# check conditions to see whether or not player A wins. If player A wins,
# the program will terminate so it does not ask for player B input after.
while True:
    player_a = int(raw_input('Player A, please select a spot that is not taken \
(0-8): '))
    # Checks for empty spot and places an 'X' if it exists, otherwise
    # asks again.
    if board[player_a] != 'X' and board[player_a] != 'O':
        board[player_a] = 'X'
        show_board()
        # Check to see if Player A wins.
        if all('X') == True:
            print "Player A wins."
            sys.exit()
            break;

# While loop to ask for player B input and display the board as well as check
# the conditions as to whether or not player B wins. If player B wins, the
# program will terminate so it does not ask for player A input after.
        while True:
            player_b = int(raw_input('Player B, please select a spot that is \
not taken (0-8): '))
            # Checks for empty spot and places an 'O' if it exists, otherwise
            # asks again.
            if board[player_b] != 'O' and board[player_b] != 'X':
                board[player_b] = 'O'
                # Check to see if Player B wins.
                if all('O') == True:
                    show_board()
                    print "Player B wins."
                    sys.exit()
                    break;

                break;

    show_board()

A: Without extensively going through the code, I can tell you that a draw is occurs after 9 turns, and only if both Player A and B do not receive a win on that final turn. For your simple program, what I would do is create a global variable called ELAPSED_TURNS or something of the sort, that increments each time a player enters a character, and then after checking both of the players' win conditions, and if there is no win, check ELAPSED_TURNS. If it is equal to 9, then the game must be a draw.

A: Here's the function that does what you want.
def is_tie():
    for position in board:
        if isinstance(position, int):
            return False
    print "The game is a tie."
    sys.exit()

Put a call to is_tie() directly after both while loops like this...
while True:
    is_tie()
    player_a = int(raw_input(...

while True:
    is_tie()
    player_b = int(raw_input(...

If this is a learning exercise for you I would recommend refactoring your code to find a way wrap all your logic blocks into functions and getting everything to flow without the use of sys.exit().  Doing so will increase the readability and make it easier to splice in new logic.
EDIT to your comment:
You can create an integer test function using just try / except statements like this...
def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

Credit here:  Python: Check if a string represents an int, Without using Try/Except?
Your is_tie() function would then look like this:
def is_tie():
    for position in board:
        if is_int(position):
            return False
    print "The game is a tie."
    sys.exit()


text:
Q: Save transient field in Room Database Consider the following data model where status is provided by the API at the top level and message is provided at a nested level (this isn't really the case but just to illustrate the problem):
data class (
    @Json(name = "status")
    val status: Int,

    @Transient
    val message: String
)

Now, suppose I want to save this data model into my database. I'd change the model like so:
data class (
    @ColumnInfo(name = "status")
    @Json(name = "status")
    val status: Int,

    @ColumnInfo(name = "message")
    @Transient
    val message: String
)

the message field will not be saved into the database due to the Transient annotation. But what if I want to? How can I force Room to save the field but Moshi to ignore it.
The problem is I have no control over this API, or how it would change in the future, so removing @Transient and changing the name to some random complicated string is not an ideal solution, even if it will fix the problem.

Found a couple of related issues on Moshi:

*

*Moshi/94

*Moshi/1262
Apparently this is an age-old issue...

A: Maybe, can you use a mapper between your object and Room database ?
Like:
data class MessageEntity(
    @ColumnInfo(name = "status")
    val status: Int,
    @ColumnInfo(name = "message")
    val message: String
) {
// ...
}

data class Message (
    @Json(name = "status")
    val status: Int,

    @Transient
    val message: String
) {
 fun toEntity(): MessageEntity {// ...}
 fun fromEntity(e: MessageEntity): Message {// ...} // or Extensions
}


text:
Q: OutOfMemoryException - GC verbose confirmed a memory leak, what now? I'm monitoring an app whose GC verbose log looks like this:

The graph draws the amount of Used Tenured after the GC runs.
As you can see, there's an obvious memory leak, but I was wondering what would be the best next step to find out which component is holding around 50MB of memory each time the GC runs.
The machine is an AIX 6.1 running an IBM's JVM 5.
Thanks

A: The pattern in the chart definitely looks like a typical memory leak, building up in tenured space over time. Your best shot would be heap dump analyzers - take a heap dump for example similar to following
jmap -dump:format=b,file=dump.bin <your java process id>

and analyze the dump file for example with Eclipse Memory Analyzer.


text:
Q: Spark SQL + Date operations I want to understand the best way to solve date-related problems in spark SQL. I'm trying to solve simple problem where I have a file that has date ranges like below:
startdate,enddate
01/01/2018,30/01/2018
01/02/2018,28/02/2018
01/03/2018,30/03/2018

and another table that has date and counts:
date,counts
03/01/2018,10
25/01/2018,15
05/02/2018,23
17/02/2018,43

Now all I want to find is sum of counts for each date range, so the output expected is:
startdate,enddate,sum(count)
01/01/2018,30/01/2018,25
01/02/2018,28/02/2018,66
01/03/2018,30/03/2018,0

Following is the code I have written but it's giving me a cartesian result set:
val spark = SparkSession.builder().appName("DateBasedCount").master("local").getOrCreate()
import spark.implicits._

val df1 = spark.read.option("header","true").csv("dateRange.txt").toDF("startdate","enddate")
val df2 = spark.read.option("header","true").csv("dateCount").toDF("date","count")

df1.createOrReplaceTempView("daterange")
df2.createOrReplaceTempView("datecount")

val res = spark.sql("select startdate,enddate,date,visitors from daterange left join datecount on date >= startdate and date <= enddate")
res.rdd.foreach(println)

The output is:
| startdate|   enddate|      date|visitors|
|01/01/2018|30/01/2018|03/01/2018|      10|
|01/01/2018|30/01/2018|25/01/2018|      15|
|01/01/2018|30/01/2018|05/02/2018|      23|
|01/01/2018|30/01/2018|17/02/2018|      43|
|01/02/2018|28/02/2018|03/01/2018|      10|
|01/02/2018|28/02/2018|25/01/2018|      15|
|01/02/2018|28/02/2018|05/02/2018|      23|
|01/02/2018|28/02/2018|17/02/2018|      43|
|01/03/2018|30/03/2018|03/01/2018|      10|
|01/03/2018|30/03/2018|25/01/2018|      15|
|01/03/2018|30/03/2018|05/02/2018|      23|
|01/03/2018|30/03/2018|17/02/2018|      43|

Now if I groupby startdate and enddate with sum on count I see following result which is incorrect:
| startdate|   enddate| sum(count)|
|01/01/2018|30/01/2018|       91.0|
|01/02/2018|28/02/2018|       91.0|
|01/03/2018|30/03/2018|       91.0|

So how do we handle this and what is the best way to deal with dates in Spark SQL? Should we build columns as dateType in first place OR read as strings and then cast it to date while necessary?

A: The problem is that your dates are not interpreted as dates by Spark automatically, they are just strings. The solution is therefore to convert them into dates:
val df1 = spark.read.option("header","true").csv("dateRange.txt")
  .toDF("startdate","enddate")
  .withColumn("startdate", to_date(unix_timestamp($"startdate", "dd/MM/yyyy").cast("timestamp")))
  .withColumn("enddate", to_date(unix_timestamp($"enddate", "dd/MM/yyyy").cast("timestamp")))
val df2 = spark.read.option("header","true").csv("dateCount")
  .toDF("date","count")
  .withColumn("date", to_date(unix_timestamp($"date", "dd/MM/yyyy").cast("timestamp")))

Then use the same code as before. The output of the SQL command is now:
+----------+----------+----------+------+
| startdate|   enddate|      date|counts|
+----------+----------+----------+------+
|2018-01-01|2018-01-30|2018-01-03|    10|
|2018-01-01|2018-01-30|2018-01-25|    15|
|2018-02-01|2018-02-28|2018-02-05|    23|
|2018-02-01|2018-02-28|2018-02-17|    43|
|2018-03-01|2018-03-30|      null|  null|
+----------+----------+----------+------+

If the last line should be ignored, simply change to an inner join instead.
Using df.groupBy("startdate", "enddate").sum() on this new dataframe will give the wanted output.


text:
Q: Maven import dependencies with classifier tag I try to import a dependency in POM in the following way:
<dependency>
    <groupId>org.bytedeco.javacpp-presets</groupId>
    <artifactId>caffe</artifactId>
    <version>master-1.3.3-SNAPSHOT</version>
    <classifier>linux-x86_64</classifier>
</dependency>

Because in local repository of this artifact, there are 4 jar files:
1) caffe-master-1.3.3-SNAPSHOT.jar 2) caffe-master-1.3.3-SNAPSHOT-javadoc.jar 3) caffe-master-1.3.3-SNAPSHOT-sources.jar and 4) caffe-master-1.3.3-SNAPSHOT-linux-x86_64.jar, if I don't use "classifier" tag, only 1) 2) 3) will be imported. So to import all 4 jar files, I add this classifier.
The problem is, it still cannot import the 4) jar file into my project. But for other artifacts in the same project, I can import all 4 jar files in this way. Anyone would like help? Thanks.


text:
Q: Problems creating an ad-hoc network in Windows 7 Windows 7: I created an ad-hoc network (wireless for 2 laptops), it worked fine - we could use the internet with no problems. The next day I tried to make again the ad-hoc network, I went through all the steps I did before, BUT, when I'm asked for network name, I put it there and then it just creates the network with local access only!  It doesn't even ask me anymore if I want to share the internet connection.
I don't know what to do now, suggestions?

A: The simpler solution is to use something like VirtualRouter or Connectify, which use Windows 7's virtual WiFi support to create an access point using your wireless card. This allows other computers to connect as if they were using a regular wireless access point, without any ad-hoc networks.


text:
Q: Can I turn off PyCharm autocomplete for a specific class Is there a way in Python on in Pycharm to indicate that I don't want the type hint of a specific class to be displayed to the user in the autocomplete window?
I have a class Result that may contain either a string, e.g. 1+2 or an instance of another class Exercise. The Exercise class contains 2 numbers and can generate an exercise string from them.
Result class uses Pydantic (also see footnote) to validate the input as a str or Exercise types, so I must declare a Union of types:
exercise: Union[str, Exercise]

At the end I want future users of my code to get autocomplete suggestions that treat the property exercise as str only and ignore the Exercise type.
In the screenshot you can see that the autocomplete window has suggestions for both str and Exercise types.

So my question is: Is there a way in Python on in Pycharm to indicate that I don't want the type hint of a specific class to be displayed to the user in the autocomplete window?

Footnote

*

*In the example I am using Pydantic to define Exercise(BaseModel) to make my point, but you can use the other definition of Exercise.

Code
from typing import Union

from pydantic import BaseModel

#
# class Exercise:
#     def __init__(self, num1: int, num2: int):
#         self.num1: int = num1
#         self.num2: int = num2
#
#     def convert_to_str(self) -> str:
#         return f'{self.num1} + {self.num2}'

class Exercise(BaseModel):
    num1: int
    num2: int

    def convert_to_str(self) -> str:
        return f'{self.num1} + {self.num2}'

class Result(BaseModel):
    exercise: Union[str, Exercise]

    def convert_to_str(self):
        if isinstance(self.exercise, Exercise):
            self.exercise = self.exercise.convert_to_str()

if __name__ == '__main__':
    exercise_example: Exercise = Exercise(num1=1, num2=2)
    result1: Result = Result(exercise=exercise_example)

    print(result1.exercise)
    result1.convert_to_str()
    print(result1.exercise)

    print(result1.exercise.split('+'))

A: The example you show seems odd to me because it could be argued that avoiding str and using just Exercise could provide a better object oriented approach.
Assuming that you actually want an exercise: str field but you want a way to initialize it by converting an Exercise instance to str, you could use a @validator:
from typing import Any

from pydantic import BaseModel, validator

class Exercise(BaseModel):
    num1: int
    num2: int

    def convert_to_str(self) -> str:
        return f'{self.num1} + {self.num2}'

class Result(BaseModel):
    exercise: str

    @validator("exercise", pre=True)
    def _convert_exercise(cls, exercise: Any) -> Any:
        if isinstance(exercise, Exercise):
            return exercise.convert_to_str()
        return exercise

if __name__ == '__main__':
    exercise_example: Exercise = Exercise(num1=1, num2=2)
    result1: Result = Result(exercise=exercise_example)

    print(result1.exercise)
    print(result1.exercise.split('+'))

Output:
1 + 2
['1 ', ' 2']

That validator will only convert Exercise instances to str. Instances of other classes will remain intact. pre=True will cause this validator to be called prior to other validations. The exercise field will be a str and not a Union and any IDE should only show you autocomplete suggestions for str.


text:
Q: I am new to React js and I am trying to create a project using it.while using map function, i am facing error I am creating  a website to deliver news.
I am beginner in reactJS and I am facing error:"TypeError: Cannot read properties of undefined (reading 'map')"
I tried searching this online but was not able to understand what is wrong with this code.
Can somebody please help me?
Below is the code snippet:
import React, { Component } from "react";
import NewsItem from "./NewsItem";

export class News extends Component {
  constructor() {
    super();
    console.log("HELLO there");
    this.state = {
      articles: this.articles,
      loading: false,
    };
  }
  render() {
    return (

        This is a news component
          //This is the part which shows error
        {this.state.articles.map((element) => {
          console.log(element)
        })}

            <NewsItem imageUrl="https://photos5.appleinsider.com/gallery/44585-86572-210921-macOSBigSur-xl.jpg" />

    );
  }
}

export default News;

A: Your this.articles does not exist in you class as a property. You can simply add
this.articles = [ { id: 1, title: "Article 1" }, { id: 2, title: "Article 2" } ];

after your console.log() statement in the constrcutor.


text:
Q: Using a certificate from Keychain in a Mac application I am trying to build a mini-application to codesign one Mac OS X application with codesign utility and my developer certificate in keychain. To do that I use NSTask, like that :
[task setLaunchPath:@"/usr/bin/codesign"];
// ...
NSString *certificateName = @"\"3rd Party Mac Developer Application: Firstname Lastname\"";
NSString *appName = @"\"/path/to/My App.app\"";
NSArray *args = [NSArray arrayWithObjects:@"-s", certificateName, appName, nil];
// ...
[task launch];

I use a NSPipe to catch the output and I got this error message : no identity found...
But if I launch this command manually via Terminal, the application is well signed (so it's not a problem of certificate badly installed, etc).
I think issue comes because my application can't access the certificate in keychain (but me I can via Terminal).
Does someone already experienced this problem ?
Thanks in advance, Best.

A: You should not embed additional quotation marks in the arguments to NSTask:
NSString *certificateName = @"3rd Party Mac Developer Application: Firstname Lastname";
NSString *appName = @"/path/to/My App.app";

Spaces in the arguments are handled automatically, and do not require quotation marks.


text:
Q: Is the complement of image equivalent to the image of the complement?
Let $f:X \to Y$ and $B\subseteq X$. Prove or disprove $f(\overline B)=\overline{f(B)}$, where $f(B)$ is the image of $B$ in $f$.

I thought it was false, but my counterexamples proved me wrong, so I need help in proving it is true.
Any guidance is appreciated!

A: There are three mutually exclusive possibilities:
(A) For all $X,Y,f,B$, we have the equality $f(\overline B)=\overline{f(B)}$.
(B) For all $X,Y,f,B$, we have the inequality $f(\overline B)\neq\overline{f(B)}$.
(C) Sometimes $f(\overline B)=\overline{f(B)}$, and other times $f(\overline B)\neq\overline{f(B)}$.
The original question asks you to prove whether (A) is true or false. If (A) is false, then you don't necessarily have to decide whether (B) or (C) is true.

I thought it was false, but my counterexamples proved me wrong...

...Okay, that means you investigated some particular counterexample $X,Y,f,B$, and you computed that $f(\overline B)=\overline{f(B)}$ after all. And you did this a few times.
These counterexamples prove that (B) is false. That's progress!

...so I need help in proving it is true.

Not quite. For all you know at this point, either (A) or (C) could still be true. So your next task isn't necessarily to prove (A).
In fact, it turns out that (A) is false, and the truth is (C): Sometimes $f(\overline B)=\overline{f(B)}$, and other times $f(\overline B)\neq\overline{f(B)}$. Consider, for example, the function $f(x)=42$.


text:
Q: Comparing un-ordered dictionary values along with keys We have 2 dictionary,i would like to apply following conditions and update the old_x with new_x
old_x = {"A":[1,2,3,4,5],"B":[],"C":[10,30]}
new_x = {"B":[3,4,5],"A":[1,5,3],"C":[30,10],"D":[2]}

*

*ordering of the elements inside the lists values is not important.
ex: "C"

*ordering of Keys inside of dictionaries is not important.
ex: un-ordered keys in new_x

*Any new Key in new_x which is not present in old_x should be added to old_x.
ex: "D"

*updating the old_x value lists with new_x values if new element found in lists of new_x, similarly remove the values if new_x doesn't contain those values of old_x.
ex: "B" for updating, "A" for removing

Expected output on comparing:

old_x = {"A":[1,5,3],"B":[3,4,5],"C":[10,30],"D":[2]}

Please help me creating a function for this?
Note: Elements & Keys in new_x is not always the same.I Kept them similar to demonstrate the keypoints of the problem.

A: If the order of keys/values in arrays is not important, why not just call:
old_x.update(new_x)

A: Isn't this simply:
old_x = new_x

You can make a copy like this:
old_x = dict(new_x)


text:
Q: Fatal error: Call to a member function execute() on a non-object $sql = "UPDATE Student ".
           "SET score = $total_score ".
           "WHERE student_id = $student_id";
    $stmt = $mysqli->prepare($sql);
    $stmt->execute();
    $query = "SELECT faculty_id ".
             "From Student s ".
             "WHERE student_id =$student_id";
    $state =$mysqli->prepare($query);
    $state->execute();
    $state->bind_result($faculty_id);
    if ($state->fetch())
    {if (strpos($faculty_id, '1') > 0) {
            include ('./Registration_Step_3_Student.php');
        } else
        {
            include ('./Registration_Step_3_Mentor.php');
        }
    }

So whenever i try to run my second query called $state, i get this error that states it cannot be execute. I am relatively new to SQL and PHP so any help would be appreciated. Thanks!

A: Since you are using mysqli you should learn how to bind properly, please read up on bind_Param
mysqli_stmt::prepare returns an false when failing, you should never execute the statement when it does:
$sql = "UPDATE Student SET score = ? WHERE student_id = ?";
$stmt = $mysqli->prepare($sql);
if($stmt){
    $stmt->bind_param('si', $total_score, $student_id);
    if($stmt->execute()){
        $query = "SELECT faculty_id From `Student s` WHERE student_id = ?";
        $state =$mysqli->prepare($query);
        $stmt->bind_param('i', $student_id);
        if($state->execute()){
            var_dump($state->fetch());
        }else{
            echo 'SELECT failed';
             printf("Error: %s.\n", $state->error);
        }
    }else{
       echo 'failed to execute UPDATE';
    }
}else{
      echo 'failed to prepare() UPDATE \n';
       printf("Error: %s.\n", $stmt->error);

}

Hope this helps


text:
Q: Virtual environment vs separate interpretor I've read a few things that said you should set up separate virualenv for each project - I mean it makes sense for compartmentalization and all that.
I also recently came across a solution that said to use separate interpreters for each project.
My question is: which is better? And what are advantages/disadvantages for each solution?
I should also add that I'm using Eclipse for this rather than a command line.


text:
Q: Docker, Registrator and Consul by example I am new to both Docker and Consul, and am trying to get a feel for how containerized apps could use Consul for both service registry and KV pair config management ("configuration").
My understanding was that I could:

*

*Create an image that runs Consul server, so something like this; then

*Spin up three of these Docker-Consul containers (thus forming a cluster/quorum) on myvm01.example.com (an Ubuntu VM); then

*Refactor my app to use Consul and create a Docker image that runs my app and Consul agent, with the agent configured to join the 3-node quorum at startup. On startup, my app uses the local Consul agent to pull down all of its configurations, stored as KV pairs. It also pulls in registered/healthy services, and uses a local load balancing tool to balance the services it integrates with.

*Run my app's containers on, say, myvm02.example.com (another Ubuntu VM).

So to begin with, if any of this seems like I am misunderstanding the normal/proper uses of Docker and Consul (sans Registrator), please begin by correcting me!
Assuming I'm more or less correct, I recently stumbled across Registrator and am now even more confused. Registrator seems to be some middleman between your app containers and your Consul (or whatever registry you use) servers.
After reading their Quickstart tutorial, it sounds like what you're supposed to do is:

*

*Deploy my Consul cluster/quorum containers to myvm01.example.com like before

*Instead of "Dockerizing" my app to use Consul directly, I simply integrate it with Registrator

*Then I deploy a Registrator container somewhere, and configure it to integrate with Consul

*Then I deploy my app containers. They integrate with Registrator, and Registrator in turn integrates with Consul.

My concerns:

*

*Is my understanding here correct or way off base? If so, how?

*What is actually gained by the addition of Registrator. It doesn't seem (to the untrained eye at least) like anything more than a layer of indirection between the app and the service registry.

*Will I still be able to leverage Consul's KV config service through Registrator?

A:
Is my understanding here correct or way off base? If so, how?

It seems to me, that it's not a good solution, to have all cluster/quorum members running inside the same VM. It's not so bad if you use it for development or tetsing or something, where you don't care much about reliability, but not for production.
Once your VM dies, you'll loose all the advantages you have by creating a cluster. And even more, you can loose all the data you have in K/V store, because you are running Consul servers inside a docker containers, which should be additionaly configured to share the configuration between runs.
As for the rest, I see it the same as you.

What is actually gained by the addition of Registrator.

From my point of view, the main thing is, that you don't have to provide an instance of Consul Agent in every container you run. And the container with the image you run is responsible only for their main functions, not for registering itself somewhere. You may simply pull an image and just run a container with it, to make it's service available, without making additional work.

Will I still be able to leverage Consul's KV config service through Registrator?

Unfortunately, no. At least, we didn't find a solution to use it this way, when we were looking for something to make service discovering and configuration management. We came to conclusion, that Registrator is not a proxy for K/V store and is used only to automate service discovery. So you have to use some other logic to access consul's K/V store.
Update: furthermore, here is 2 articles: "Automatic Docker Service Announcement with Registrator" and "Automatic container registration with Consul and Registrator", I found usefull to understand Registrator role in service discovery process.


text:
Q: Make document getElementById as Int I have this code that add numbers and prints it in input text for readonly
document.getElementById('total') += parseInt(tot);

but it JUST adds numbers as sting , for example when add 8 and 10 that would be 18 but it prints them as 810 , why ?

A: Use the parseInt() function to both of them:
document.getElementById('total').value = parseInt(tot)+parteInt(document.getElementById('total').value);

A: Just parse the value from string to integer like this
var x = document.getElementById('total');
x.value = parseInt(x.value) + parseInt(tot);

Or use parseFloat() if you have decimal numbers.

A: You can try this:
var elem = document.getElementById('total');
elem.value = +elem.value + parseInt(tot);

The + sign force the type to number.


text:
Q: How can to test in Espresso without R.id.edit_text? I create dynamic fields in my class. And I cannot to write EditTexts in layout (.xml), so I have not R.id.edit_text, How Can to test edit text without R.id.edit_text in Espresso 2? If I have R.id.edit_text - I can write onView(withId(R.id.edit_text)).perform(typeText("123")); But I have not the R.id.edit_text.

A: withId is only one of view matchers. You could you use others that are suitable for you case. You could check under ViewMatchers of com.google.android.apps.common.testing.ui.espresso.matcher.
Google code could be found here.
Also hamcrest matchers could help to have more complex conditions.
One of samples could be this:
onView(allOf(
    isAssignableFrom("class name"),
    withText("Text to match")))
    .perform(...);

You could also write your own matcher if you need more complex one.
I am recommending also to read the Espresso documentation.


text:
Q: Deriving iterative applications of an operator using recursion In this answer by Angina Seng, they start with the proposition that:
$$ P^n = \sum_{k=1}^n a_{n,k} x^k D^k$$
Why were they able to do this? Is there any easy justification to give for it?

A: It's a general fact about the Weyl algebra $k[x, D]$ (where $D = \partial_x$) that every element can be written this way. The proof is just by induction; you apply the canonical commutation relation $D x - x D = 1$ a lot to move $x$'s past $D$'s. As a simple example,
$$(xD)^2 = x(Dx)D = x(xD + 1)D = x^2 D^2 + xD.$$
In general, it suffices to show that $D^i x^j$ can be written as a sum of terms of the form $x^k D^{\ell}$, which you do by commuting the $k$ copies of $x$ past the $j$ copies of $D$ using the canonical commutation relation. It will be convenient to adopt the notation $[X, Y] = XY - YX$ and to prove lemmas about it, e.g. that it's a derivation in each variable, and a lemma about what $[X, Y^n]$ looks like.
Abstractly you can get this out of the Poincare-Birkhoff-Witt theorem, applied to the universal enveloping algebra of the Heisenberg algebra $\text{span}(x, D, 1)$. (You then need to take a quotient of the universal enveloping algebra given by setting $1$ to the identity to get the Weyl algebra.)


text:
Q: Google sheets function that outputs URL of spreadsheets in a specific folder? Google sheets function that outputs URL of spreadsheets in a specific folder? I would like to use "importrange" for a dynamic set of files, where a new file is created every month and added to the importrange.

A: Answer:
You can do this with a custom formula and a Web App.
More Information:
There is no Sheets formula which allows you to obtain file IDs simply by giving a folder. You can however use a custom function to extend the function of formulae and get the data this way.
As per the documentation on custom functions:

Unlike most other types of Apps Scripts, custom functions never ask users to authorize access to personal data.

Which means it is not possible to directly call DriveApp as this requires authentication. The list of supported services can be found on the custom function page, but for this, we can use UrlFetchApp.
Code:
First you will need to write a doGet() function, and publish your script as a web app:
function doGet(e) {
  var files = DriveApp.getFolderById(e.parameter.folderId).getFilesByType("application/vnd.google-apps.spreadsheet");
  var IDs = [];
  while (files.hasNext()) {
    IDs.push(files.next().getId())
  }
  return ContentService.createTextOutput().setContent(IDs.join()).setMimeType(ContentService.MimeType.TEXT);
}

Follow the Publish > Deploy as Web App menu item, and set the settings to Execute the app as: me and Who has access to the App: anyone, even anonymous, and press save. Make sure to copy the script URL that appears in the following modal.
With this Script URL, you can then create your custom function:
function getSheetIds(folderId) {
  var url = "script-url"
  var resp = UrlFetchApp.fetch(url + "?folderId=" + folderId).getContentText();
  var vals = [];
  return resp.split(",")
}

Making sure to paste the web app URL as the value of the url variable. Save the script, and return back to your Sheet.
You can then call the function from Sheet using the following formula:
=GETSHEETIDS(folderId)

Where folderID is the ID of the folder from which you want to get the list of Sheet IDs.
Example:

References:

*

*Custom Functions in Google Sheets | Apps Script | Google Developers


text:
Q: How do I install delayedresult module in wxPython I have installed and used wxPython on my work pc (using threading in many apps). However, I attempted to set-up the same environment on my personal computer, and I cannot get the module lib.delayed result to run for anything. I can use wxPython with my applications that don't use threading, but when I attempt to run any app that uses threading, I get the following traceback:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import lib.delayedresult
ImportError: No module named lib.delayedresult

I've exhausted what I know to do, at this point .... I appreciate any help/direction in advance.

A: I am using it by importing like:
import wx.lib.delayedresult as delayedresult


text:
Q: neo4j / cypher : delete double linked list in one request Using Neo4j, i have done an implementation of a newsfeeds for each users.
I am using a double linked list with two kind of relation "next_activity" / "prev_activity".
On each activity node i can have others relations as "LIKE".
When a delete an user in my system i would like to delete all the news feeds.
So i have to iterate each activity, delete it (and all relations as LIKE) and be able to go to the next using the relation "next_activity".
Does it possible using Cypher in one request (i mean using the *..100 option).
Thank you!

I have tried (version 1.8.2) :
    start user=node:id(id="...") match  path=user-[r:NEXT|PREV|LIKES*]->activity
    with relationships(path) as act_r, nodes(path) as act_n
    foreach(r in act_r : delete r)
    with act_n
    foreach(n in act_n : delete n);

But i have 'TransactionFailureException"
I am going to test on 1.9.2 RC2

A: I think something like this should work:
start user=node... // lookup user in index
match p=user-[:NEXT*]-activity // find all activities nodes in the linked list
with nodes(p) as activities // this also includes the user
foreach activity in activities:
  match activity-[r?]-() // get all relationships coming off of each activity
  delete activities, r; // delete all for each activity

Update: New idea. I'll leave the other idea there for posterity. This should work because it should match each path until the end, and we'll just use the endpoint to delete the :LIKE relationships (or any relationship) going off of those.
start user=node... // lookup user in index
match p=user-[:NEXT*]-activity, activity-[r?]-()
delete user, activity, r;

I built a graph and tested it, so I think it should be a general solution.
http://console.neo4j.org/?id=nnj5h8


text:
Q: Flutter google map web marker on click I am using this library in my app to load the Google map on the web using this answer as a reference, I am able to add the marker on it but wondering how I can do the marker on tap action
Adding marker:
final _icon = jsMap.Icon()
      ..scaledSize = jsMap.Size(60, 60)
      ..url = 'https://www.freeiconspng.com/thumbs/pin-png/pin-png-9.png';

final marker = jsMap.Marker(
      jsMap.MarkerOptions()
          ..position = latLng1
          ..map = map
          ..title = 'Test Title1'
          ..icon = _icon
        );

A: I am able to do the on click action using the below code:
final infoWindow =
        jsMap.InfoWindow(jsMap.InfoWindowOptions()..content = 'This is the content inside the Info window');
    marker.onClick.listen((event) => infoWindow.open(map, marker));

It may help someone!


text:
Q: Trouble Shooting Cannot Read Property 'length' of Undefined My d3 US map was working fine for a while, I was plotting circles from my csv data with no problem. It looked like this:
var url = "my_data.csv";

      d3.csv(url, function(error, rawData) {
                var data = rawData.map(function(d)
          {
            return {
                        File: d.File,
                Latitude: +d.Latitude,
                Longitude: +d.Longitude,
                Place: d.Location,
            };
          }).filter(d => projection([d.Longitude,d.Latitude]));

However, I noticed when I tried to parse the time dimension of the data, things got a little complicated. My parse of data containing dates failed citing the error: "Cannot read property 'length' of undefined". My dates are have the 1/22/2015 format, so I used the following (I also tried %x):
var parseTime = d3.time.format("%m/%d/%Y").parse;
var formatDate = d3.time.format("%m/%d/%Y");
var url = "my_data.csv";

      d3.csv(url, function(error, rawData) {
                var data = rawData.map(function(d)
          {
            return {
                        File: d.File,
                Latitude: +d.Latitude,
                Longitude: +d.Longitude,
                Place: d.Location,
                        Due: parseTime(d.Due),
                        //Notif: parseTime(d.Notification)
            };
          }).filter(d => projection([d.Longitude,d.Latitude]));

I check the existing literature relating to this error in D3 and it seems to have two main causes (that I'm aware of at least):

*

*the data callback had an issue, as was the case
here

*or the data itself suffered a delimiter issue, as was the case
here
I have parsed dated data before without (too many) issues, so at first I thought it could be the 2nd of the above causes -- the data has a delimiter issue. Perhaps a comma has been omitted or there were two commas, or instead of a comma there is a period or semi-colon.
My first step to troubleshoot was to take my data set (which was in the thousands) and delete everything except for about 80 observations, which is more manageable. After looking through the scaled-down data, everything seemed to be in order. And just to be safe I deleted everything except for 2 observations, and yet the error persisted. So, it looks like it was not a delimiter issue after all.
Question: This whole process created more questions than answers, I'm not sure how to proceed. Perhaps there is another cause of the error that I'm not aware of?
For reference, I have uploaded a minimalist block of my particular undefined 'length' issue.

A: The error message is self-explanatory: you have undefined values. To be more precise, 71 objects out of 141 in the rawData array have Due: undefined.
Just filter them out:
rawData = rawData.filter(function(d){
    return d.Due != undefined;
});

Here is your updated bl.ocks: https://bl.ocks.org/anonymous/b576bf06ab86cd0d27735b18da66c2ad/a2f363be3875574ba89f0015be1ac0853095d7ab


text:
Q: Two dimensions data, display no results I'm a beginner with angularJs
I have json data on two dimensions :
[
    {
        "nom": "Name 1",
        "subventions": [
            {
                "beneficiaire": "ben\u00e9f Phipippe C mars 2015",
                "montant": "7<\/span>898,99",
                "annee": 1,
                "trimestre": 4,
                "infoAdditionnelle": "
info mars - 2015<\/p>\r\n
\u00a0<\/div>"
            },
            {
                "beneficiaire": "cvbcvbn",
                "projet": "
cvnnncbcnbcbn<\/p>",
                "circonscription": "456sdxfvxc",
                "montant": "131,00",
                "annee": 3,
                "trimestre": 2,
                "infoAdditionnelle": "
test<\/p>"
            }
        ]
    },
    {
        "nom": "Name 2",
        "subventions": [
            {
                "beneficiaire": "pierre m",
                "montant": "1<\/span>000,00",
                "annee": 3,
                "trimestre": 1,
                "infoAdditionnelle": "
avtil 2015-16<\/p>"}
        ]
    },
    {
        "nom": "Name 3",
        "subventions": [
            {
                "beneficiaire": "bene pierre p avril 2015-16",
                "montant": "1<\/span>222,00",
                "annee": 3,
                "trimestre": 1,
                "infoAdditionnelle": "
p avril 2015-16<\/p>"
            }
        ]
    }
]

As you can see, there is an array of persons containing the field "nom" and "subventions", "subventions is also an array
I have filters by the fields "annee" and "trimestre", and what i want to do is when there's not result to display, to display a "no results" message
To calculate the number of results, i use this function
$scope.filterArray = function(resultsPersonnes) {
    var data = resultsPersonnes.filter(function(prop) {
        return prop.subventions[0].annee == $scope.annee.id;
    });
    if ($scope.myFilter.trimestre > 0) {
        return data.filter(function(prop) {
            return prop.subventions[0].trimestre == $scope.myFilter.trimestre;
        });
    } else {
        return data
    }

}

It's doesn't work for all the cases, you can see an example here http://plnkr.co/edit/9TbO0Hl9LziUS2B6AsAr?p=preview
If you click on "Juillet - septembre" in "Trimestre, i got one result, but the "no results" message is displayed!!!
do you see the error ? please help!
Thanks a lot

A: As you already guessed in your comment, you were checking only the first row. The fix is to check all rows, for example like this, using Array.some (which returns true if at least one item in array returns true for the function given as parameter)
Edit: the filtering needs to be updated into a single filter
$scope.filterArray = function(resultsPersonnes) {
    var data = resultsPersonnes.filter(function(prop) {
      return prop.subventions.some(function (subvention) {
        var anneeMatches = subvention.annee == $scope.annee.id;
        var trimestreMatches = true;
        if ($scope.myFilter.trimestre > 0) {
          trimestreMatches = subvention.trimestre == $scope.myFilter.trimestre;
        }
        return anneeMatches && trimestreMatches;
      });
    });
    return data;
};

See working plunker


text:
Q: Database table prefix in controller file of CAKEPHP Any short code to get the database table prefix in cakephp controller action ?
Please advise me .Thanks in advance

A: well:
$prefix = $this->ModelName->tablePrefix;


text:
Q: Freshman's Dream Quotient Rule I have been researching the Freshman's Dream Quotient Rule for awhile now and have been unable to find an example for which the rule works. I want to know if anyone knows of 2 function which it works for.
Rule is:
$$\left(\frac{f(x)}{g(x)}\right)'=\frac{f'(x)}{g'(x)}$$

A: Define the functions $f$ and $g$ on $[1,+\infty]$.
$f(x)=0$ and $g(x)=x$, so $f'(x)=0$ and $g'(x)=1$.
$$\left(\frac{f(x)}{g(x)}\right)'=\left(\frac{0}{x}\right)'=0'=0$$
$$\frac{f(x)'}{g(x)'}=\frac{0}{1}=0$$


text:
Q: How can I validate an array of enum values with Nestjs I feel like a combination of this thread and this thread is what I need to implement, I'm having trouble drawing them together.
I have a DTO that contains an enum.
Using Postman, I am sending a PurchasableType of FOO and expecting to get an error of some sort. Reading through the above links, it seems like the process is quite involved; which makes me thing I'm completely missing the point.
How can I use the validation pipe(s) to make sure only the values in the purchasable-type.enum.ts are allowed?
Thank you for any suggestions!
// create-order.dto.ts

import { IsEmail, IsNotEmpty, IsEnum } from 'class-validator';
import { PurchasableType } from '../enum/purchaseable-type.enum';

export class CreateOrderDto {
  @IsNotEmpty()
  readonly userId: string;

  @IsNotEmpty()
  readonly locationId: string;

  @IsNotEmpty()
  @IsEnum(PurchasableType)
  readonly purchasableType: PurchasableType;

  @IsNotEmpty()
  @IsEmail()
  readonly email: string;
}

// purchasable-type.enum.ts

export enum PurchasableType {
  CLINIC = 'CLINIC',
  EVENT = 'EVENT',
  LESSON = 'LESSON',
  RESERVATION = 'RESERVATION',
  TEAM = 'TEAM',
}

EDIT
It seems I was also not defining the entity correctly, and that may have been the main issue. I am still curious if my implementation good/bad.
// order.entity.ts

...
import { PurchasableType } from '../enum/purchaseable-type.enum';

@Entity()
export class Order extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

@Column({
    type: 'enum',
    enum: PurchasableType,
  })

Now when I send a purchasableType of foo I am getting a 500 error. If I send any valid value that is within the enum I am getting a 200/201.
EDIT 2
Sure - here is a bit wider view of what I've got. Everything seems to be working properly, I'd just like to have a better grasp of what was really happening.
// event.controller.ts

@Post('/:id/orders')
  async purchaseEventTickets(@Body() createOrderDto: CreateOrderDto):
    Promise<Order> {
    return await this.eventService.purchaseEventTickets(createOrderDto);
  }

// create-order.dto.ts

export class CreateOrderDto {
    @IsNotEmpty()
    @IsEnum(PurchasableType)
    readonly purchasableType: PurchasableType;
}

// event.service.ts

async purchaseEventTickets(createOrderDto: CreateOrderDto): Promise<Order> {
    ...
    return await this.orderRepository.createOrder(createOrderDto);
}

// order.repository.ts

async createOrder(createOrderDto: CreateOrderDto): Promise<Order> {
    const { purchasableType } = createOrderDto;

    const order = this.create();

    order.purchasableType = purchasableType;

    try {
        await order.save();
    } catch (error) {
        this.logger.error(`Failed to create the order: ${error.stack}`);

        throw new InternalServerErrorException();
    }

    return order;
}

Using Postman, if I send an invalid value of "Foo" as a PurchasableType I get the expected error.

A: Here is what your create-dto looks like that contains an enum.
// create-order.dto.ts

import { IsEmail, IsNotEmpty, IsEnum } from 'class-validator';
import { PurchasableType } from '../enum/purchaseable-type.enum';

export class CreateOrderDto {

    ...

    @IsNotEmpty()
    @IsEnum(PurchasableType)
    readonly purchasableType: PurchasableType;
}

Here is what that enum file looks like:
// purchasable-type.enum.ts

export enum PurchasableType {
  CLINIC = 'CLINIC',
  EVENT = 'EVENT',
  LESSON = 'LESSON',
  RESERVATION = 'RESERVATION',
  TEAM = 'TEAM',
}

From there I can confidently expect the value of the enum to be one of the above values. If some other value comes through, nest will throw a validation error.
Additionally, If you are attempting to use a nested object (or something with multiple attributes or an array) you can do something like this in your DTO:
import { PurchasableType } from '../interface/purchasable-type.interface';
...

@ApiProperty()
@IsArray()
@ArrayMinSize(7)
@ArrayMaxSize(7)
@ValidateNested({ each: true })
@Type(() => PurchasableType)
@IsNotEmpty()
readonly PurchasableType: PurchasableType[];

...

A:   @IsArray()
  @IsEnum(enum, { each: true })
  prop: enum[]

A: It took me a while to find a good solution.
@ApiProperty({
  description: 'List of enums',
  isArray: true,
  enum: MyEnum
})
@IsEnum(MyEnum, { each: true })
prop: MyEnum[];

A:   @IsEnum(myEnum, { each: true })
  @Transform((value) => myEnum[value])
  tags: myEnum[];

A: None of the above worked for me, I did it this way:
@Column({ type: 'enum', enum: MyEnum, array: true })
myProperty: MyEnum[];


text:
Q: Mobile browsers not working with Jquery mousedown/touchstart/HTML5 Canvas UI element So I've been trying to spend hours on getting this UI toggle switch to work on mobile and I sort of have it, but not ideally.
If you use it on a desktop browser you will find that you are able to both click on the "on" or "off" side of the toggle switch and it will switch to that side and it is also "draggable".
In the Android mobile browser and Chrome for Android you still can click and release the toggle switch and get it on the side you want, however you lose the "dragging" function. I think it may be an issue with how the animation is rendering or something. Here is the code the event handler of my script:
$("#"+togID).on('mousedown touchstart', function() {
    mouseIsDown=true;
    animate();
});
$(document).on('mouseup', function() {
  if(mouseIsDown){
    animate();
    if(on===true){
    primXX=cw-cx;
    draw();
    } else {
    primXX=cx;
    }
  mouseIsDown=false;
}
});
}

Other info: Here is a link to the FIDDLE and it should be noted that I'm using the jquery 1.11.X library and Paul Irish's rAF polyfill
Any help is greatly appreciated!


text:
Q: question on IoC I've been relying on IoC pattern for 1 year now using structuremap & asp.net mvc. IoC is really neat especially if you have a lot of dependencies in your class, just inject dependency in your constructor and your done, the IoC will auto-inject it for you.
My question is that im using asp.net mvc with a controller class which have IServices dependencies.
I need the dependency services only for a certain controller action let say "/customer/add"
but i don't need those dependency on other action let say "/Customer/Index". However, since i'm using a DI (Dependency injection) in constructor, the dependency are always instantiated even if i don't need them. Is that any good? object creation is expensive and consume memory footprint.
Of course, i can do container.GetInstance inside an action, but it is not a good practice since you will heavily be dependent on IoC in your code and unit testing.
Any suggestion? correct me if im wrong with something.

A: I always use constructors. imho properties should only be used to solve circular dependencies.
The reason is that the intent is not clear when using properties. Nothing in your code says that MyController.DoThat wont work if the property MyController.MyProperty is not set.
If a method needs a specific service, then the service is required for your whole class. Else you'll break the contract that your class exposes.

A: Updated in response to jgauffins comment
I see two straightforward ways to solve your issue:
Inject a service factory to your constructor and create the service on demand.
interface IFooService
{
    void Bar();
}

interface IFooServiceFactory
{
    IFooService CreateFooService();
}

class YourController
{
    public YourController(IFooServiceFactory fooServiceFactory)
    {
        this.fooServiceFactory = fooServiceFactory;
    }

    public void YourAction()
    {
        IFooService fooService = this.fooServiceFactory.CreateFooService();
        fooService.Bar();
    }
}

Inject a service proxy to your constructor and let the proxy create the real service on demand.
interface IFooService
{
    void Bar();
}

class FooServiceProxy : IFooService
{
    private IFooService realFooService;

    void IFooService.Bar()
    {
         IFooService realFooService = GetRealFooService();
         realFooService.Bar();
    }

    private IFooService GetRealFooService()
    {
        if(this.realFooService == null)
        {
            this.realFooService = CreateRealFooService();
        }
        return this.realFooService;
    }

    private IFooService CreateRealFooService()
    {
        // You could inject the service factory in the constructor of the proxy and use it here to create the real service.
    }
}

class YourController
{

                          Inject FooServiceProxy here
                          v
                          v
    public YourController(IFooService fooService)
    {
         this.fooService = fooService;
    }

    public void YourAction()
    {
         this.fooService.Bar();
    }
}

A:

the dependency are always instantiated even if i don't need them. Is that any good?

Although not every part of the class requires the dependency, the class itself needs that dependency and it is therefore not an optional dependency. Typically when you see that some dependencies are used in one part of the class and other dependency in another part, your class might be violating the SRP; it might be doing more than one thing. Splitting them up however, would probably not help you since MVC Controller classes are more focused around interfaces, so I would just leave it as it is.

object creation is expensive and consume memory footprint.

Reference types always have a 8 bytes overhead (on the 32 bits platform), so that's not much. The service object you would normally inject do contain very little state, often just some configuration values and references to their dependencies. From a memory perspective, it is nothing compared to the data that flows through you application (such as data from the database or the strings that get generated by MVC to build the HTML). It does depend on the DI framework you use, but typically even a relatively big dependency graph will get generated in a split second. And even when graph construction takes too much time, there are other ways to optimize performance. Consider defining some services with a singleton lifestyle for instance. When this is not enough, you might want to consider switching to a faster DI framework. StructureMap however, is one of the faster DI containers in the field (of the more commonly known ones), so for normal application development, this shouldn't be a problem.

A: The way I've always done it was that for injected dependencies that are optional (such as in the scenario you just described where only certain methods requires the dependency), set them up as properties. For required dependencies, use constructor injection.

A: StructureMap supports delayed instantiation - no need to craft your own service factory/proxy solution. If you only want IService instantiated when in the actions it is used, inject a Func<IService> into your constructor instead. Then, in your action that needs it, invoke the Func to return the instance.
class CustomerController {
  Func<IService> _service;

  public CustomerController(Func<IService> service){
    _service = service;
  }

  public ActionResult Index(){
    _service().CallMethodOnService();
  }
}

However, I would first make sure that instantiating the service really is a performance problem before going to this extra effort.


text:
Q: VPS disk size is much larger than expected (830GB instead of 80GB) We have rent a server and created a few VPS on it.  I have an VPS that I deployed some services on it, The amount of storage has been defined to 80GB and  10GB of the space is used.
Problem is that the size of VPS on the host is 830GB that it very strange. do you have any suggestion that help me find out why the size is this much different and how to solve it?

Thanks.


text:
Q: jsp?Action=someaction not working but jsp?action=someaction works In my web application, I use jsp and servlets. To redirect to a page, I use the following URL Pattern with some action.
This does not work.
1.http://100.320.22.1423:1023/hello/SomePage.jsp?Action=Det&FunctionId=ID123
These work. As you can see, the only difference between 1 and 2 are 'Action' starts with capital and simple letters. I encountered these problems afrer updating my browers ( both Chrome and firefox )
2.http://100.320.22.1423:1023/hello/SomePage.jsp?action=Det&FunctionId=ID123
3.http://100.320.22.1423:10023/hello/SomePage.jsp?FunctionId=ID123&Action=Det
Any suggestion or reasons why this happens?
Thanks in advance.

A: Firstly, I think it's really important that you consider how you can help other people help you when writing your question. You have not included any details about the error, nor your code, which is why you've been down-voted so many times.
I suggest you read this article so that you can craft better questions in the future that may lead you to quicker, better answers.
Without the code or the error message it's really difficult to help you out. However, I suspect you're probably not considering the case-sensitivity of action (or Action).
A and a are not the same, so Action and action need to be accessed differently.
If you want to read Action in PHP for example, you would need to access the $_GET array with the index Action.
$action = $_GET["Action"];

Using action with a lower-case "a" will result in an error saying that the index is undefined.


text:
Q: How to make grid scrollable on Windows Phone? I need to make my grid scrollable. I have a grid control that will eventually hold 30-40 rows of data. I populate/create these rows dynamically with code. Every time these rows render on the screen, they try to fit in the height I have set for the grid.  I tried wrapping my grid in scrollviewer but that didn't work. I want to stay away from the listbox because text will get misaligned.  Here is my XAML code for constructing the Grid:
            <ScrollViewer Canvas.Left="56" Canvas.Top="354">
        <Grid x:Name="grdWeather"  Canvas.Left="56" Canvas.Top="354" Width="371" ShowGridLines="True" Background="#FFDCB3B3" ScrollViewer.VerticalScrollBarVisibility="Visible" MaxHeight="196">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition Width="100"/>
                <ColumnDefinition Width="100"/>
            </Grid.ColumnDefinitions>
            </Grid>
        </ScrollViewer>

And here is my code for creating the rows:
                for (int t = 0; t <= 30; t++)
            {
                RowDefinition row1 = new RowDefinition();
                grdWeather.RowDefinitions.Add(row1);

                TextBlock txtTime = new TextBlock();
                txtTime.Text = time;
                txtTime.SetValue(Grid.RowProperty, t);
                txtTime.SetValue(Grid.ColumnProperty, 0);
                txtTime.Width = 100;
                grdWeather.Children.Add(txtTime);

                TextBlock txtTemp = new TextBlock();
                txtTemp.Text = time;
                txtTemp.Width = 100;
                txtTemp.SetValue(Grid.RowProperty, t);
                txtTemp.SetValue(Grid.ColumnProperty, 1);
                grdWeather.Children.Add(txtTemp);
            }

Any suggestions/feedback are appreciated. Thanks!

A: Using a ListBox is definitely a better idea. The problem with your code is the MaxHeight=196 on your Grid. Delete it on it will work


text:
Q: Why the input field is starting from center of the field? The intitial position of cursor is at center of the field. How to make it to top left?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>
<body style="background-color: cadetblue; height:1000px">
<form>
   <input type="text" class="notes-input" name="note">
</form>
</body>
</html>

.notes-input {
    width: 50%;
    line-height: 8em;
    margin:50px 0px 0px 150px ;
}

A: use textarea instead of input.

<textarea name="textarea" style="width:250px;height:150px;"></textarea>

A: You can use textarea instead of input
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>
<style>
.notes-input {
    width: 50%;
    margin:50px 0px 0px 150px ;
}
</style>
<body style="background-color: cadetblue; height:1000px">
<form>
   <textarea type="text" rows="5" class="notes-input" name="note"></textarea>
</form>
</body>
</html>

if we want only input and box size should be big means we can use the below code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
</head>
<style>
.notes-input {
    width: 50%;
    margin:50px 0px 0px 150px ;
    padding-bottom:150px;

}
</style>
<body style="background-color: cadetblue; height:1000px">
<form>
   <input type="text" class="notes-input" name="note">
</form>
</body>
</html>


text:
Q: How to detect the origin of a query execution in SQL Server? We have a SQL Server DB that is filled with records from two external applications that have the ability to execute queries against this DB. Both apps are black boxes for us, we don't have access to the code.
We would like to know each execution of these queries from which application it is called.
We have detected when and how often the queries are executed thanks to the Query Store, but we do not know the origin of each execution.
Is there any way to find out?


text:
Q: Xamarin.Forms (iOS Project): ListView Separator shows in all screen I have a ListView with the default SeparatorVisibility. My Android project shows the Separator if there are elements in the ItemsSource and stops showing it below the last element. It's the result I want for my iOS project.
However, in my iOS project the screen is full of Separators no matter how many elements I have, even if I have no elements or only one, the Separators still being there.
Could someone give me a reason and how to fix it please? Thanks.

A: I think you can take a look to this post
these are some tips
First disable the default separator, this is done by adding following property to the ListView XAML
SeparatorColor="Transparent"

After this, wrap the complete ViewCell content inside a double StackLayout! I know this sounds like overkill but this way you'll not run into any BoxView issues regarding margins inside the ViewCell… or other stuff.
The first StackLayout should have a BackgroundColor set to the colour you want your separator to be, the second StackLayout should have the same BackgroundColor as the rest of the container it is in… in our example the page and that is set to white. Be sure to also add a Margin to the bottom of this second StackLayout because that will represent the thickness of our separator!
I think you can play with this "Margin"... when your data is empty, remove the margin so you should not have the separator
<ListView x:Name="SeparatorListView"
    SeparatorColor="Transparent"
    ItemsSource="{Binding Persons}"
    Margin="0,20,0,0"
    RowHeight="60"
    HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
    BackgroundColor="White"
    Grid.Row="1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell IsEnabled="false">
                <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
                    BackgroundColor="Black">
                <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand"
                    BackgroundColor="White"
                    Margin="0,0,0,0.4">
                    <StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="FillAndExpand" Spacing="0">
                        <Label Text="{Binding FullName}" TextColor="Maroon" VerticalOptions="CenterAndExpand" Margin="20,0,20,0" />
                        <Label Text="{Binding Profession}" TextColor="Maroon" VerticalOptions="CenterAndExpand" Margin="20,0,20,0" />
                    </StackLayout>
                </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

With that in place, you'll get the same visual result as the preview image at the top right of this blog post.
As a bonus, you could omit one of the StackLayouts IF your page has a background color other than white. Because if this is the case, you can use that color as the separator color by playing with transparency inside the ListView.
Example of this, note will only work if the page itself also has a BackgroundColor set to Olive!
<ListView x:Name="SeparatorListView"
    SeparatorColor="Transparent"
    ItemsSource="{Binding Persons}"
    Margin="0,20,0,0"
    RowHeight="60"
    HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
    BackgroundColor="Olive"
    Grid.Row="1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell IsEnabled="false">
                    <StackLayout BackgroundColor="#f4eac3"
                                Padding="0,5,0,5"
                                 HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                        <StackLayout BackgroundColor="Transparent"
                                     HorizontalOptions="FillAndExpand" VerticalOptions="CenterAndExpand"
                                     Spacing="0"
                                     Margin="20,0,20,0">
                        <Label Text="{Binding FullName}" TextColor="Maroon" VerticalOptions="CenterAndExpand" />
                        <Label Text="{Binding Profession}" TextColor="Maroon" VerticalOptions="CenterAndExpand" />
                    </StackLayout>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

A: using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer (typeof(ListView), typeof(CustomListViewRenderer))]
namespace yourNamespace
{
    public class CustomListViewRenderer : ListViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.ListView> e)
        {
            base.OnElementChanged(e);
            if (e.NewElement != null)
            {
                var listView = Control as UITableView;
                listView.SeparatorInset = UIEdgeInsets.Zero;
            }
        }
    }
}

A: That is due to the implementation of the ListView on the iOS side. It renders as a UITableView which (in the case of the ListView) always takes the entire height and shows empty items. To change this type of behavior you could set the ListView height dynamically in the code-behind for your page. Another option is taking a look at Xamarin's Evolve sample app which has a few pages where it uses a CardView combined with a ListView to make it appear as it does on Android.


text:
Q: How to call a method as a response to another method call in Java? Suppose you have a Library L.jar which contains class C.class and a method m.
Now, you have a project which imports this library and uses the m method.
In the project there is class X with method mX.
What I want to do is to somehow monitor all invocations of the method m and invoke the method mX whenever method m gets invoked.
If I can somehow read the parameters which get passed to method m when invoking it, that would be awesome.
Is this possible in Java and if so, how to do it?

A: There are two approaches. You can either use AspectJ to intercept your program calls. OR You should be wrapping L.jar method m into a class of yours and expose that class to end user. end user should be using this class to invoke m. now you will have full control on who is calling m with which parameters. The downside is that user can always call m directly and bypass your code.


text:
Q: Yii How to add ajax-loading indicators clistview pagination links i want's to add ajax loader in my clistview pagination links.
how is it possible in yii pagination.
Thanks.

A: You have to create two js functions: first to show loader and second to hide it and pass them to CListView.
$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_post',   // refers to the partial view named '_post'
    'beforeAjaxUpdate' => 'function(id) { $(\'.loader\').show(); }'
    'afterAjaxUpdate' => 'function(id) { $(\'.loader\').hide(); }'
    'sortableAttributes'=>array(
        'title',
        'create_time'=>'Post Time',
    ),
));

Of course, you have to create div loader in html structure with image and position.
Here you have reference:
http://www.yiiframework.com/doc/api/1.1/CListView#beforeAjaxUpdate-detail
http://www.yiiframework.com/doc/api/1.1/CListView#afterAjaxUpdate-detail


text:
Q: browser back button vs refresh button Scenario 1: let say the previous page that i visited is example.com, so if i hit the back button, the browser will load example.com
Scenario 2: let say i am currently on example.com and hit the refresh/reload button, the browser will load example.com
My question: in the browser point of view, does it differentiate the two scenario and do anything differently? is there a spec for this?
My suspicion is that the browser does differentiate these 2 scenario. In my case, example.com is a static single page react app that do fetch request onComponentDidMount. I got a Status Code: 304 Not Modified when click refresh/reload button and Status Code: 200 OK (from disk cache) when click back button.

A: The difference between refresh and back is that the browser understands the back button as completely new access. Refresh is something little bit different. For example, in back button result, you won't get 304 status.


text:
Q: How to fix - 1084: Syntax error: expecting rightbrace before end of program So I'm copying this tutorial from a website - making a Space Shooter game.
I'm at the 1+: Interactive Animation (Afterburner) Part but I can't seem to figure out where to add the last code for the last given code:
Return now to your stage and enter your original ActionScript from the previous tutorial. You need to edit the code in 'function 'playerMovement' to reflect the snippet below:
enter image description here
Source From:
http://markbennison.com/actionscript/as3-space-shooter/1plus-interactive-animation-afterburner/
Whenever I try to insert this code anywhere, it always says
1084: Syntax error: expecting right-brace after end of program
I can't figure out where I need to put the 'right brace after end of program"
Is it a nesting symbol problem or a code problem?
The whole point of the tutorial on the website is to make an interactive animation of spaceships fire depending on what arrow key you press.
Pleaseee helpppp - tips?


text:
Q: Qual a melhor tag para criar uma barra de menu Boa noite pessoal, sou iniciante e tals, venho pedir ajuda para criar uma barra de menu
Estou montando um site e tenho 2 barras horizontais, a primeira eu quero colocar uma barra, com um botão de pesquisa e outro de login/cadastro
Já em baixo são os menus de navegação.
Geralmente crio uma tag e coloco um bg color nelas para fazer uma barra, e tenho extrema dificuldade para posicionar da forma que desejo
Alguém saberia me indicar o que fazer para posicionar perfeitamente está barra, além de uma tags adequada para cria-la?
Valeu pessoal!

A: você pode usar a tag nav ele representa uma seleção de links
ex:

test

não entendi muito bem sua pergunta, você quer uma tag pra posicionar melhor seu menu?

A: você pode fazer seu menu desta forma na horizontal

  *{margin: 0; padding: 0;}
  body{font-family: 'Roboto', sans-serif;}
  .menu{height: 60px; width: 100%; background-color: #f74343; display: table;}
  .menu ul{list-style: none;}
  .menu ul li{float: left;}
  .menu ul li a{text-decoration: none; color: #fff; padding: 20.8px; float: left; font-weight: lighter;}
  .menu ul li a:hover{background-color: #f77d7d; transition: 0.5s;}
<!DOCTYPE html>

 <title></title>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

Página Inicial

Loja

Suporte


text:
Q: get Index from an Array using Express + GraphQL I am just getting my hands dirty with GraphQL using Express. I am following the Academind YouTube Series for GraphQL-Express-Node-React. I have just setup a basic GraphQL Schema where I have hardcoded Array of Strings which is returned. I want to create a Query which gives me the index of the element from this hardcoded array using GraphQL (graphiql)
Code
const express = require('express'); // Add Express Module
const bodyParser = require('body-parser'); // Add Body-Parser Middleware for JSON handling in Requests
const graphqlHttp = require('express-graphql'); // Add Middleware for GraphQL Resolvers over Express HTTP
const { buildSchema } = require('graphql'); // Javascript Object-Destructuring (pull objects from packages)

const app = express();

app.use(bodyParser.json()); // JSON parsing Middleware added

app.use('/graphql', graphqlHttp({
    schema: buildSchema(`
        type RootQuery {
            events: [String!]!
            getEventIndex(eventName: String): Int
        }

        type RootMutation {
            createEvent(name: String): String
        }

        schema {
            query: RootQuery
            mutation: RootMutation
        }
    `),
    rootValue: {
        events: () => {
            return ['Cooking', 'All-Night Coding', 'Romantic'];
        },
        getEventIndex: (args) => {
            const _arr = ['Cooking', 'All-Night Coding', 'Romantic'];
            const index = _arr.findIndex(args.eventName);
            return index;
        },
        createEvent: (args) => {
            const eventName = args.name; // same as that of the parameter for `createEvent`
            return eventName;

        }
    },
    graphiql: true
}));

app.listen(3000);

I created a query  getEventIndex(eventName: String): Int which takes in the event name and provides me the index (which is integer)
Result in graphiql
query
query {
  getEventIndex(eventName: "Cooking")
}

result
{
  "errors": [
    {
      "message": "Cooking is not a function",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "getEventIndex"
      ]
    }
  ],
  "data": {
    "getEventIndex": null
  }
}

Why would Cooking here be considered as a function and not as an argument in createEvent mutation?
Of course I am jumping into GraphQL without much deep diving into its Specifications but I guess it might be capable of handling parameter based querying too.

A: This error is not specific to GraphQL.
Array.findIndex expects a function to be passed in as its first parameter. The function is called for each element in the array until the function returns a truthy value, at which point it returns the index of that element. The value of args.eventName is not a function (it's a String) so you end up with that error.
Either pass it a function, like:
const index = _arr.findIndex(value => value === args.eventName)

or just use Array.indexOf instead, which is probably what you meant to do:
const index = _arr.indexOf(args.eventName)


text:
Q: Understanding the main purpose of creating Host in asp.net core In IIS we need ASP.NET Core Module that hosts the app inside w3wp worker process.
Thinking the same was required for Kestrel, and apart from configuring logging, DI, and Middleware pipeline, the root purpose of HostBuilder is exactly the same i.e. to host the app inside Kestrel as ASP.NET Core module do to host the app inside IIS.
Am I wrong?

A: You're kind of correct. You need to keep in mind that:

*

*You don't have to use IIS. You also need something to get the requests from IIS into your application, as the module inside IIS is only for making IIS aware of the ASP.NET Core pipeline, since IIS only works with ASP.NET (framework) natively. That extra setup, then, is needed both in IIS and ASP.NET Core (in the form of UseIISIntegration)

*ASP.NET Core needs to configure the middleware pipeline, services, etc etc.

*The idea behind modularizing like this is that you can easily remove .UseIISIntegration() and just host on Kestrel and even Kestrel behind other servers like nginx and httpd.

*The host doesn't know about Kestrel, only Host.UseDefaultBuilder (which calls UseKestrel() internally) inject Kestrel.

Basically, then, the Host is the central configuration of the app. Whether you use Kestrel, IIS, http.sys, or some other framework, is a decision of the particular app you might be working on.


text:
Q: vim syntax match is wrong ([A-Z] is matching all alphabetic characters) I have a .vimrc file that contains the following line:
syntax match proper /\s[A-Z][a-zA-Z]*/

In theory, it should match any set of alphabetic characters that is prefixed by a space and starts with a capital letter. This works as it should when I run it with vim 7.3 on Ubuntu 11.11. However, when I sent the .vimrc to a server running vim 7.0 on CentOS 5.6, it matches all words prefixed by a space, not just the words that start with a capital letter.
I've been searching for a few hours to figure this out, but I'm baffled. I tried [[:upper:]] instead of [A-Z] but it came up with the same results. Using /[A-Z] and /[[:upper:]] to search properly selects only uppercase characters. Running ls | grep "[A-Z]" in bash only highlights files with uppercase characters.

A: My next best guess (after ignorecase) would be an error in the configuration of the syntax highlighting script itself:
Some languages are not case sensitive, such as Pascal.  Others, such as C, are
case sensitive.  You need to tell which type you have with the following
commands:
:syntax case match
:syntax case ignore

Could you try what happens when you specifically add :syntax case match to the mix (or spot where a spurious ignore is coming from)?

A: Have you accidentally turned ignorecase on? What do you get with /\s\C[A-Z]\c[A-Z]*/?


text:
Q: Troubles with for loop and Range var colRange = getRange("Sheet1!G2:G200")

  logger.log(colRange)
  logger.log(colRange[0])

  for(var i = 0; i < colRange.length; i++) {
    if(activeCell.getColumn() == 7 && activeCell.getRow() == colRange[i] && ss.getActiveSheet().getName()=="Sheet1") {
      newValue=e.value;
      oldValue=e.oldValue;
      if(!e.value) {
        activeCell.setValue("");
      }
    else {
      if (!e.oldValue) {
        activeCell.setValue(newValue);
      }
    else {
      activeCell.setValue(oldValue+', '+newValue);
        }
      }
    }
  }

Could anybody help with the for loop. Need it to check every row of column G to allow multiple drop down selections. If I replace colRange[i] with the specific row it does work. I assume I need to loop through each range G2, G3, G4, etc

A: Please explain what you are trying to
It's hard to figure out what you are trying to accomplish with you code but this is my best guess
function onEdit(e) {
  const sh = e.range.getSheet();
  if (e.range.columnStart == 7 && e.range.rowStart > 1 && sh.getName() == "Sheet1") {
    if (!e.value) {
      e.range.setValue("");//doesn't make sense it's already null
    } else if (!e.oldValue) {
      e.range.setValue(e.value);
    } else {
      e.range.setValue(oldValue + ', ' + newValue);
    }
  }
}


text:
Q: autoincrementing primary key n entering data from frontend that is a web page I created a table and autoincremented the primary key column. I created a web form in C# in .NET platform which is locally hosted. I have a problem when i try to enter data from the web form, primary key column is not automatically filled when i fill other fields, it does not take any value i enter.

*

*when i enter a value by myself it says"Cannot insert explicit value for identity column in table 'Product' when IDENTITY_INSERT is set to OFF."

*When I don't enter a value it says;

Incorrect syntax near ','.
  Source Error:
Line 41:             objCommand.Connection=objConnection;
Line 42:             objCommand.CommandText = "Insert into
  Product(CustomerName,CustomerAddress,InvoiceNumber,InvoiceDate,ProductName,ProductDescription,UnitCost,Quantity,TotalAmountToBePaid) values ('" + tbcustomername.Text+ "','" + tbcustomeraddress.Text + "'," + tbinvoicenumber.Text + ",'"+tbinvoicedate.Text + "','" + tbproductname.Text + "','" + tbproductdescription.Text + "'," + tbunitcost.Text + "," + tbquantity.Text + "," + tbamounttobepaid.Text + ")";
Line 43:             objCommand.ExecuteNonQuery();
Line 44:
Line 45:

Because i have autoincremented it, i wish to obtain a value automatically while i m filling other columns but that does not happen. What do i do?

A: you can change your command.
objCommand.CommandText = "INSERT INTO Product " +
   "(CustomerName,CustomerAddress,InvoiceNumber,InvoiceDate,ProductName,"+
   "ProductDescription,UnitCost,Quantity,TotalAmountToBePaid) VALUES " +
   "(@cname, @caddress, @inumber, @idate, @pname, @pdesc, @unitcost, @qty, @total); " +
   "SELECT SCOPE_IDENITY();";

objCommand.Parameters.Add(new SqlParameter("@cname", tbcustomername.Text));
objCommand.Parameters.Add(new SqlParameter("@caddress", tbcustomeraddress.Text));
objCommand.Parameters.Add(new SqlParameter("@inumber", int.Parse(tbinvoicenumber.Text)));
objCommand.Parameters.Add(new SqlParameter("@idate", DateTime.Parse(tbinvoicedate.Text)));
objCommand.Parameters.Add(new SqlParameter("@pname", tbproductname.Text));
objCommand.Parameters.Add(new SqlParameter("@pdesc", tbproductdescription.Text));
objCommand.Parameters.Add(new SqlParameter("@unitcost", decimal.Parse(tbunitcost.Text)));
objCommand.Parameters.Add(new SqlParameter("@qty", int.Parse(tbquantity.Text)));
objCommand.Parameters.Add(new SqlParameter("@total", decimal.Parse(tbamounttobepaid.Text)));

int id = (int)objCommand.ExecuteScalar();

This will return the last identity inserted in this transaction wich is the one you want to access.
It is good to remember that you can send multiple statements in a single command.
And as @Wiktor_Zychla says in the comment below it is better coding practice to use parameters in your queries to escape from sql injection.


text:
Q: Cannot get any archetypes from Maven when using the remote catalog URL I'm trying to create a new Maven project but I can't. I tried the command line and also through Eclipse.
The error I get when trying to use the command line is along the lines of

[ERROR] No plugin found for prefix 'archetype' in the current project and in the
   plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the
  repositories [local (C:\Users\MY_NAME.m2\repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

After searching around for the solution to the error, the problem seems to occur because I'm behind a firewall/proxy here at work.
I was then advised to go into Eclipse and try adding the remote catalog URL to Eclipse. What I done was I went to Windows > Preferences > Maven > Archetypes > Add Remote Catalog. I then put it http://repo1.maven.org/maven2/archetype-catalog.xml for the "Catalog File" field and maven catalog for the "Description" field.
I then click Verify to see if it was working and I got a warning saying that the "Remote catalog is empty".
I went ahead and tried to create a new Maven project anyway. After filling out my groupId and all that, I click finish. Another error comes up saying

Could not resolve archetype
org.apache.maven.archetypes:maven-archetype-webapp:1.0 form any of the configured repositories.

How do I get around this?

A: I fixed it today by firstly downloading the file in the browser then adding it as local file

A: http://repo1.maven.org/maven2/archetype-catalog.xml  is the "given" link to get access the the remote archetype.
However it may be outdated.  You need to include http (s) therefore https://repo1.maven.org/maven2/archetype-catalog.xml
is what is required to get the remote archetypes to appear in eclipse or your favorite browser.

A: I fixed it today by firstly downloading the file in the browser then adding it as local file.
You need to include http (s)
Try the below link:-
https://repo1.maven.org/maven2/archetype-catalog.xml

A: Remote url should be
https://repo1.maven.org/maven2/archetype-catalog.xml
instead
http://repo1.maven.org/maven2/archetype-catalog.xml
it worked for me in 2021 Jan

A: You need to add archetype catalog, you can use the Remote archetype catalog.
Old links which are shared are not working
Use - https://repo.maven.apache.org/maven2/archetype-catalog.xml

A: This works for me.  I downloaded and saved the archtype-catalog xml file to local drive and then added using "Add Local Catalog".

A: just look at the address
you havnt put https
https://repo1.maven.apache.org/maven2
try this it will halpful to


text:
Q: colortbl row column color overwrite hline on screen I have the following code to generate table with color highlights on certain rows and columns, also vertical bars and hline are used to partition the table, the table prints ok on paper, however on screen the lines are overwritten by the colors, as seen in the picture below:

See also here: https://www.writelatex.com/1123639gvpdyx
The code used:
\documentclass{article}
\usepackage{colortbl}
\definecolor{Gray}{gray}{0.8}
\newcolumntype{g}{>{\columncolor{Gray}}c}
\begin{document}
\begin{table}[h]
  \centering
  % Table generated by Excel2LaTeX from sheet 'Sheet1'
  \begin{tabular}{cgc|c}
    128   & 64    & 32    & 16 \\ \rowcolor{Gray}
    64    & 32    & 16    & 8 \\
    32    & 16    & 8     & 4 \\ \hline
    16    & 8     & 4     & 2 \\
  \end{tabular}%
\end{table}
\end{document}

Is there a work around to show correctly on screen?


text:
Q: preserving and recreating state via the URL Imagine the following scenario:
The user goes to https://mywebsite.com, searches for something and hits [submit]. The results are displayed and the URL is now https://mywebsite.com/floobah?q=burp. The user clicks on an anchor which scrolls the page down to a div a choice of ways to visualize the result. The URL is now https://mywebsite.com/floobah?q=burp#viz. The user chooses the pie chart widget and displays the pie and associated data. The URL is now https://mywebsite.com/floobah?q=burp&chart=pie&sort=asc#viz.
Then the user sends the URL to a friend. When its recipient opens that URL, the state is restored exactly as what it was for the sender. In other words, the URL is parsed and the actions performed to restore the state… the query is performed, the page scrolls down to the viz section, the pie chart opens up and the associated data is shown sorted as requested.
I am doing this right now by parsing the URL and replaying all the steps. But surely there must be a library already for doing this, no? To sum, I want the state of a page encoded in the URL which can be shared and then recreated by the recipient of the URL bookmark.
Update 1: A problem with my URL as noted above https://mywebsite.com/floobah?q=burp&chart=pie&sort=asc#viz is that there is no way to differentiate between a true query param such as q=burb and something that was a result of clicking on an element with an event listener attached to let, for example, chart=pie&soft=asc. I need to be able to differentiate commands for handling events and the query string and hash (#viz)
Update 2: So, I have three sets of params: the queryString that is processed on the server, the events that are processed in the client, and the hash fragment which specifies an anchor on the page to which the browser scrolls. What if I mark the events with ! ? Imagine https://mywebsite.com/floobah?q=burp!makePieChart!sortAscending#viz. The queryString q=burp is processed by the server and returned to the client which scrolls down to #viz and fires events to makePieChart and sortAscending. Thoughts?


text:
Q: How to make module private method in Java modules I want to create a Java IPC server module (with Jigsaw) which has two packages:

*

*com.example.ipc.backend

*com.example.ipc.backend.api

in my module-info.java I have the following export:
module ipclib {
    exports com.example.ipc.backend.api;
}

I can import this module in my JavaFX GUI module without problems, but I'm having a problem creating a class inside the api module.
I have one interface in this class which some class in the GUI module should implement to register itself for changes in the IPC module (e.g. when a client connects to the IPC server):
public interface IpcCallback {
    void clientConnected(Client client);
}

The class which implements this interface should then receive a Client with the information about the connected client. This Client class also internally holds a reference to the thread which holds the socket to the client.
public class Client {
    private IpcConnection connection; //IpcConnection is from com.example.ipc.backend

    public Client(IpcConnection connection) {
        this.connection = connection;
    }
}

My problem is now that I want to create an instance of Client in the non-exported backend module, whenever a new connection is created. How can I make the constructor to be only accesible within the module, without making it public?
If I make the constructor public, IntelliJ offers to use the constructor to create a new Client object in the GUI module, but does not have access to the IpcConnection class. It offers a quick fix to export the backend module, but this is not what I want when exporting the api.
Therefore, I wonder if this is still "allowed", because the Java compiler compiles this without any warnings and problems, and it is just a problem of IntelliJ. Or shouldn't this be done like this?
But if this is not the allowed way to do so, I wonder why the module system actually allows exporting only some packages, as there will always be a boundary between exported packages and not-exported packages (only except if the not-exported classes are called from within the exported class, but not the other way round).
Minimal project
Module 'backend'
// backend/src/main/java/module-info.java
module ipclib {
    exports com.example.ipc.backend.api;
}

// backend/src/main/java/com/example/ipc/backend/IpcConnection.java
package com.example.ipc.backend;

public class IpcConnection {
}

// backend/src/main/java/com/example/ipc/backend/api/Client.java
package com.example.ipc.backend.api;

import com.example.ipc.backend.IpcConnection;

public class Client {
    private IpcConnection connection;
    public Client(IpcConnection connection) {
        this.connection = connection;
    }
    public String hello() {
        return "Hello";
    }
}

// backend/src/main/java/com/example/ipc/backend/api/IpcCallback.java
package com.example.ipc.backend.api;

public interface IpcCallback {
    void clientConnected(Client client);
}

Module 'gui'
// gui/src/main/java/module-info.java
module gui {
    requires ipclib;
}

// gui/src/main/java/com/example/ipc/gui/App.java
package com.example.ipc.gui;

import com.example.ipc.backend.api.Client;
import com.example.ipc.backend.api.IpcCallback;

public class App implements IpcCallback {
    public static void main(String[] args) {

    }
    @Override
    public void clientConnected(Client client) {
        System.out.println(client.hello());
    }
}

A: I think, this is not possible in java. You can not declare an interface that is "visible in namespace A and all its sub-namespaces").
In contrast to .net, Java does not really know about the "internal" principle.
If you just omit the word public on an interface or class definition, this element is only visible inside it's current package.
But this is not recursive, as it is in .net (where you create an internal object which is visible only inside the current project, no matter which subfolder or namespace).
In Java, the object is only visible inside its current package (i.e. the very same namespace). Sub-namespaces are not included. Neither are parent namespaces.

A: If I understood correctly you have subpackages A and B, and only A is made public. A has a class C that has a constructor that should be called from B but not be made public.
I think your best option is to make class C (Client) implement and interface that is public. So the interface class can be in the public package and the actual implementation can be in the non-public package.


text:
Q: Default folder icons missing after user account rename I started using a MacBook Air M1, macOS Big Sur 11.2. When I created the user account I selected a lowercase name for the home directory. Later, I wanted to change that to a first uppercase name. I found and used instructions for that (log in as a different user, rename directory, modify account info to point to the right directory). All of this worked fine; I can log in without problems, all files and foldes are there.
However - in Finder, all top level folders in my home directory now have the generic folder icon. No special icons for Documents, Music, Movies, Pictures, Downloads, Desktop, Public.
How do I restore those?
Any help appreciated - thanks.

A: I had never modified account info correctly. It still indicated the lower case directory as home dir - and that worked since the file system is not case sensitive. No more help needed.