text:
Q: Generalization of a cyclic inequality : $ \sum_{cyc}{\sqrt{\frac{x+1}{4x^2+10x+4}}}\leqslant 1$ Hi it's a follow up of Prove $\sum_{cyc}{\sqrt{\frac{x+1}{x^2+16x+1}}}\geqslant 1$ and $ \sum_{cyc}{\sqrt{\frac{x+1}{4x^2+10x+4}}}\leqslant 1$ for $x,y,z>0,xyz=1$ :
Problem :
Let $x_i>0$ such that $\prod_{i=1}^{n}x_i=1$ and $n\geq 3$
Then prove or disprove that :
$$\sum_{i=1}^{n}\sqrt{\frac{x_i+1}{4x_i^2+10x_i+4}}\leq \frac{n}{3}$$

My attempt :
In the giving link I give a skectch of proof for the case $n=3$ using the simple (I mean easy) bounds :
$x\in (0,1]$ we have :
$$r(x)=\frac{\frac{1}{2}x^{2}+\frac{7}{2}x+2}{4x^{2}+4+10x}\geq \sqrt{\frac{x+1}{4x^2+10x+4}}$$
And for $x\geq 1$ :
$$h(x)=\frac{2}{3}-\frac{1}{1.5x^{-0.5}+1.5}\geq\sqrt{\frac{x+1}{4x^2+10x+4}}$$
Other case :
For the general case and using the fact :
Let $x\in (-\infty,0]$ then  we have :
$$\frac{d}{dx}\left(\frac{d}{dx}r\left(e^{x}\right)\right)<0$$
So we can use Jensen's inequality for $0<x_k\leq 1$ so we need to show :
$$\sum_{i=1}^{n-k}h(x_i)+k r\left(\prod_{i=n-k+1}^{n}(x_i)^{\frac{1}{k}}\right)\leq \frac{n}{3}$$
If there is some mistake related to the index tell me .
For example in the case $n=4$ when two variables are superior to one and the two other less than one I use Buffalo's way see Wolfram alpha .
Edit  :
In fact in the WA link I show something stronger .

Questions :
1)How to (dis)prove it ?
2)How to use Buffalo's way in the general case (if true)?
Thanks in advance .

A: $x=0.1$ gives $$\sqrt\frac{1.1}{0.04+1+4} > 0.46$$
Therefore we can have $x_i = 0.1$ for  $i \in [1;n-1]$ and $$\sum_{i=1}^n\sqrt\frac{x_i+1}{4x_i^2+10x_i+4} > \sum_{i=1}^{n-1}\sqrt\frac{x_i+1}{4x_i^2+10x_i+4} > 0.46(n-1)$$ which disproves your conjecture.
For example, for $x_1=x_2=x_3=0.1$ and $x_4=1000$ we have $$\sum_{i=1}^4\sqrt\frac{x_i+1}{4x_i^2+10x_i+4}\approx1.417>\frac{4}{3}$$
The upper bound for $\sqrt\frac{x_i+1}{4x_i^2+10x_i+4}$ seems to approach 0.5, so we can probably say that for every $\epsilon>0$ there exists $(x_1,x_2,...,x_n)$ such that: $$\sum_{i=1}^n\sqrt\frac{x_i+1}{4x_i^2+10x_i+4} > \sum_{i=1}^{n-1}\sqrt\frac{x_i+1}{4x_i^2+10x_i+4} > (0.5-\epsilon)(n-1)$$ but I'm not qualified enough to go there.


text:
Q: Why migrations is not working neither it creates migrations directory in django app It was working fine I first installed the app. After that i deleted my db.sqlite migrations and pycache file. Then I tried to migrate again all the default migrations worked except for the Post model which is in the postapp. I tried several time to migrate, every time it says no change detected and doesn't create any migrations directory
after running python manage.py showmigrations I get something like this it does not mentions post app name or any migrations related to post app
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
 [X] 0003_logentry_add_action_flag_choices
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial

How can I solve this it happens to me in every Django project. it needs to  be fixed

A: You need to either run the migration commands mentioning the particular app, for example:
python manage.py makemigrations <app_name>
python manage.py migrate <app_name>

Then it will create the migrations file inside the app directory.
Or you need to create a migrations folder inside the app directory, and put a __init__.py file inside it. Then run python manage.py makemigrations and python manage.py migrate command.
BTW, why do you need to delete migration files? Its best to keep the migration files and commit them to your repository if needed.

A: Django keeps track of all migrations in django_migration table. you can reinitiate all migration of app by
python manage.py migrate <APP_NAME> zero

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deleting User data in firebase Database not working I have created a delete profile button but nothing wants to be deleted in the database!
here are the codes i used for it
    private void deleteRecord() {
    DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference("MyUsers").child("id");

    Task<Void> mTask = DbRef.getDatabase().getReference("MyUsers").child("id").removeValue();
    mTask.addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid) {
            showToastMyUsersDelete("Profile permanently deleted!!");

            Intent i = new Intent(EditProfileActivity.this, Login_Activity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
            finish();
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            showToastMyUsersDelete("Error Deleting Profile");
        }
    });
}

It does what I say but doesn't remove the value If I use this code for example
        Task<Void> mTask = DbRef.getDatabase().getReference().removeValue();

Then the entire database will be deleted, but really everything!
This is how my hashmap looks not the full one
enter image description here

A: That's because in the second code, you are actually storing the reference of the entire database, as you have not specified any particular path. So removeValue() will remove the entire database.

A: Assuming the id under MyUsers is the currently logged in user id, then do the following:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference DbRef = FirebaseDatabase.getInstance().getReference("MyUsers").child(user.getUid());
Task<Void> mTask = DbRef.removeValue();

If you don't know the id under MyUsers then do the following:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("MyUsers");
ref.orderByChild("email").equalTo("example@gmail.com").addValueEventListener(new ValueEventListener() {
         @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
      for(DataSnapshot data: dataSnapshot.getChildren()){
            data.getRef().removeValue();
                  }
            }
        @Override
       public void onCancelled(DatabaseError databaseError) {
         Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
               }
          });

Add a reference to child MyUsers then using the query orderByChild you can get the correct node and delete it


text:
Q: Concatenating lists in PySpark In my Spark Dataframe, one of the columns is of strings
Activities
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"
"1 1 1 1 0 0 0 0 0"
"0 0 0 1 1 1 0 0 0"

I wish to collect strings from each row of this column and make a single list by concatenation. Then, split this huge string to make a huge single integer array like
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0,...]

(Of course, one can split the strings first, into lists, then append all the lists to form a big list, but the issue of How to concatenation RDD based lists remains)
Using pythons local data structures I can do:
import pyspark.sql.functions as F

allActivities = []
activitiesListColumn = df.agg(F.collect_list("Activities").alias("Activities")).collect()[0]
for rowActivity in activitiesListColumn["Activities"]:
    activities = rowActivity.split()
    allActivities += activities
print(allActivities)

How to get this done with RDD based (ie parallel-ized) data structures?

A: This possible with GROUP_CONCAT method but spark-sql doesnt contains this method. We can identify an UDF that runs like GROUP_CONCAT. About detail this UDF you can see in this link: SPARK SQL replacement for mysql GROUP_CONCAT aggregate function.. But we must change the seperator character (',' to ' ').. And after that, you can try this line:
df.agg(GroupConcat(new ColumnName("your_string_array"))).show

The GroupConcat object is:
object GroupConcat extends UserDefinedAggregateFunction {
  def inputSchema = new StructType().add("x", StringType)
  def bufferSchema = new StructType().add("buff", ArrayType(StringType))
  def dataType = StringType
  def deterministic = true

  def initialize(buffer: MutableAggregationBuffer) = {
    buffer.update(0, ArrayBuffer.empty[String])
  }

  def update(buffer: MutableAggregationBuffer, input: Row) = {
    if (!input.isNullAt(0))
      buffer.update(0, buffer.getSeq[String](0) :+ input.getString(0))
  }

  def merge(buffer1: MutableAggregationBuffer, buffer2: Row) = {
    buffer1.update(0, buffer1.getSeq[String](0) ++ buffer2.getSeq[String](0))
  }

  def evaluate(buffer: Row) = UTF8String.fromString(
    buffer.getSeq[String](0).mkString(" "))
}


text:
Q: Create dictionary from list python I have many lists in this format:
['1', 'O1', '', '', '', '0.0000', '0.0000', '', '']
['2', 'AP', '', '', '', '35.0000', '105.0000', '', '']
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']

I need to create a dictionary with key as the first element in the list and value as the entire list. None of the keys are repeating.
What is the best way to do that?

A: >>> lists = [['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''],
['2', 'AP', '', '', '', '35.0000', '105.0000', '', ''],
['3', 'EU', '', '', '', '47.0000', '8.0000', '', '']]
>>> {x[0]: x for x in lists}
{'1': ['1', 'O1', '', '', '', '0.0000', '0.0000', '', ''], '3': ['3', 'EU', '', '', '', '47.0000', '8.0000', '', ''], '2': ['2', 'AP', '', '', '', '35.0000', '105.0000', '', '']}

A: put all your lists in another list and do this:
my_dict = {}
for list in lists:
  my_dict[list[0]] = list[:]

This basically gets the first element and puts it as a key in my_dict and put the list as the value.

A: If your indexes are sequential integers, you may use a list instead of a dict:
lst = [None]+[x[1:] for x in sorted(lists)]

use it only if it really fits your problem, though.


text:
Q: How can I add the dropdown selected values dynamically with Handlers? I don't know how to get values from multiple dropdowns created dynamically based on the fetched data [drugs].
I have 1 input and 2 dropdowns.
each one with its own handler:
- Amount   : handleChangeDoseAmount
- Unit     : handleTimeUnitClose
- Interval : handleToolClose

Can anyone suggest a solution or a proper example?
  handleChangeDoseAmount = (index) => {
    return (event) => {
      console.log(index)
      this.setState([ { unitCount: event.target.value } ])
      this.props.handleAddDoseAmount(0, [event.target.value])
    }
  }

  handleTimeUnitClose = (index, item) => { // changing here
    this.setState({ timeUnitEL: null, timeUnitName: item !== 'close' ? item : this.state.timeUnitName })
    this.props.handleAddDoseInterval(0, [item])
  }
  handleToolClose = (index, item) => {
    this.setState({ toolEL: null, toolName: item !== 'close' ? item : this.state.toolName })
    this.props.handleAddDoseUnit(0, [item])
  }
  handleTimeUnitOpen = event => { this.setState({ timeUnitEL: event.currentTarget }) }
  handleToolOpen = event => { this.setState({ toolEL: event.currentTarget }) }

And this is the rendered components:

{

      {drugs.map((drug, index) => {
        return [

How often do you take {drug.name}?
,
          <HowOften
                        key="second"
 onChangeUnitCount={this.handleChangeDoseAmount(index)}
 onTimeUnitClose={(i) => this.handleTimeUnitClose(index, i)} // change
                        onTimeUnitOpen={this.handleTimeUnitOpen}
 onToolClose={(ii) => this.handleToolClose(index, ii)} // change
                        onToolOpen={this.handleToolOpen}
                        timeUnitEL={timeUnitEL}
                        timeUnitList={timeUnitList}
                        timeUnitName={timeUnitName}
                        toolEL={toolEL}
                        unitCount={unitCount}
                        toolList={toolList}
                        toolName={toolName}
                        howOftenId={'how-often-id'}
                      />]
                  })}

              }

Thanks,


text:
Q: How to debug without formatting the code in Javascript (ECMAScript 6) When using arrow functions and short functions in javascript (ECMAScript 6) debugging becomes difficult.
Normally i add debuggerin my code or I add a breakpoint.
With the syntax above its not possible to debug without formatting the code.
export const submitDevice = passCode => dispatch => dispatch(addDevice(passCode)).then(dispatch(loadDevices());

Does anyone know a way to debug without formatting the code?


text:
Q: ¿Como puedo recorrer un DataGrid y obtener los valores de la ceda? c# WPF quiero recorrer cada fila del DataGrid y obtener los valores de cada celda.
mi DataGrid tiene por nombre: DGDLISTA
Al DataGrid lo cargo de la siguiente manera
 String CADENA = "select * from mitabla";
                OracleCommand command = new OracleCommand(CADENA, connection);
                OracleDataReader reader = command.ExecuteReader();
                reader.Read();
                if (reader.HasRows != false)
                {
                    DGDLISTA.ItemsSource = reader.Cast<Object>();
                    DGDLISTA.Items.Refresh();
                  //  reader.Close();
                }

A: Aunque me falta información, te paso un ejemplo funcional para ve si te sirve.
       dg_data.SelectAllCells();
        foreach( DataGridCellInfo d in dg_data.SelectedCells)
        {
            if (dg_data.Columns[0]==d.Column)//evita repetidos ya que devuelve la fila
              Console.WriteLine(d.Item.ToString());//d.Item usando binding
   devuelve el itemsource
          }


text:
Q: trouble setting javascript variable to output of php I'm trying to set a javascript variable to the output of a php script but the JS variable continues to evaluate to the literal output of the PHP snippet.
Even when I do something as simple as this in my .js file:
var list = "<?php echo 'foo'?>";

the JS variable comes out as:
"<?php echo 'foo'?>"

When I try removing the quotes, I get parsing errors.
I've seen several examples like the above on various sites, though, so it seems like this should work.

A: As the comments above pointed out, the solution was to run that snippet of Javascript in a .php file.
I just moved that line to the
<script>

section of my main .php file, and it works.

A: In order for those php tags to run, they need to be in a file that actually executes php (so a .php file). Putting that line in a script tag at the top of the head in a php file will solve your problem. (Side-note: If you prefer to use html files instead like I do, you can add AddType application/x-httpd-php .html to your .htaccess file in your root directory. This will make php execute html files as well.)

<html>
  <head>
    <script>
      var list = "<?php echo 'foo'?>";
    </script>
    ...
  </head>
  ...
</html>


text:
Q: Scale image with SRT to the smallest possible ratio with imagemagick This is a follow-up question to Crop and resize image around a custom focus point where I got helpful answers on what command parts to use for imagemagick in order to achieve what I want: Scale an image down, but instead of using a predefined gravitiy (like "Center" or "North"), I want to use a custom point of focus on the image that should be the new center of the scaled image to ensure the "important point" of the image is always visible when cropping/resizing it.
This works quite well, except for the actual size calculation. I guess something is wrong in my math, because the resulting output is missing some parts that could be visible if the image is being scaled down more than I calculate. I can't find the mistake I'm doing, maybe someone can give me a hint into the right direction.
What I am currently doing:
# Example image from https://unsplash.com/photos/p-I9wV811qk
source_image = 'input.jpg'

source_image_size = [3008, 2000]
target_image_size = [295, 195]

# Focus point position, in percentages.
focus_point = {
  x: 46.7087766,
  y: 24.2
}

# Calculate the focus point in px on the source image.
source_focus_point = [
  source_image_size[0] / 100.0 * focus_point[:x],
  source_image_size[1] / 100.0 * focus_point[:y]
]

# Calculate the distances to the focus point in percentage,
# from all four image sides, and use the smalles value.
smallest_percentage_distance = [
  focus_point[:x],
  (100.0 - focus_point[:x]),
  focus_point[:y],
  (100.0 - focus_point[:y])
].min

# Scale image to reach smallest percentage distance.
scale_factor = smallest_percentage_distance / 100.0

# Calculate the focus point on the target image for the transformation,
# which will be on the center of the new image.
target_focus_point = [
  target_image_size[0].to_f / 2.0,
  target_image_size[1].to_f / 2.0
]

# Define how many degrees the image should be rotated.
rotation_degrees = 0

command = [
  'convert',
  source_image,
  "-set option:distort:viewport #{target_image_size.join('x')}",
  "-distort SRT '#{source_focus_point.join(',')} #{scale_factor} #{rotation_degrees} #{target_focus_point.join(',')}'",
  'output2.jpg'
].join ' '

The resulting command is:
convert input.jpg -set option:distort:viewport 295x195 -distort SRT '1405.000000128,484.0 0.242 0 147.5,97.5' output.jpg

In my understanding, imagemagick's distort SRT's second argument (here, scale_factor) defines how much, in %, the image has to be scaled down. My idea was to calculate the distances of all sides to the focus point, take the smallest distance, convert it to a suitable argument, and use that one for defining the scaling amount.
The goal is to scale the image as much as possible to ensure that the output image does not crop off too much in order to show as much as possible of the original image. My output right now cuts off too much.
I tried to visualize it for a better understanding:

The original image can be found here: https://unsplash.com/photos/p-I9wV811qk
What am I doing wrong? How do I calculate the value for scaling down the image correctly to have as much of the picture visible as possible?

Edit 1
At the end, multiple variations of the image will be generated, having different aspect ratios. Next to the given 295x195, another one will be 1440x560; Especially in this one, a simple "crop with gravity" will most likely crop out the middle or upper part of the image, thus the focus point to ensure the vital part is always visible.

Edit 2 to the answer from fmw42
The code works so far that it does resizing and cropping without using SRT. Unfortunately, the result is further away compared to the result I'm currently having (but maybe I did something wrong when adapting the script).
What I did was

*

*using the image from my question

*replacing px and py with the focus point values from my question

*keeping the scale calculation but using wd=295 and ht=195 as this is the desired target crop

The resulting output looks like this:

A: Here is how I would do that in Imagemagick (Unix syntax)
Input:

# get image dimensions and aspect ratio
WxH=`convert barn.jpg -format "%wx%h" info:`
ww=`echo "$WxH" | cut -dx -f1`
hh=`echo "$WxH" | cut -dx -f2`
aspect=`convert xc: -format "%[fx:$ww/$hh]" info:`

# define centering point
px=200
py=200

# compute distances to each side of the image
dleft=$px
dright=$((ww-px-1))
dtop=$py
dbottom=$((hh-py-1))

# find the minimum distance and to which side
dminx=`convert xc: -format "%[fx:round(min($dleft,$dright))]" info:`
dminy=`convert xc: -format "%[fx:round(min($dtop,$dbottom))]" info:`
dmin=`convert xc: -format "%[fx:round(min($dminx,$dminy))]" info:`

# compute crop width, height and scale percent
if [ $dmin -eq $dminx ]; then
wd=$((2*dminx))
ht=`convert xc: -format "%[fx:round($wd/$aspect)]" info:`
scale=`convert xc: -format "%[fx:100*$ww/$wd]" info:`
else
ht=$((2*dminy))
wd=`convert xc: -format "%[fx:round($ht*$aspect)]" info:`
scale=`convert xc: -format "%[fx:100*$hh/$ht]" info:`
fi

# compute x and y offsets to the top left corner of crop region
xoff=`convert xc: -format "%[fx:round($px-$wd/2)]" info:`
yoff=`convert xc: -format "%[fx:round($py-$ht/2)]" info:`

# crop and resize the image to original dimensions
convert barn.jpg -crop ${wd}x${ht}+${xoff}+${yoff} +repage -resize $scale% barn_result.jpg

Result:

A: If your center point is too close to a side of the image, it may not support either of those sizes or aspect ratios. What do you want done in those cases? Should the image be smaller than your desired sizes or padded with black or transparent? Or should the desired size be maintained and the desired center not be in the center?
Here is an ImageMagick solution, assuming I now understand what you want, that will crop the desired sizes and aspects. If the center is too close to one side, the output size will still be as desired, but the desired point will not be in the center. I have marked the desired point in relative to the coordinates in the input with a small red circle.
Once again, Unix syntax.
Input:

Desired point at 200,200:
cd
cd desktop
infile="barn.jpg"
inname=`convert "$infile" -format "%t" info:`
# get image dimensions and aspect ratio
WxH=`convert "$infile" -format "%wx%h" info:`
ww=`echo "$WxH" | cut -dx -f1`
hh=`echo "$WxH" | cut -dx -f2`

# define centering point
px=50
py=50

# define crop size
wd=295
ht=195

# check if enough space on each side
left=`convert xc: -format "%[fx:round($px-$wd/2)]" info:`
left=`convert xc: -format "%[fx:$left<0?0:$left]" info:`
right=`convert xc: -format "%[fx:$left+$wd-1]" info:`
right=`convert xc: -format "%[fx:$right>$ww-1?$ww-1:$right]" info:`
top=`convert xc: -format "%[fx:round($py-$ht/2)]" info:`
top=`convert xc: -format "%[fx:$top<0?0:$top]" info:`
bottom=`convert xc: -format "%[fx:$top+$ht-1]" info:`
bottom=`convert xc: -format "%[fx:$bottom>$hh-1?$hh-1:$bottom]" info:`

# compute crop values
xoff=$left
yoff=$top
width=`convert xc: -format "%[fx:round($right-$left+1)]" info:`
height=`convert xc: -format "%[fx:round($bottom-$top+1)]" info:`
echo "$left; $right; $top; $bottom;"
echo "$xoff; $yoff; $width; $height"

# crop and resize the image to original dimensions
convert "$infile" -fill red -draw "translate $px,$py circle 0,0 0,2" -alpha off \
-crop ${width}x${height}+${xoff}+${yoff} +repage ${inname}_${px}_${py}.jpg

Desired point at 50,50:


text:
Q: How to connect a USB 2.0 9 pin cable to a USB 3.0 19 pin connector? I have a multi-card reader that connects to my motherboard via USB 9/10 pin port, the problem is that I have none available, however I have a free 19/20 pin USB 3 port. I have been looking everywhere for an adapter to convert the 9 pin to 19 but I cannot find it anywhere... The only one I found is the other way around, 19 to 9.
Am I missing something? Like it's not possible to do the conversion or something?
Thanks!
EDIT: I don't want to just jam the 9 pin into the 19... I was looking more for an adapter/converter

A: Ok I accidentally found it... It seems to be much less common than 19 to 9... for whoever is interested this is what I was looking for.
http://www.amazon.com/SIENOC-USB3-0-Female-Motherboard-Adapter/dp/B00O0HC3Y0


text:
Q: Problem in setting video thumbnail with ffmpeg I'm trying to add thumbnail to a mkv video with the following command: ffmpeg -y -i video.mkv -i image.jpg -map 1 -map 0 -c copy -disposition:0 attached_pic out.mkv. However this command replaces all frames in the video with that image and no sound. Am I doing something wrong. I'm using latest version of ffmpeg.

A: What you tried works for MP4 file and not for MKV file. Try this:
ffmpeg -y -i video.mkv -i image.jpg \
       -attach image.jpg -metadata:s:t mimetype=image/jpeg \
       -c copy out.mkv


text:
Q: Swift | UICollectionView without storyboard shows incorrect data I am building an app that has a UICollectionView with three items. Each item takes up the complete width of the screen and shows a timer that counts down to the next  departure times for our busses in each location.
Each item contains 1) the departure address, 2) a string "Next shuttle leaves at time", and 3) a timer that counts down to the next departure time in 00:00:00 format.
Item 1 and 2 display as expected, but when I get to item 3 the departure address and string are correct, but the timer shows the time for cell 1 instead of cell 3.
I am setting the UICollectionView up like:
func setupCollectionView() {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.itemSize = frame.size
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    let collFrame:CGRect = CGRectMake(0, 0, self.frame.width, self.frame.height)
    collectionView = UICollectionView(frame: collFrame, collectionViewLayout: layout)
    collectionView!.dataSource = self
    collectionView!.delegate = self
    collectionView!.registerClass(NextShuttleCell.self, forCellWithReuseIdentifier: "cell")
    collectionView!.backgroundColor = UIColor.whiteColor()
    collectionView!.pagingEnabled = true
    collectionView!.scrollIndicatorInsets = UIEdgeInsetsZero
    collectionView!.layer.borderWidth = 0
    collectionView!.layer.borderColor = UIColor.clearColor().CGColor
    self.addSubview(collectionView!)

}

And creating the items using:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell:NextShuttleCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! NextShuttleCell

    switch(indexPath.row) {
    case 0:
        cell.setCellColor(help.darkAccent1())
        cell.setLocationLabel("Auckland, Victoria Street")
        cell.schedule = getScheduleFor("Victoria Street")
    case 1:
        cell.setCellColor(help.darkAccent2())
        cell.setLocationLabel("Wellington, Airedale Street")
        cell.schedule = getScheduleFor("Airedale Street")
    case 2:
        cell.setCellColor(help.darkAccent3())
        cell.setLocationLabel("Airport, Auckland")
        cell.schedule = getScheduleFor("Auckland Airport")
    default: break
    }

    return cell

}

When this view is instantiated it retrieves the schedule from Parse.com. The getScheduleFor function then iterates through this schedule and returns the relevant locations schedule object to the custom cell.
I know that the getScheduleFor function is working correctly as it pulls the right information for the first two items, and if I change the order of the items (e.g. swap the item 3 code with item 1, then the correct data shows in item 1 but item 3 is incorrect.
Also note that it is only the timer that is incorrect on item 3, the remaining information is correct and this is pulled from the schedule object as well - so I know it's pulling the right data.
I also moved this into a UITableView and it showed the correct data so it seems to be something to do with the way the UICollectionView manages it's items.
EDIT:
I am using a custom UICollectionViewCell and initialising it using:
override init(frame: CGRect) {
super.init(frame: frame)
    initTimer()
}

This gets the next shuttle time and initialises a timer to update the count down label.
func initTimer() {
    nextShuttleTime = getNextShuttleTime()
    timeTillNextShuttle = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateTime", userInfo: nil, repeats: true)
}

Then, it gets the time using the following:
func updateTime() {

    let nextShuttleAt:NSTimeInterval = NSTimeInterval(nextShuttleTime.timeIntervalSinceNow)
    let currentTime:NSTimeInterval = NSTimeInterval(NSDate().timeIntervalSinceNow)
    let timeLeft:NSTimeInterval = nextShuttleAt - currentTime

    if timeLeft >= 0 {
        let seconds = timeLeft
        timeLabel.text = "\(stringFromTimeInterval(seconds))"
        self.updateNextShuttleLabel()
    } else {
        timeTillNextShuttle.invalidate()
        initTimer()
    }

}

WORKING SOLUTION:
As per the comments, I stopped getNextShuttleTime() from being assigned to a variable and instead called this in the updateTimer() function. Updated as per below:
func initTimer() {
    timeTillNextShuttle = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateTime", userInfo: nil, repeats: true)
}

func updateTime() {

    let nextShuttleAt:NSTimeInterval = NSTimeInterval(getNextShuttleTime().timeIntervalSinceNow)
    let currentTime:NSTimeInterval = NSTimeInterval(NSDate().timeIntervalSinceNow)
    let timeLeft:NSTimeInterval = nextShuttleAt - currentTime

    if timeLeft >= 0 {
        let seconds = timeLeft
        timeLabel.text = "\(stringFromTimeInterval(seconds))"
        self.updateNextShuttleLabel()
    } else {
        timeTillNextShuttle.invalidate()
        initTimer()
    }

}

A: Your NextShuttleCell objects will be re-used, so you need to make sure that everything is updated when the cell is assigned - you can't rely on init() as this will only be called the first time that a cell is assigned.
Rather than storing the nextShuttleTime variable in initTimer() you can call getNextShuttleTime() in updateTime - this way you will always get the correct time.


text:
Q: what happened when MVVMLight SimpleIoc registered multiple times? I'd like to know when .Register() is performed multiple times. Based on my experiment, below Console.WriteLine gives same Init value.
So, does .Register() check already registered instance and ignore to re-register?
void Main()
{
    // #1
    SimpleIoc.Default.Register<TestClass>();
    Console.WriteLine(SimpleIoc.Default.GetInstance<TestClass>().Init);

    // #2
    SimpleIoc.Default.Register<TestClass>();
    Console.WriteLine(SimpleIoc.Default.GetInstance<TestClass>().Init);

    // Result: #1 and #2 give identical Init value.
}

public class TestClass
{
    public string Init { get; set;}
    public TestClass()
    {
        Init = Guid.NewGuid().ToString();
    }
}

A: If look at source code of Register method by decompiling it (in case you cannot find \ don't want to bother with actual source code), you will see (with irrelevant parts skipped):
public void Register<TClass>(bool createInstanceImmediately) where TClass : class
{
  Type index = typeof (TClass);
  // skipped irrelevant parts
  if (this._factories.ContainsKey(index) && this._factories[index].ContainsKey(this._defaultKey))
  {
     if (!this._constructorInfos.ContainsKey(index))
       throw new InvalidOperationException(string.Format((IFormatProvider) CultureInfo.InvariantCulture, "Class {0} is already registered.", (object) index));
  } else {
      if (!this._interfaceToClassMap.ContainsKey(index))
        this._interfaceToClassMap.Add(index, (Type) null);
      this._constructorInfos.Add(index, this.GetConstructorInfo(index));
      Func<TClass> factory = new Func<TClass>(this.MakeInstance<TClass>);
      this.DoRegister<TClass>(index, factory, this._defaultKey);
      if (!createInstanceImmediately)
        return;
      this.GetInstance<TClass>();
    }
  }
}

So, if there is already registered factory in _factories dictionary - it checks if there is constructor info registered for this type and if NOT - throws exception about already registered class. I suppose this is a typo and check should be reversed - if there IS already registered constructor (which you register in else block) - there should be exception about already registered class. But as it is implemented now - it just does nothing when you try to register second time.


text:
Q: CSS doesn't work similarly on similar elements everyone. I'm working on a Node/Express + Jade application. I used the same styling for the login and register pages. The CSS for the pages is shown below:
.form-page {
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
}
.form {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 70%;
  height: 100%;
}
.form form .form-input {
  width: 100%;
  height: 35px;
  background-color: #505050;
  margin-bottom: 10px;
  border: none;
  padding-left: 10px;
  font-size: 16px;
  color: #FFFFFF;
}
.form form {
  margin-top: 20px;
  width: auto;
}
.form .form-header {
  font-size: 50px;
  color: #FFFFFF;
}
.form .form-header .logo {
  color: #505050;
}
form .btn-action {
  background-color: #505050;
  color: #FFFFFF;
  width: 100px;
  height: 35px;
  border: none;
  font-family: IBM Plex Mono;
  font-size: 15px;
  margin-top: 10px;
  font-weight: lighter;
}
form .btn-action:hover {
  background-color: transparent;
  color: #FFFFFF;
  border: 2px solid #505050;
  cursor: pointer;
}
.form .alternative {
  font-size: 16px;
  color: #D3D3D3;
  margin-top: 10px;
}
.form .alternative .alternative-link {
  color: #FFFFFF;
}

The Jade templates are seen below:
register.pug (Signup page)
doctype html
html
  head
    title Register | Diode
    meta(name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no')

    link(rel='stylesheet' type='text/css' href='/css/diode.css')
  body.form-page
    .form(align='center')
      p.form-header Register |
        span.logo Diode
      form(method='post' action='/users/register')
        input.form-input(placeholder='Your first name' name='firstname' type='text' required)
        input.form-input(placeholder='Your last name' name='lastname' type='text' required)
        input.form-input(placeholder='Your email address' name='email' type='email' required)
        input.form-input(placeholder='Your username' name='username' type='text' required)
        input.form-input(placeholder='Your password' name='password' type='password' required)
        input.form-input(placeholder='Confirm your password' name='confirmpassword' type='password' required)
        button.btn-action(type='submit') Register
      p.alternative Already have an account?
        a.alternative-link(href='/users/login') Log In.

And login.pug (Login page)
doctype html
html
  head
    title Login | Diode
    meta(name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no')

    link(rel='stylesheet' type='text/css' href='/css/diode.css')
  body.form-page
    .form(align='center')
      p.form-header Log In |
        span.logo Diode
      form(method='post' action='/users/login')
        input.form-input(placeholder='Your username' name='username' type='text' required)
        input.form-input(placeholder='Your password' name='password' type='password' required)
        button.btn-action(type='submit') Log In
      p.alternative Don't have an account?
        a.alternative-link(href='/users/register') Sign up.

The problem is, the width of the form inputs on a laptop screen is smaller on the login page than on the register page, but the same on mobile. How do I make them the same size. Note that the below images are of different sizes, which make them look similar.


text:
Q: Defined product custom field value replace price on WooCommerce loop On my WooCommerce products I would like to replace product price by the product model reference custom field (ex: #AB2568B). How to display the model reference instead of the price? Any help please.

A: As you don't give any detail on your product custom field, The code below will add a custom field to admin single product settings.
Then when this custom field will have a defined value, it will replace the product price:
// Admin product general settings: Display a custom field (below prices)
add_action( 'woocommerce_product_options_pricing', 'add_product_general_setting_field' );
function add_product_general_setting_field() {
    echo '
';

    woocommerce_wp_text_input( array(
        'id'                => '_reference_id',
        'label'             => __( 'Reference Id', 'woocommerce' ),
        'placeholder'       => __( 'Please enter the model reference Id', 'woocommerce' ),
        'description'       => __( 'Please enter the model reference Id', 'woocommerce' ),
    ) );

    echo '
';
}

// Admin product general settings: Save custom field
add_action( 'woocommerce_admin_process_product_object', 'save_product_general_setting_field' );
function save_product_general_setting_field( $product ){
    if(isset($_POST['_reference_id']) ) {
        $product->update_meta_data( '_reference_id', sanitize_texT_field( $_POST['_reference_id']) );
    }
}

// replace loop product price by the model reference Id
add_action( 'woocommerce_after_shop_loop_item_title', 'action_after_shop_loop_item_title_callback', 9 );
function action_after_shop_loop_item_title_callback() {
    global $product;

    $reference_id = $product->get_meta('_reference_id');

    if( ! empty($reference_id) ) {
        remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 ); // remove the price

        // Display the model reference
        echo ''.$reference_id.'';
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


text:
Q: Freezing first row while highlighting row and column I need to do a table where I need to freeze the top row and highlight the row and column on hover.
I have the 2 working separately but when I combine them, it isn't working right.

#table_grid {
  border-spacing: 0;
  border-collapse: collapse;
  overflow: hidden;
  font-family: arial, verdana, sans-serif;
  font-size: 12px;
  background: #fff;
  margin: 0px;
  text-align: left;
  max-width: 1200px;
  border-radius: 10px;
}

#table_grid td,
th {
  color: #669;
  padding: 9px 8px 4px 8px;
  font-size: 13px;
  position: relative;
}

#table_grid tr:hover {
  background-color: rgba(220, 220, 220, 0.5);
}

#table_grid td:hover::after,
th:hover::after {
  background-color: rgba(211, 211, 211, 0.2);
  content: '\00a0';
  height: 10000px;
  left: 0;
  position: absolute;
  top: -5000px;
  width: 100%;
  pointer-events: none;
}

table {
  text-align: left;
  position: relative;
  border-collapse: collapse;
}

th,
td {
  padding: 0.25rem;
}

th {
  background: white;
  position: sticky;
  top: 0;
  /* Don't forget this, required for the stickiness */
  box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
}

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

    test
    test
    test
    test
    test
    test

If I change
overflow: hidden

to
overflow: auto

in #table_grid, the highlight on hover and freezing the first row is working but the hightlight on hover is running off the screen.
If I change it back to
overflow: hidden

Hightlight on hover is working properly but the first row is not freezing.
Is there any way to fix this?


text:
Q: Meteor Svelte can't find files I create on Ubuntu I've tried following along multiple Meteor tutorials, and I keep getting the same issue, although I haven't been able to find a solution when searching for answers.
When I try to import html files in my client/main.js, it keeps telling me it can't find those modules. For example, I have the following file:
imports/app.svelte

Yo!

Then in my main.js:
client/main.js
import { Meteor } from 'meteor/meteor';
import App from '../imports/App.svelte';

Meteor.startup(() => {
  new App({
    target: document.getElementById("app"),
  });
});

And now I keep getting this error:
Uncaught Error: Cannot find module '../imports/App.svelte'

I'm following along a LevelUpTuts tutorial, so I'm certain I've installed the right packages etc. And as mentioned, the same happened when I tried to do the Meteor official tutorial as well as the Vue tutorial. I'm suspecting this might have something to do with Ubuntu?

A: You have a typo there in the filename: Your file is called app.svelte, but you are importing App.svelte.
You need to rename the file to be called App.svelte with capital A.

Your feeling that it has something to do with Ubuntu is sort-of-right because the file system there is by default case-sensitive, while in Windows it is by default case-insensitive. So if you previously did the same mistake in Windows, you may not have noticed it because when the application asked Windows for App.svelte, Windows happily said "yes here is your file" and sent app.svelte instead, while Ubuntu would say "no sorry I don't know about any App.svelte (only an app.svelte but you asked for App and not app, soo...)".
So, Ubuntu made your mistake visible while Windows hid it away. It's good that you ran into this issue now and not only once you were trying to deploy your code to a Linux server.


text:
Q: Flutter build crashes using ProGuard with Firebase Auth I followed these instructions on adding ProGuard to Flutter and am now seeing this exception when starting the application:
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/auth/internal/zzae;

This is obviously connected to Firebase Auth. The mentioned instructions also state the following:

Any additional libraries (for example, Firebase) require their own rules to be added.

I did, however, not find any resources which show what statements I would need to append to proguard-rules.pro.
I can imagine that other Firebase components would crash similarly after the Auth component is fixed, so I am wondering what the meaning of "for example, Firebase" is, i.e. if there are rules for every component or if I will just need to fix this for Firebase Authentication.

A: Include
-keep class com.google.firebase.** { *; }

Proguard is providing you with several features: dead code removal, code size reduction by renaming class members and package names to short strings and, by that renaming, making the code more difficult to read and thus reverse engineer.
By keeping the whole com.google.firebase tree intact you are not benefiting from the size reductions. I guess obfuscation is irrelevant in this case since it's a open source library.
You could experiment with just keeping the top level API classes that you use (you may not be able to tell what those are without reading the firebase plugin implementation) to achieve the size reduction, but that's a lot of work to achieve a possible reduction in APK size, and probably introduces some fragility.
No, it is not 'optimal', but it's simple.


text:
Q: why my PCA and PCA from sklearn get different results? I tried to use the PCA provided in "machine learning in action", but I found that the results obtained by it are not the same as those obtained by the PCA in sklearn. I don't quite understand what is going on.
Below is my code:
import numpy as np
from sklearn.decomposition import PCA

x = np.array([
    [1,2,3,4,5, 0],
    [0.6,0.7,0.8,0.9,0.10, 0],
    [110,120,130,140,150, 0]
])

def my_pca(data, dim):
    remove_mean = data - data.mean(axis=0)
    cov_data = np.cov(remove_mean, rowvar=0)
    eig_val, eig_vec = np.linalg.eig(np.mat(cov_data))
    sorted_eig_val = np.argsort(eig_val)
    eig_index = sorted_eig_val[:-(dim+1):-1]
    transfer = eig_vec[:,eig_index]
    low_dim = remove_mean * transfer
    return np.array(low_dim, dtype=float)

pca = PCA(n_components = 3)
pca.fit(x)
new_x = pca.transform(x)
print("sklearn")
print(new_x)

new_x = my_pca(x, 3)
print("my")
print(new_x)

Output:
sklearn
[[-9.32494230e+01  1.46120285e+00  2.37676120e-15]
 [-9.89004904e+01 -1.43283197e+00  2.98143675e-14]
 [ 1.92149913e+02 -2.83708789e-02  2.81307176e-15]]

my
[[ 9.32494230e+01 -1.46120285e+00  7.39333927e-14]
 [ 9.89004904e+01  1.43283197e+00 -7.01760428e-14]
 [-1.92149913e+02  2.83708789e-02  1.84375626e-14]]

A: The issue relates to your function, in particular the part where you calculate your eigenvector and eigenvalues:
eig_val, eig_vec = np.linalg.eig(np.mat(cov_data))

It appears that ScitKit learn uses "eigh" instead of "eig", so if you change the code snippet from np.linalg.eig to np.linalg.eigh, you should get the same results.


text:
Q: prove this inequality $x^{n+1}\geq (n+1) x-n$ I tied to prove this by induction
$$\forall x\in\mathbb{R_+} ,\forall n \in\mathbb{N}:x^{n+1}\geq (n+1) x-n$$
I know it holds for $n=1$ but I get stacked after this step.

A: Simple solution using AM-GM: $\frac{x^{n+1}+n}{n+1}=\frac{x^{n+1}+1+1+...+1}{n+1} \geq \sqrt[n+1]{x^{n+1}\cdot 1\cdot 1 \cdot ... \cdot1} = x \implies $ $$x^{n+1}\geq (n+1) x-n.$$

In addition, there is a solution where you don't need to know any AM-GM or use induction:
$x^{n+1}-x\ge n(x-1) \iff x(x^n-1)\geq n(x-1) \iff x(x-1)(x^{n-1}+x^{n-2}+...+x+1)\geq n(x-1) \iff$ $$(x-1)(x^n+x^{n-1}+...+x^2+x-n)\geq 0$$ If $x\ge1$, then $x^n+x^{n-1}+...+x^2+x\ge1+1+...+1=n$, and if $x \le 1$, then $x^n+x^{n-1}+...+x^2+x\le1+1+...+1=n$, so
$$(x-1)(x^n+x^{n-1}+...+x^2+x-n)\geq 0 \implies x^{n+1}-x\ge n(x-1)$$

A: Assume $x\geq 0, n\geq 0$.
Define $f(x)=x^{n+1}-(n+1)x+n$, then $f'(x)=(n+1)(x^n-1)$.
The function is monotone increasing in $[1,+\infty)$ and decreasing in $[0,1]$. So the minimal is $f(1)=0$.
Then, $f(x)\geq0$ for all $x\geq 0$, i.e., $x^{n+1}\geq(n+1)x-n$.

1.$n=1$ holds.

*Assume $n=k$ holds. then, $x^{k+1}\geq(k+1)x-k, \forall x$.

Then, for $n=k+1$, we have
\begin{equation}
\begin{aligned}
x^{k+2}&=x*x^{k+1}\\
&\geq (k+1)x^2-kx\\
&=(k+2)x-(k+1)-(k+2)x+(k+1)x^2-kx+(k+1)\\
&=(k+2)x-(k+1)+(k+1)(x-1)^2\\
&\geq (k+2)x-(k+1).
\end{aligned}
\end{equation}
So, the inequality also holds for $k+1$

*Therefore, the inequality holds for all positive integers.


text:
Q: $a=b$ yet I'm allowed to turn $a$ into $b$ but not $b$ into $a$. PatrickJMT at 9:49 of this video says that you can turn $$\sum_{n=0}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}$$ into $$\sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}$$
and that the converse is wrong.
Logically this doesn't make sense. Both series are equal because the first two terms of the infinite sums are zero.
If $a=b$ then I can turn $a$ into $b$ or I can turn $b$ into $a$.

A: That's not what he said.
He said that whereas you change $\sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}$ to $\sum_{n=0}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}$ and back and forth because of the $0$ terms
However you can change $\sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}\color{red}{( = \sum_{m=0} \frac{(-1)^{m+2}(m+2)(m+2-1)x^{m+2}}{2}) }  = \sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$ by reindexing.  I think this is clear if we do an additional red step.  Let $n= m+2$ and express in terms of $m$.  Then just replace the symbols for $m$ to $n$.
What has says now is we can't replace  $ \sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$ with $\sum_{n=2} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$ because we don't have any zero terms anymore.
In summery:  $\sum_{n=0}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}=\sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}=\sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$
But $ \sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}\ne \sum_{n=2} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$
.....
.... You can go from $\sum_{n=0}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2} = \sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}$ because the first two terms are zero.  You can go from $\sum_{n=2}^\infty  \frac{(-1)^nn(n-1)x^{n}}{2}= \sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$ because you are reexpressing and lowering the index of the non zero terms.  But you can't go from $\sum_{n=0} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}\ne \sum_{n=2} \frac{(-1)^{n+2}(n+2)(n+2-1)x^{n+2}}{2}$ because you don't have any non-zero terms anymore.

A: It's because the first two terms of the first sum are $0$, hence we can shift the lower limit.
Let us consider the second sum right now. The first term (for $n=2$) equals $\frac{(-1)^2 2 x^2}{2} \neq 0$ and the second $\frac{(-1)^3 6 x^3}{2} \neq 0$, hence there is no reason to get rid of them.


text:
Q: Hibernate delete How do I delete object from Hibernate?
 Session session = HibernateSession.getSessionFactory().openSession();
        org.hibernate.Transaction tx = session.beginTransaction();
        int q = session.createQuery("from Modele where (model='"+u.getModel() +"' and markaid='"+u.getMarki().getId()+"'").executeUpdate();
      //  session.delete(u);

        session.getTransaction().commit();

INFO: Not supported!  Use the AST translator...
When using session.delete(u)  instead I get this
INFO: handling transient entity in delete processing
CREATE TABLE modele
(
  id serial NOT NULL,
  markaid integer NOT NULL,
  cena numeric(100,2),
  model character varying(32),
  CONSTRAINT k_glwny PRIMARY KEY (id),
  CONSTRAINT obcy FOREIGN KEY (markaid)
      REFERENCES marki (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE
)

<hibernate-mapping>
    <class name="bazaMap.Modele" table="modele" schema="public">
        <id name="id" type="int">
            <column name="id" />
            <generator class="identity" />
        </id>
        <many-to-one name="marki" class="bazaMap.Marki" fetch="select">
            <column name="markaid" not-null="true" />
        </many-to-one>
        <property name="cena" type="java.lang.Double">
            <column name="cena" scale="0" />
        </property>
        <property name="model" type="string">
            <column name="model" length="32" />
        </property>
        <set name="wypozyczenias" inverse="true">
            <key>
                <column name="modelid" not-null="true" />
            </key>
            <one-to-many class="bazaMap.Wypozyczenia" />
        </set>
    </class>
</hibernate-mapping>

This doesnt work too
session.createQuery("from Modele where model = :mmodel and markaid = :mmarkaid").setParameter("mmodel", u.getModel()).setParameter("mmarkaid", u.getMarki().getId()).executeUpdate();

A: I believe that your HQL is missing the DELETE keyword which is causing the AST error (basically an HQL syntax error.)  It should be:
DELETE from Modele where (model='"+u.getModel() +"' and markaid='"+u.getMarki().getId()+"'"

If you want to use the delete method (which is actually deprecated in hibernate 3 in favor of using HQL) you have to make sure that you load the entity in the same session your are deleting it from before you delete it.
I generally use the HQL style delete, although I would recommend using named parameters instead of string concatenation.


text:
Q: Is it a good practice to test absolutely everything or it is a waste of time (Rails)? I recently learned, Rspec + Capybara (I'm new to testing things). And I've been testing some new models I've created. Now, I was thinking of adding the title column to my Post model. It's not a hard task, and I've done it many times before. But I realized that it's going to take me some work updating the spec files (e.g. post, post pages, user, user pages, factories, sample_data, etc.).
Is testing in this case, a waste of time? Or it is a good practice to test absolutely everything?
I also wonder if testing gems is a waste of time as well? Since they've been probably already tested by their creators (the same for testing something taken from a reliable tutorial).

A: While the ruby community is known by its focus on testing, every case should be analyzed in context to figure out what the most cost-effective decisions are.
It is useful to think of tests as a technique to manage risk. If you don't think that displaying titles/adding them to the database is a task that is error-prone, complex to perform, or that the cost of adding those tests is higher than the risk of eventually breaking something, them it might be wise to not do it.
That said, since you said that you are new to testing, I would recommend (if you are not time-constrained, of course) to try to take the idea to the extreme of testing absolutely everything, so that you can have an idea of how much of it adds value, and how much is waste of time.
You might want to take a look at this blog post from DHH, the creator of Rails, where he talks about that: Testing like the TSA
About testing gems, it is generally well-accepted that they shouldn't be tested by your application tests, but by their creators. Most of the time you can simply assume that they work the ways they promise.

A: one of the main concepts of testing is: "It's impossible to test everything"


text:
Q: How to set value from grid column to textbox? I have a DataGridView in which i have a column 'total'. DataGridView is editable true. below the grid view i have textbox in which i want the total of the 'total' column of grid. What i did is, when user enters into the total column in grid, it reflects into the total text field belo the grid view. to display total in the textfield, i added the total column of grid view. But the problem is, if first time i enter into the total column of grid view, it immediately reflects into the textfield below. but if i edit the same value in total column of DataGridView, the textfield below the grid adds it with previous value where i want the new edited value in the textfield. How to fix this?
Following is the code:-
    private void grdCaret_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        try
        {

            string value = grdCaret.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            if (e.ColumnIndex == 1)
            {
               int val = int.Parse(value);
               quantity = val;
               ekundag = ekundag + quantity;
               tbTotDag_cr.Text =ekundag.ToString();
            }

            if (e.ColumnIndex == 2)
            {
                float val = float.Parse(value);
                total = val;
                ekunrakam = ekunrakam + total;
                tbTotPrice_cr.Text = ekunrakam.ToString();
            }
            grdCaret.Columns[3].ReadOnly = false;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }


text:
Q: PHP count() returns 2 separate values So I have a function that selects all the columns where something = something, and then I return a variable that fetches all $var->fetchAll();.
I made that function so I can count whatever it's returning and it almost worked as expected.
That function returns (using var_dump for debug):
array(2) { [0]=> array(2) { ["id"]=> string(2) "18" [0]=> string(2) "18" } [1]=> array(2) { ["id"]=> string(2) "19" [0]=> string(2) "19" } } 2

array(1) { [0]=> array(2) { ["id"]=> string(2) "20" [0]=> string(2) "20" } } 1

it returns this separately so when I count() this it returns 2 and 1 separately instead of 3... any idea why ?
Here is the code I made:
$ticketsRes = $objDatabase->getMemberResponsesById($playerTicket->ticketid);

var_dump($ticketsRes);

$group = array();

foreach ( $ticketsRes as $ticket ) {
    $group[$ticket['id']][] = $ticket;
}

echo count($group); //returns 2 and 1 instead of 3

A: Count only conuts the top level of the array, nested arrays mean you have to do
count ( $array, true )

For example it even says array(2) {..} array(1){...} from your var_dump, which tells me right there that I would expect 2 and 1 from count($array).  Besides I can tell it's multi-dimensional arrays just looking at them.
http://php.net/manual/en/function.count.php

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
mode: If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.

The little known second parameter allows you to count "recursively" by setting it to 1 or COUNT_RECURSIVE, but in PHP true is the same thing as 1 ( so lazy me just uses that )
Right who knew count has 2 inputs, ( << this guy ).  I also know you can do isset on multiple items isset($item1, $item2, ... ) ha ha.  I also know your output is from var dump,  yea me...  ( I write too much code, almost got divorced when I was learning PHP, got a bit addicted to it)


text:
Q: Unity2D: Player continues to move after he respawns Okay to be basic, I have a 2d top down click to move game with a small problem. You see I created my player to have three heart lives and that after you get hit by an object you lose a heart, once you lose a heart the player automatically re-spawn back to where he started. however I'm having problems with player's movement, as mentioned before to move my player you have to click around (click to move). When I click to a place and I get hit by an object my player does go back to where it started off at (which is what I want) but after it reset back to where it was in the beginning, my player would continue to move until it get to the destination (which is not want I want)
This is my player movement's script:
public class PlayerMovement : MonoBehaviour {

private Animator anim;
public float speed = 15f;
private Vector3 target;
public PlayerMovement playerMovementRef;
private bool touched;

void Start () {
    target = transform.position;
    anim = GetComponent<Animator> ();
}

void Update () {
    if (Input.GetMouseButtonDown (0)) {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition.z = 10; // distance from the camera
        target = Camera.main.ScreenToWorldPoint(mousePosition);
        target.z = transform.position.z;
    }

    transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

    var movementDirection = (target - transform.position).normalized;

    if (movementDirection.x != 0 || movementDirection.y != 0) {
        anim.SetBool ("walking", false);
        anim.SetFloat("SpeedX", movementDirection.x);
        anim.SetFloat("SpeedY", movementDirection.y);
        anim.SetBool ("walking", true);
    }
}

void FixedUpdate () {
    float LastInputX = transform.position.x - target.x;
    float LastInputY = transform.position.y - target.y;

    if (touched) {
        if (LastInputX != 0 || LastInputY != 0) {
            anim.SetBool ("walking", true);
            if (LastInputX < 0) {
                anim.SetFloat ("LastMoveX", 1f);
            } else if (LastInputX > 0) {
                anim.SetFloat ("LastMoveX", -1f);
            } else {
                anim.SetFloat ("LastMoveX", 0f);
            }
            if (LastInputY > 0) {
                anim.SetFloat ("LastMoveY", 1f);
            } else if (LastInputY < 0) {
                anim.SetFloat ("LastMoveY", -1f);
            } else {
                anim.SetFloat ("LastMoveY", 0f);
            }
        }
    }else{
        touched = false;
        anim.SetBool ("walking", false);
        }
    }
}

And this is my Player's health script (this script respawns my player back to where it started after he is hit by an object):
public class PlayerHealth : MonoBehaviour {

//Stats
public int curHealth;
public int maxHealth = 3;
Vector3 startPosition;

void Start ()
{
    curHealth = maxHealth;
    startPosition = transform.position;
}

void Update ()
{

    if (curHealth > maxHealth) {
        curHealth = maxHealth;
    }
    if (curHealth <= 0) {

        Die ();
    }
}

void Die ()
{
    //Restart
    Application.LoadLevel (Application.loadedLevel);

}

public void Damage(int dmg)
{
    curHealth -= dmg;
    Reset();
}

void Reset()
{
    transform.position = startPosition;
    }
}

A: So when you first click a location that the player walk towards,
Input.GetMouseButtonDown (0) is true, so inside of the if statement you set mousePosition with the following line:
Vector3 mousePosition = Input.mousePosition;

and then you set the target equal to that with
target = Camera.main.ScreenToWorldPoint(mousePosition);

The problem is that outside of the if statement, but within the update method, you have
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

Where the player's postition is continually changed to move towards the target. This is causing the problem because update() is constantly being called, even after you respawn, and if you don't assign the target a different value, your player will still move towards target, which was set before the player dies.
So put simply, target is only set once when you click a place to move, but your character always moves towards target, even after he respawns. Inside of the Start() method, write something like PlayerMovement.target = startPosition
Keep in mind target will either have to be public or have a public getter and setter in order to be able to access it from your health class.


text:
Q: Are manifolds defined by level sets uniquely determined by gradients? Let $f : \mathbb R^n → \mathbb R$ be a continuously differentiable function with non-zero gradient. Then, according to the implicit function theorem a level set defines a $n-1$ dimensional manifold $M$ and the gradient of $f$ is perpendicular to $M$.
Now, assume that we have a second function $g : \mathbb R^n → \mathbb R$ also continuously differentiable with non-zero gradient.
How to prove or refute precisely that if for all points in $M$ (defined by the level set of $f$) the direction of the gradient of $f$ and $g$ is identical (but not the length), then $M$ is also a manifold defined by a level set of $g$.

A: Suppose that  $M=f^{-1}(a), a\in R$, for every $x$ in $M$, we have to show that $g$ is constant on the connected component of $M$ which contains $x$. Let $c:I\rightarrow M$ be a differentiable path such that $c(0)=x$, ${d\over{dt}}g(c(t))=\nabla g_{c(t)}.c'(t)=u(t)\nabla f_{c(t)}c'(t)=0$  since the restriction of f to M is constant and $\nabla f$ is proportional to $\nabla g$. This implies that $g$ is constant on $c$ and henceforth on the connected component of $M$ which contains $x$.


text:
Q: apache alias or redirect short url I would like to have a short url like:
https://domain/essr

to evaluate to:
https://domain/dir1/dir2/myFile.html

I've been trying to use alias in my apache config but I haven't been able to make it work. How would you go about it?

A: Best way to do this is using .htaccess mod-rewrite.
Create a .htaccess file in your web root directory. And paste this code:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/dir1/dir2/(.*)$
RewriteRule ^(.*) http://www.example.com/essr/%1 [R=301,NC]


text:
Q: parsing the JSON string with only mandatory POSIX tools I have json string like this
{"state":{"stateId":0,"nextPollingTime":null,"updateState":null},"config":{"privateIPs":null,"64Bit":false,"silent":false,"iid":14,"selfp":null,"sevlfp":null,"av":14,"aid":null,"aty":2,"sev":0,"seci":0,"sti":false,"scto":60000,"sci":5000,"stkd":5000,"sud":5000,"mpfa":3}}

I need to get "state" and "config" keys content to a shell custom variable or to a file.
tried with a command:
$RESPONSE is the API response, the above json string
 echo $RESPONSE | sed 's/{"$state":"*\([0-9a-zA-Z]*\)"*,*.*}/\1/'

this prints nothing but suppose to get this output:
{"stateId":0,"nextPollingTime":null,"updateState":null}

Tried with saving the response to tmp file and executed this command
cat /tmp/a.json | grep -o -e "{"state":.*}"

this also print empty string but expected result:
{"stateId":0,"nextPollingTime":null,"updateState":null}

Am new to shell script and trying with various options available in the internet, please help me to write the command for the same.

A: This uses any sed:
$ sed 's/.*"state":\({[^}]*}\).*/\1/' file
{"stateId":0,"nextPollingTime":null,"updateState":null}

That will work for your posted input but fail given other json input (e.g. with "state" as a value or with } inside a value), just like any other solution that uses mandatory POSIX tools as none of them have a JSON parser (unless you write one with awk, but I expect that's more work than you or anyone here would put into this).


text:
Q: Replacing a string in Rubymine with a string with newlines I want to use the Search and Replace dialogue in Rubymine, or something similar to replace something like "Scenario:" with "@Desktop\nScenario"
I'm trying to replace every instance of Scenario: in a large Cucumber test suite with
@desktop
Scenario:

Any best ways to do this?

A: Update:
Thanks to @ryan2johnson9 comment, I realise there's now an easier option (tested on 2017.3).
By clicking on the "New Line" (or using the shortcut Ctrl+Shift+Enter / Alt+Enter), the input becomes multilines.

Original Answer
In the search and replace box, if you tick the "Regex" option you can do:
Search: "Scenario:"
Replace by: "@desktop\nScenario:"
The only trick is to tick the "Regex" option :)

A: Rubymine has macros (http://www.jetbrains.com/ruby/webhelp/binding-macros-with-keyboard-shortcuts.html) but I dont think they are powerful enough for this example.
It's possible that you could solve it with some elaborate feature hidden inside Rubymine, but I think it would be a lot easier to do this with a tool like perl/sed from the Terminal. If you are using Windows I assume you could search the net and find a text search/replace tool that fits your need.
In OSX I there are a bunch of Text Substitutions app too.
I would go that route since Rubymines macro tool isnt up to the task.

A: Here's a cheap and sleazy alternative:

*

*Copy a newline character from between two empty lines in the file being edited.  Temporarily add two empty lines if you don't have any.

*Set up search/replace and enter the string you want to replace into the search text input box.

*Paste the newline you just copied into the replacement text box plus whatever other text you want.  You will be able to see the height of the replacement text input box grow vertically by one line due to the newline.

*Perform the search/replace.

For this, the use of the Rubymine regex is optional.


text:
Q: Using SSH to push to 2 different repos using the same account? I have two repositories on one machine on the same account on Github. I've added an ssh key to my account and pushing to repository A succeeds but I can't push to repository B. SSH keys on github aren't associated to specific repos iirc.
A little research has led me to find out that I need two different keys. How do I edit my config file so that git uses the correct key when pushing to the second repo?

A: I got to the solution by modifying the .ssh/config file to append this
Host repo2.github.com
  User git
  Port 22
  Hostname github.com
  IdentityFile ~/.ssh/id_rsa2
  TCPKeepAlive yes
  IdentitiesOnly yes
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no

and then adding by appending the following in the .git/config file
[remote "origin"]
    url = git@repo2.github.com:[Username]/G2-FrontEnd.git
    fetch = +refs/heads/*:refs/remotes/origin/*


text:
Q: Need to call com function from VB.NET If anyone wants to take a crack at this I'd really appreciate it. I'm writing a VB.NET app that will control a commercial backup product. One of the things I need to do is loop through all existing jobs and look at the source drive. I am able to do this in VBScript very simply like this:
Dim SP, BackupJob, volumes
Set SP = CreateObject("ShadowStor.ShadowProtect")
For Each Job In SP.Jobs
    Set BackupJob = SP.Jobs.GetBackupJob(Job.Description)
    BackupJob.GetVolumes volumes
    For Each Volume in volumes
        WScript.Echo volume
    Next
Next
Set SP = Nothing

However nothing I try in VB.NET works. I'm pretty sure it has to do with the fact that the com functions are returning variant data types and arrays (specifically GetVolumes). I have tried using string arrays, object arrays, and even wrapping the return value in a VariantWrapper and I always get errors such as "not implemented" or "the parameter is incorrect." If anyone is bored and wants to write some code I'll gladly give it a shot and report back.
UPDATE:
This is odd. Look at this code:
Dim SP As Object = CreateObject("ShadowStor.ShadowProtect")
Dim gotJob As Object
Dim volumes() As Object

Try
    For Each Job As Object In SP.Jobs
        gotJob = SP.Jobs.GetBackupJob(Job.Description.ToString())
        gotJob.GetVolumes(volumes)

        For Each volume As Object In volumes
            MsgBox(volume.ToString())
        Next

    Next

Catch ex As Exception
    MsgBox(ex.Message)
End Try

This will display the volume from ONE job, then it crashes if there is more than one jobwith the error "invalid callee."

A: Locate ShadowStor.ShadowProtect in your registry in HKCR.  It will have a CLSID which is a GUID.  Search for that GUID, also in HKCR.  You should find it in the CLSID section.  Under that key you should find the actual dll path under InprocServer32.
Now if that component has an embedded TypeLib you should be able to add a reference to it in Visual Studio.  (If you have OLE View installed you can inspect the type lib easily as well).
And if you cannot add a reference to the dll, there might be a seperate .tlb file, and you can find that by searching on the GUID present in the TypeLib value.

A: For anyone interested, the solution was to Dim volumes() As Object inside the loop and then set volumes = Nothing at the end of the loop so that it was re-created each time. If anyone can explain why this is so I would love to understand it.


text:
Q: Circular NIM Game Trying to change this code, so that it will play the nim game like this:
01  02  03  04  05  06  07  08  09
20                              10
19  18  17  16  15  14  13  12  11

So far, it prints like this:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7.

This is the code:
I know it's clunky code, but i'm still learning.
public class Main {

public static void main(String[] args) {
    System.out.println("Let's play the NIM game!");
    TheNimGame game = new TheNimGame();
    //Rows rows1 = new Rows();
    game.StartGame();
}

TheNimGame.java
package com.company;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by SimonBlixenkrone on 21/10/2015.
 */
public class TheNimGame {
    private Scanner scanner = new Scanner(System. in );
    private ArrayList < Player > players = new ArrayList < Player > ();
    private ArrayList < Rows > rows = new ArrayList < Rows > ();
    private int defaultValueForRows = 3;
    //private int maxNumberOfObjectsInRow = 5;
    private int maxNumberOfObjectsInRow = 10;

    public void SetNumberOfRows(int numberOfRows) {
        defaultValueForRows = numberOfRows;
    }

    public void StartGame() {
        // set game
        populateRows();

        //add players
        for (int i = 0; i < 2; i++) {
            System.out.println("Enter name of player " + i + ": ");
            Player player = new Player();
            player.setName(scanner.nextLine());
            players.add(player);
        }

        //run the game
        while (true) {
            printRows();
            takeTurn(players.get(0));
            if (gameover() == true) {
                System.out.println(players.get(0) + " lost the game");
                break;
            }
            printRows();
            takeTurn(players.get(1));
            if (gameover() == true) {
                System.out.println(players.get(1) + " lost the game");
                break;
            }

        }
    }

    private void printRows() {
        for (int i = 0; i < rows.size(); i++) {
            System.out.println(rows.get(i));
        }
    }

    // this methods put a max number of obj in the first row and the one les in the next...
    private void populateRows() {
        for (int i = 0; i < defaultValueForRows; i++) {
            Rows r = new Rows();
            r.setNumberOfObjects(maxNumberOfObjectsInRow - i);
            rows.add(r);
        }
    }

    private boolean gameover() {
        /*for (int i = 0; i < rows.size(); i++)
        {
            if (rows.get(i).getNumberOfObjects() > 0)
            {
                return false;
            }
        }
        return true;*/

        for (Rows row: rows) {
            if (row.getNumberOfObjects() > 0) {
                return false;
            }
        }
        return true;
    }

    private void takeTurn(Player player) {
        System.out.println(player + ": Which row do you want to take obejcts from?");
        int rowNumber = Integer.parseInt(scanner.nextLine());

        Rows row = rows.get(rowNumber - 1);

        System.out.println(player + ": How many object do you want to remove?");
        int numberOfObjects = Integer.parseInt(scanner.nextLine());

        if (player.removeObjects(row, numberOfObjects) == false) {
            takeTurn(player);
        }

    }

}

Rows.java
package com.company;

/**
 * Created by SimonBlixenkrone on 21/10/2015.
 */
public class Rows {
    private int numberOfObjects = 20;
    public int numberInRows = 0;

    public int getNumberOfObjects() {
        return numberOfObjects;
    }

    public void setNumberOfObjects(int numberOfObjects) {
        this.numberOfObjects = numberOfObjects;
    }

    public boolean removeObjects(int numberOfObjects) {
        if (this.numberOfObjects >= numberOfObjects) {
            this.numberOfObjects -= numberOfObjects;
            return true;
        } else return false;
    }

    @Override
    public String toString() {
        String s = "";
        //        for (int i = 0; i < numberOfObjects; i++) {
        for (int i = 0; i < numberOfObjects; i++) {
            //s = s + "|";
            s = s + numberInRows+++" ";
        }
        return s;
    }
}

Player.java
package com.company;

import java.util.Scanner;

/**
 * Created by SimonBlixenkrone on 21/10/2015.
 */
public class Player {
    private String name;
    //private Scanner scanner = new Scanner(System.in);

    public void enterName(Scanner scanner) {
        setName(scanner.nextLine());
    }

    @Override
    public String toString() {
        return getName();
    }

    public boolean removeObjects(Rows rows, int numberOfObjects) {
        if (rows.removeObjects(numberOfObjects)) {
            System.out.println(getName() + " removed " + numberOfObjects + " objects");
            return true;
        } else {
            System.out.println("Not possible! try again");
            return false;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

A: I'm pretty sure we take the same class. Cause that's my assignment as well.
Excuse my still-poor practice and feel free to relegate methods to their relevant classes. Maybe that'll give you some idea of where I am headed. Still WIP though.
public class NimGame {

//instantiate scanner object
Scanner scanner = new Scanner(System.in);

private ArrayList<Integer> numbersArray = new ArrayList<>();
private ArrayList<Player> players = new ArrayList<Player>();

public void startGame() {

    fillArrayList(20);
    printArrayListAsCircle();
    //add players
    for (int i = 0; i < 2; i++) {
        System.out.println("Enter name of Player " + (1 + i) + ": ");
        Player player = new Player();
        player.setName(scanner.nextLine());
        players.add(player);
    }

    //run!!!
    while (true) {
        takeTurn(players.get(0));
        if (gameOver() == true) {
            System.out.println(players.get(0) + " lost the game");
            break;
        }
        printArrayListAsCircle();

        takeTurn(players.get(1));
        if (gameOver() == true) {
            System.out.println(players.get(0) + " lost the game");
            break;
        }
        printArrayListAsCircle();

    }
}

private void fillArrayList(int i) {
    //populate arrayList
    for (int j = 1; j <= i; j++) {
        numbersArray.add(j);
    }
}

//worked on this forever, trying (and failing) to implement foreach-loops, while-loops, simple for-loops.
//the result is... not pretty but performs well enough!
//most problems arose with printing the middle part and I must've tried 30 versions until this one worked.
//first I introduce two variables, one 'end'-point and one 'pivot'-point at which to 'wrap' the arraylist around.
//the ascending row is straightforward. run print() on all indices up to but not including the halfwayNumber.
//middle row: i honestly struggle to understand how I arrived there. So much debugging last night I lost it. It works though...
//descending row: analogue to ascending row, run print() on all indices DOWN to the halfwayNumber
public void printArrayListAsCircle() {
    int size = numbersArray.size();
    int halfwayNumber = size / 2;

    int i = 0;
    // Ascending row
    while (i < halfwayNumber-1) {
        print(numbersArray.get(i));
        i++;
    }

    // Middle row
    System.out.println();
    print(numbersArray.get(numbersArray.size()-1));
    for (int j = -1; j < halfwayNumber*2; j++) {
        System.out.print(" ");
    }
    print(numbersArray.get(halfwayNumber-1));
    i = size-2;
    System.out.println();

    // Descending row
    while (i >= halfwayNumber ) {
        print(numbersArray.get(i));
        i--;
    }
    System.out.println();
}

//my print() method. contains some formatting to make the top and bottom row align nicely. at least at the first iteration.
private void print(Integer i) {
    if (i < 10) {
        System.out.print(" " + i + " ");
    } else {
        System.out.print(i + " ");
    }
}

//my new gameOver() method. short and sweet
private boolean gameOver() {
    return numbersArray.size() == 0;
}

//takeTurn() method, changed things around a bit
private void takeTurn(Player player) {
    System.out.println(player + ": please enter a start number");
    int startNumber = Integer.parseInt(scanner.nextLine());
    System.out.println(player + ": please enter an end number");
    int endNumber = Integer.parseInt(scanner.nextLine());
    removeNumbers(startNumber, endNumber);

}

//this took a while and some trial and error, but in the end I came up with an algorithm that works:
//for-loop cycles through the arraylist 'size' times (-> this how often it cycles is dependent on the flexible size of the arraylist)...
// ...and for each iteration increments i to arrive at the next index UNLESS...
//...it finds an index where both if-conditions are found to be true. then i is removed.
//To ensure that ALL numbers in between startNum and endNum are removed as well i is then decremented...
//... because of the arraylist shrinking and assigning new indices to the elements 'shuffled to the left'.
private void removeNumbers(int startNumber, int endNumber) {
    for (int i = 0; i < numbersArray.size(); i++) {
        if (numbersArray.get(i) >= startNumber && numbersArray.get(i) <= endNumber) {
            numbersArray.remove(i);
            i--;
        }
    }
}
}


text:
Q: jquery if has been clicked This I'm sure has a really easy answer:
I have a search form that when you focus on the form additional buttons pop under the form to allow you to filter choices, I'm trying to make it so on blur on the search form those options go away. Currently when you click on one of those options it closes the option menu, so I'm looking for a way to test if those options were clicked. Here is the code I've come up with so far:
    $("#search").blur(function(){
       $("#selector").click(function(){
           return false;
       });
       $("#selector").toggle();
    });

Also attempting to do something like the following yielded failing results:
    var is_clicked = true;
    $("#selector").click(function(){
        is_clicked = false;
    });
    console.log ( is_clicked ); // always returns true

A: See this : http://jsfiddle.net/gP8Jg/1/
 $("#search").blur(function(){
   $("#selector").mousedown(function(){
       return false;
   });
   $("#selector").toggle();
});
 $("#search").focus(function(){
   $("#selector").fadeIn();
});

Try to using mousedown() instead of click()

A: This always returns true because the console.log is executed synchronously:
var is_clicked = true;
$("#selector").click(function(){
    is_clicked = false;
    // console.log( is_clicked ); // will yeild false
});
console.log ( is_clicked ); // always returns true

I don't quite understand what you have done here:
$("#search").blur(function(){
   $("#selector").click(function(){
       return false; // Cancels the click
   });
   $("#selector").toggle(); // Slides vissible/hidden $('selector')
   // There is no code here that checks state of buttons or any other element
   // on the page.
});

Toggling an element upon click is done in it's own click handler:
$('#selector').click(function (event) {
    $('#selector').toggle();
});

A: if you need to close the option menu after click on an option, toggle it with a delay, eg. use js setTimeout() and catch the click on the option element itself


text:
Q: How to Create a Listener for WCF ServiceHost events when service is hosted under IIS? I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but they are application wide resources which will only free up when the service itself or IIS shuts down.
I saw another post where someone mentioned that he has created a listener to capture the events of ServiceHost.  Can someone help me with figuring out how to get a handle of the ServiceHost and capture the IIS reset or IIS shutdown event and free up my resources in WCF service?

A: You can use the IDisposable pattern with finalizer on the class that holds the resources.
On unload of AppDomain, all objects are finalized and if the object that has reference to the resources (such connections) has a finalizer, the finalizer will be called and you can close / dispose the resources at that point.

A: Well, I'm out of ideas, but I think that this article contains your answer in the chapter: "Accessing ServiceHost in IIS". It seems you need to build your own HostFactory because out of the box IIS uses the standard HostFactory and practically controls the creation and destruction of Hosts. By providing your own HostFactory you can add your own code to control the initialization and destruction...

A: The whole point of WCF services and IIS hosting is to achieve scalability and allow easy hosting. Although you could connect to events exposed by the ServiceHostBase class (see here), I would recommend against it and analyzing if you really need those shared resources. The main reasons for asking you to re-think are: shared resources need to be thread safe (IIS can serve many requests simultaneously), so this creates a bottleneck for the scalability of your application and secondly, it's best if your services are stateless, and this includes (I guess) the usage of share resources (or application wide resources).


text:
Q: PHP CLI script errors after git commit I have a CLI script with the ff. on top:
#!/usr/bin/env php
<?php
// ...

The script works however after I git commit, running the same script again returns the ff. error:

/usr/bin/env: 'php\r': No such file or directory

The script is fixed by doing the suggestion here.
My question is how do I prevent this issue from happening in the first place?

A: Probably there's a git config that is changing EOL format to CRLF instead of keeping LF. It's a whole topic. Long-story short, if you want git to not mess with EOL format of files, set this on .gitattributes:
* -text

With that you are telling git not to mess up with the EOL format of any file in the project. Add the file to the project so that it can be shared by all developers. Finally, if the commit that is messing up with the file is the last one, amend it (after adjusting the file to have unix EOL and have the attribute set on .gitattributes):
dos2unix the-script.php
git add the-script.php
git commit --amend --no-edit


text:
Q: How to get the indexes of xgb.DMatrix to add information for feval function? I need to optimize xgboost parameters on a customized evaluation function.
But to do so, I need to join some other information about the selected observations to measure performance.
The best way for me would be to add the information directly to the xgb.DMatrix something like :
dtrain <- xgb.DMatrix(data = matrix, label = OBSERVATIONS$actual, ID = OBSERVATIONS$ID)

This way I would be able to retrieve what observations is being evaluated and join some additionnal information to evaluate.
Something like :
feval = function(preds, dtrain){
# getting labels
actual <- getinfo(dtrain, "label")
# Retrieving additionnal information
ID <- getinfo(dtrain, "ID")
dt <- data.table(ID = ID, actual = actual, preds = preds)
# Note that it would work also work if there is a way to know what
# is the index of the observations in dtrain

# Joining additional information
dt = scalingFact[dt, on = c("ID")]

Anyone knows if there is a way I can add the information either by index or with additionnal information I could had to the matrix?

A: I don't think there's a easy way of defining a
Maybe try setting attributes of dtrain, setting ID to be one of the attributes. I don't think it classes with other uses:
library(xgboost)
library(data.table)

# use iris
# fictitious id
iris$ID = 1:nrow(iris)
dtrain <- xgb.DMatrix(data=as.matrix(iris[,-5]),
label = as.numeric(iris[,5])-1)
# set attributes
attr(dtrain,'ID') <- iris$ID

mdl <- xgboost(dtrain,nrounds=3,objective="multi:softmax",num_class=3)
preds = predict(mdl,newdata=dtrain)

feval = function(preds, dtrain){
# getting labels
actual <- getinfo(dtrain, "label")
# Retrieving additionnal information
ID <- attr(dtrain,"ID")
dt <- data.table(ID = ID, actual = actual, preds = preds)
dt
}
feval(preds,dtrain)


text:
Q: apache loads externally but not locally I just recently upgraded my internet and Comcast sent me a new router/modem in one; the ARRIS TG1682G.  I thought I was having all sorts of issues port forwarding with this router until I took a minute to try from my phone and found out it was forwarding the ports.  But on my local machine when ever I try to load my IP or domain I have set up for my IP, I get an error as if the page does not exist.
I have flushed my DNS, cleared all my cache, tried multiple browsers, checked my host file, and ran ccleaner.  Yet I am still unable to locally navigate to my IP.  I can get to my domain using a proxy, but as you can imagine this is not ideal.
My domain is set up at http://its.dirtrif.com (please verify that works for you in your response)
Additional Requested Information
I have XAMPP set up on my local machine and I can navigate to it using localhost or my local ip (10.0.0.92).  I have port forwarded port 80 on my modem and set up a sub domain that points to my public IP (noted above), and even though I can get to the domain on my mobile device (not on my local network) I can not load the domain on my local machine, or any other machine connected to the network (wifi / ethernet).
I've never used wireshark before but I filtered the port and  navigated to my ip in the browser this is the results in wireshark after navigating to my IP once http://i.imgur.com/lwvY2rJ.png http://i.imgur.com/rVT1O9f.png (sorry for it being screenshot I couldn't figure out how to get the text for every one) and honestly I have no idea how to interoperate any of that this is what I see in my browser http://i.imgur.com/n2kOGRW.png and through a proxy it works http://i.imgur.com/SbKhhcY.png
UPDATE
I have posted this issue on another forum and a response I got was "the issue might be that the router does not support NAT loopback"  I am looking into this now.
How can I get my IP (domain) to work locally, when it is working externally?

A: The modem/router in question does not support NAT loopback.  A way to get around this would be to point the device IP to the domain via the host file although this is not ideal.
Example:
 10.0.0.92 its.dirtrif.com

Better off purchasing my own router/modem and get rid of the Comcast provided one, plus save 10$ on my bill every month.
After reading a bit about them the ARRIS SURFboard SBG6900-AC seems to be a solid choise.


text:
Q: Wrapping javascript concatenated html correctly with ",' and \ I'm having a bit of trouble correctly displaying a message in a webpage I am trying to create. The code I have is:
content.innerHTML += "<button 'onclick=\"likeFunction(" + feed.messages[y]._id + ")\">" + "Like(" + feed.messages[y].likesCount + ")" + "</button>"

When I inspect the element on the page source, I get this output:
<button 'onclick="like(idOfObject)">Likes(likeNumber)</button>

What I need it to look like is:
<button 'onclick="like("idOfObject")">Likes(likeNumber)</button>

I'm a bit confused on how I would add more single or double quotes and where to escape them correctly to get this desired output.

A: I think I see a few typos. Most noticeably with the leading ' in front of onclick. I don't think this needs to be here.
As for formatting the string, consider looking into template literals introduced in ES6.
Might look something like this:
content.innerHTML += `<button onclick="likeFunction(${idOfObjectVariable})">Likes (${likeCountVariable})</button>`

Hope this helps

A: I would have guessed what you wanted in your HTML would be:
<button onclick="like('idOfObject')">7</button>

or
<button onclick='like("idOfObject")'>7</button>

You probably do not want to quote the entire on-click attribute, just the part on the right hand side of the = .
content.innerHTML += "<button onclick=\"like('" + feed.messages[y]._id + "')\">" + ...

I'm guessing you also probably don't want something that gets displayed to the user that looks like a function all, but the result of the function call, but that is not what you were asking about.

A: You're so close! First, you need to remove the ' before onclick. If you want to add double quotes around the idOfObject, then you just need escape one double quote after likeFunction( and one double quote before )\">".
"<button onclick=\"likeFunction(\"" + feed.messages[y]._id + "\")\">"

The only problem is that when the double quotes around your variable idOfObject render, they'll correspond to the opening and closing quotes you already have for onclick. So, your solution should have single quotes inside of double quotes:
"<button onclick=\"likeFunction(\'" + feed.messages[y]._id + "\')\">"

A: You SHOULD NOT concatenate html manually from untrusted input (suppose someone injected malicious html code to your feed.messages[y]._id or another field). Sanitization is one of your options but it's like patching a huge hole.
You can read more about preventing those security attacks named XSS here.
Consider creating your DOM manualy with createElement API and bind your event handlers manually.
function renderButton(content, feed, y) {
    function likeFunction() {
      alert("LIKE" + feed.messages[y]._id);
    };

    var button = document.createElement("button");
    var text = document.createTextNode("Like(" + feed.messages[y].likesCount + ")");
    button.appendChild(text);
    button.addEventListener('click', likeFunction)
    content.appendChild(button);
}

Then you can just render your button with a simple function call.
renderButton(content, feed, 0)


text:
Q: laravel session authentication in middleware I have stored some value in session and checked in it middleware for authentication .my session timeout is SESSION_LIFETIME=120 .when its page is ideal for 30 minutes and does some action on it middleware validate it's true and go forward but due to code it give some error in function but again I refresh the code it redirect to login page
laravel version 6
handle method
    {
        $this->authuser   = getLogedinUser();

  if(Arr::has($this->authuser,['id','name','email',token]) && Arr::get($this->authuser,'token',0))
        {
            return $next($request);
        }
        return redirect('/login');
    }```

A: Try This
  public function handle($request, Closure $next)
    {
        if(!$this->session->has('lastActivityTime'))
            $this->session->put('lastActivityTime',time());
        elseif(time() - $this->session->get('lastActivityTime') > $this->getTimeOut()){
            $this->session->forget('lastActivityTime');
            Auth::logout();
            return redirect('auth/login')->withErrors(['You had not activity in 30 minutes']);
        }
        $this->session->put('lastActivityTime',time());
        return $next($request);
    }


text:
Q: JavaScript parser in JavaScript I need to add some lightweight syntactic sugar to JavaScript source code, and process it using a JavaScript-based build system. Are there any open source JavaScript parsers written in JavaScript? And are they reasonably fast when run on top of V8 or a similar high-performance JavaScript implementation?
Thank you for any pointers you can provide!

A: It's not a JavaScript parser itself, but there's a project called Jison (like Bison) for generating parsers that's written in JS.

A: The only metacircular interpreter that I have seen implemented in JavaScript is the Narcissus Engine.
It was developed also by Brendan Eich, they used a lot of non-standard extensions that are specific to SpiderMonkey, I think it will not work on V8.

A: Microsoft has developed the TypeScript compiler in TypeScript. Since TypeScript is a strict superset of JavaScript, and TypeScript compiles to JavaScript, the resulting compiler is technically a JavaScript compiler written in JavaScript.
That of course depends upon your definition of "compiler". But if a compiler accepting a superset of language A is not a language A compiler, that excludes GCC, Clang and pretty much every other compiler.

A: UglifyJS (JS compressor/beautifier in JavaScript) contains a complete JavaScript parser that exposes a simple API.  It's heavily tested and used in some big projects (WebKit).

A: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API:

Recent builds of the standalone SpiderMonkey shell include a
  reflection of the SpiderMonkey parser, made available as a JavaScript
  API.

Note that this is only an API in JavaScript, the parser is C++.

A: The fastest Javascript parser in Javascript was esprima.
It also gives you

Sensible format for the abstract syntax tree (AST), compatible with Mozilla Parser API

A: Crescent Fresh answered this question in the comments:

JSLint contains a JavaScript parser written in JavaScript. See JSlint by Douglas Crockford Around line 2712 begins the parser. JSLint is written to also handle html so you'd have to gloss over those parts

A: acorn is a really fast JavaScript parser written in JavaScript. It's even faster than esprima now. The results I got in Chrome form esprima's speed comparison page:
Source            Esprima    UglifyJS2    Traceur    Acorn
Underscore 1.4.1  15.1       23.8         14.2       7.6
Backbone 1.0.0    17.1       30.2         16.7       7.9
jQuery 1.9.1      241.1      247.2        125.4      81.4
Total             273.3 ms   301.2 ms     156.3 ms   96.9 ms

It's compatible with Mozilla's Parser API, so you can use escodegen to generate JavaScript from the parse trees.

A: JS/CC - The LALR(1) parser and lexical analyzer generator for JavaScript, written in JavaScript - http://jscc.phorward-software.com/