text:
Q: stuck with checking a winning condition and defining a function to move in python game I'm working on a Tic Tac Toe game with a custom grid size and a custom length of the winning line (from input).
The winning conditions that I have, check if there are N-times of the same player's letter horizontally, vertically or diagonally but they don't see if the moves are next to each other (so if they make a line). They only check if there's particular amount of same letter throughout the length of the grid.
I'd appreciate any tips on this.
#find the winner based on row, colum or diagonal downward/upward
def winnerFind(board, player, winLineLength):

    tempVar=[]
    for g in range(len(board)):
        if listSum(board[g]) == winLineLength or listSum(board[g]) == -winLineLength:
            print(player, "wins!")
            exit()

    for t in range(len(board)):
        for u in range(len(board)):
            tempVar.append(board[u][t])
        if listSum(tempVar)== winLineLength or listSum(tempVar)== -winLineLength:
            print(player, "wins!")
            exit()
        else:
            tempVar=[]
    tempVar=[]

    for a in range(len(board)):
        tempVar.append(board[a][a])
    if listSum(tempVar)== winLineLength or listSum(tempVar)== -winLineLength:
        print(player, "wins!")
        exit()

    tempVar=[]
    for s in range(len(board)):
        tempVar.append(board[-s-1][s])
    if listSum(tempVar)== winLineLength or listSum(tempVar)== -winLineLength:
        print(player, "wins!")
        exit()


text:
Q: Replace multiple strings of text in a large dataframe in r I have been trying to use gsub to replace identifier keys with simple integers in an edgelist.  The edgelist is comprised of individuals and a list of their connections (variable length by individual). Unfortunately, since my dataset is over 300K rows (thereby requiring 300K+ search and replace operations), running it iteratively will take almost a week to run through.  The currently code is able to produce the desired output, but I'm attempting to find a more efficient method.  Does anyone know a better method for producing a similar output?  My current code, some hypothetical sample data, and the sample output are below:
Sample Data:
Person  Connection_list
ENJAK   IDFJA, FDAKD, AODMK
JBJDF   KJDFA
LAFMD   JBJDF, KAOJD, ENJAK,FKJSE,IDFJA, AKSKE, FNAFJ, KJDFA, ATNFN, ADOFA, ODIJA, AODMK, NAGJA, NFAKD, FDAKD, KDSFN
ADOFA   JDFKA, KAOJD, NAGJA
KJDFA   ENJAK, ATNFN, NFAKD, ADOFA, AODMK, JDFKA, LAFMD, ODIJA, FNAFJ, KDSFN, JBJDF, FJKAS, FKJSE, AKSKE, NAGJA
IDFJA   AKSKE, KJDFA, FJKAS, ADOFA
KDSFN   KAOJD, ADOFA, AKSKE, FDAKD, NFAKD, FKJSE, NAGJA, JDFKA, ODIJA, FJKAS, ATNFN, JBJDF, FNAFJ, KJDFA, LAFMD, ENJAK
AKSKE   ADOFA, ODIJA, KAOJD, JBJDF, ENJAK, AODMK, FDAKD, IDFJA, NAGJA, KJDFA
NAGJA   KAOJD, AKSKE
ODIJA   ADOFA, FDAKD, FKJSE, ATNFN, IDFJA, NAGJA, KAOJD
FKJSE   JBJDF, NAGJA, KDSFN, KAOJD, LAFMD, KJDFA, NFAKD, FDAKD, ENJAK, ATNFN, FNAFJ, ODIJA, ADOFA, AODMK, FJKAS, AKSKE, IDFJA
FDAKD   ADOFA, ODIJA, FKJSE, NAGJA, NFAKD, KJDFA, JBJDF, ATNFN, AODMK, AKSKE, KDSFN, JDFKA, LAFMD
NFAKD   ADOFA, KJDFA, AKSKE, KDSFN, FJKAS, JBJDF, JDFKA
FJKAS   FKJSE, AKSKE, FDAKD, NAGJA, ADOFA, ENJAK, FNAFJ, KDSFN, NFAKD, ATNFN, AODMK, KAOJD, JBJDF, JDFKA, LAFMD, IDFJA
JDFKA   AKSKE, KJDFA, IDFJA
ATNFN   AODMK, IDFJA, AKSKE
KAOJD   ENJAK, FJKAS, FKJSE, AKSKE, NFAKD, LAFMD, JDFKA, KDSFN, ODIJA
AODMK   AKSKE, FNAFJ, KAOJD, JDFKA, LAFMD, FDAKD, KDSFN, ENJAK, FJKAS, JBJDF, FKJSE, IDFJA, ATNFN
FNAFJ   JBJDF, ADOFA, NFAKD, ODIJA, KAOJD, FKJSE, LAFMD, AKSKE, KDSFN, IDFJA, FNAFJ, ENJAK

Current Code:
for (i in 1:dim(data)[1]){
  data$key[i] <- i
  data[,2] <- gsub(data[i,1],as.character(i),data[,2])
}

Desired/current output:
key  Person Connection_list
1   ENJAK   6,12,1,18
2   JBJDF   5
3   LAFMD   2,17,3,1,11,6,8,19,5,16,4,10,18,9,13,12,7
4   ADOFA   15,17,9,4
5   KJDFA   1,5,16,13,4,18,15,3,10,19,7,2,14,11,8,9
6   IDFJA   8,5,14,4,6
7   KDSFN   17,4,8,12,13,11,9,15,7,10,14,16,2,19,5,3,1
8   AKSKE   4,10,17,2,1,18,12,6,9,5
9   NAGJA   17,8
10  ODIJA   4,12,11,16,6,9,17
11  FKJSE   2,9,7,17,3,5,13,12,11,1,16,19,10,4,18,14,8,6
12  FDAKD   4,10,11,9,12,13,5,2,16,18,8,7,15,3
13  NFAKD   4,5,8,7,14,2,15
14  FJKAS   11,8,14,12,9,4,1,19,7,13,16,18,17,2,15,3,6
15  JDFKA   8,5,15,6
16  ATNFN   16,18,6,8
17  KAOJD   1,14,11,8,13,3,15,7,10
18  AODMK   8,19,17,15,3,12,7,1,14,2,11,6,16,18
19  FNAFJ   2,4,13,10,17,11,3,8,7,6,19,1

A: Not explicit code to solve your problem, but the strategy I would use.
If I read this correctly, Person is a unique identifier and Connection_list are your edges between people. Explicit conversion to integer is really not necessary if your values are factors and if you need numeric values for calculations further in your analysis stream, you can use the factor integer values.
First, I would convert Connection_list to multiple columns, discussed here for example: Split column into multiple columns R.
Then, after that is done and your columns are recognized as containing factor values,
aframe2 <- as.data.frame(lapply(aframe1, factor))

You should be able to retrieve the numeric values from those factors using something along the lines of as.numeric(as.character(f)).

A: I ended up solving the problem in a round-about way.  Because each user had varying lengths of friends, I used the dplyr package to split up each row and apply a split function (using the stringr package) to each row: making a 'long' edgelist, and then I recombined the result back to the original format after converting the list to their factor equivalents.  The code for the recombine is quite messy, and I'm sure there may be a more efficient way to do it, but the code looks something like this:
library(dplyr)
library(stringr)
# User defined split fuction
longedge <- function(df){
  user <- df$user_id
  cnx <- df$friends
  split <- as.data.frame(ifelse(cnx=="",NA,str_split(cnx,", ")))
  combine <- as.data.frame(cbind(user,split),stringAsFactors=FALSE)
  colnames(combine) <- c("user_id", "friend")
  return(combine)
}
# Creating long edgelist
edgelist <- edgelist %>%
  rowwise() %>%
  do(longedge(.)) %>%
  rbind()
# Convert to number
edgelist$friend <- as.numeric(as.factor(edgelist$friend))

# Create count of No. of connections
edgelist1 <- edgelist %>%
  group_by(user_id) %>%
  summarize(friend_count=n())

# Recreate 'wide' connection list
friend_list <- rep(NA,dim(edgelist1)[1])
for (i in 1:dim(edgelist1)[1]){
  if(i==1){j<-1}
  x <- j + edgelist1$friend_count[i]
  friend_list[i] <- as.character(edgelist$friend[j])
  j <- j+1
  while(j < x ){
    friend_list[i] <- paste(friend_list[i],edgelist$friend[j],sep=", ")
    j <- j+1
  }
}

# Recombine
edgelist1 <- cbind(edgelist1,friend_list)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kendo Directive to Center Grid Column Header and Text I'm trying to create an Angular directive to center the column header and cell text for a particular <kendo-grid-column>, instead of using inline CSS.
Based on this post on the telerik forums, I've got the text centering:
https://www.telerik.com/forums/alignment-of-kendo-grid-column-data
Unfortunately, it doesn't work on the header.
Here's the grid definition (ignore the kendo-column-date-format, that's a separate custom directive):
    <kendo-grid [data]="feedbackGridItems" [selectable]="true">
        <kendo-grid-column field="id" title="ID"></kendo-grid-column>
        <kendo-grid-column field="dateModified" title="Date Modified" kendo-column-text-center kendo-column-date-format="d MMM yyyy"></kendo-grid-column>
    </kendo-grid>

And, here's the directive:
import { Directive, OnInit, Input } from '@angular/core';
import { ColumnComponent } from '@progress/kendo-angular-grid';

@Directive({
  selector: '[kendo-column-text-center]'
})
export class ColumnTextCenterDirective implements OnInit {

  constructor(private element: ColumnComponent) { }

  ngOnInit() {

    // This doesn't check for JSON formatted classes, but this project won't
    // use those
    if (Array.isArray(this.element.cssClass)) {
      this.element.cssClass.push("!k-text-center");
    } else if (this.element.cssClass instanceof Set) {
      this.element.cssClass.add("!k-text-center");
    } else {
      this.element.cssClass = "!k-text-center";
    }

    // This doesn't work
    if (Array.isArray(this.element.headerClass)) {
      this.element.headerClass.push("!k-text-center");
    } else if (this.element.headerClass instanceof Set) {
      this.element.headerClass.add("!k-text-center");
    } else {
      this.element.headerClass = "!k-text-center";
    }

  }
}

Anyone see anything obvious why my column header won't center?


text:
Q: xUnit test Uwp project get 'Unsupported MRT profile type' exception I am trying to test a UWP project with xUnit.
On create instance of Windows.ApplicationModel.Resources.ResourceLoader(), I get exception:
Unsupported MRT profile type. (Exception from HRESULT: 0x80073B20)
Example method to test:
public int Sum(int a, int b)
{
    var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
    return a + b;
}

With MsTest test is passed.


text:
Q: Unable to get FTP server directory listing from android ftp4j client Running following code on emulator. Connecting to filezilla server on windows development host using ip address  10.0.2.2.
FTPClient ftp = new FTPClient();
try
{
    ftp.connect("10.0.2.2", 21);
    ftp.login(username, password);
    String REMOTE_DEFAULT_INITIAL_DIRECTORY = ftp.currentDirectory();
    File mDirectory = new File(REMOTE_DEFAULT_INITIAL_DIRECTORY);
    File[] listing = mDirectory.listFiles();
}
catch (Exception e)
{
    e.printStackTrace();
}

Problem: The File[] contains listing of files on android client instead of server.
Thanks
Imdad

A: I use the same library for my Android project and to get the listing I use the following:
FTPClient ftpClient = new FTPClient();
ftpClient.connect(serverName);
ftpClient.login(username, password);
ftpClient.setPassive(true);
ftpClient.setType(FTPClient.TYPE_BINARY);
final FTPFile[] remoteFiles = ftpClient.list();

A: Android Emulator dosen't support FTP connection...
Because, Emulator is fixed port to 5554 ~ 5555?
FTP prot is 21..
So, you just run on real device.


text:
Q: Oracle SQL: Extract Date & Time from Timestamp Timezone I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT. I'm trying to insert those values into another table but i'm getting a date format not recognized error. How do I fix this?
Sample SQL statement
INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT
    TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'),
    TO_DATE(TO_TIMESTAMP(START_DATE, 'YYYY-MM-DD HH:MI:SS AM TZD'), 'YYYY-MM-DD HH:MI:SS AM')
FROM TABLE_DATE

Sample Data
2016-01-21 09:31:49 AM GMT
2016-02-22 06:37:32 PM GMT
2016-02-23 07:10:52 PM GMT
2016-03-15 08:54:40 PM GMT
2016-03-16 12:10:52 AM GMT

If it helps, these are the datatypes of the two columns in TABLE2

DATE_WITH_TIMEZONE TIMESTAMP WITH TIME ZONE
DATE_WITHOUT_TIMEZONE DATE

A:
I have a START_DATE column in my table with values in the format YYYY-MM-DD HH:MM:SS AM/PM GMT

Assuming that your START_DATE column is of the DATE data type then your statement is incorrect; a DATE column has no format and it is stored internally as 7-bytes. It is only when it is passed to the user interface you are using to access the database that that UI will format the date (and not the database). SQL/Plus and SQL developer will format the date using the NLS_DATE_FORMAT session parameter (which is set per user session and can be changed) so relying on this format can lead to "interesting" bugs where the code you are using does not change but will start and stop working for different users depending on their session settings.
You can just do:
INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT FROM_TZ( CAST( START_DATE AS TIMESTAMP ), 'GMT' ),
       START_DATE
FROM   TABLE_DATE;

If your START_DATE column is of a string datatype (why would you do this?) then you will need to convert it to the appropriate type:
INSERT INTO TABLE2 (
    DATE_WITH_TIMEZONE,
    DATE_WITHOUT_TIMEZONE
)
SELECT TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ),
       CAST( TO_TIMESTAMP_TZ( START_DATE, 'YYYY-MM-DD HH12:MI:SS AM TZR' ) AS DATE )
FROM   TABLE_DATE;


text:
Q: What are the strongest objections to be made against decoherence as an explanation of "collapse?" When we measure an observable A of a quantum system, we get an eigenvalue of A. Without worrying about connotations of Copenhagen vs. MWI, etc., let's just call this "collapse."
Question: Among people who are not convinced that decoherence gives a complete answer to this problem, what are the strongest objections that have been raised against its acceptance?
A somewhat cryptic take on this seems to be given in this 2013 paper by Bubb, who says on p. 20,

The argument here is not that decoherence provides a dynamical explanation of how an indefinite quantity becomes definite in a measurement process—Bell [3] has aptly criticized this argument as a 'for all practical purposes' (FAPP) solution to the measurement problem.  Rather, the claim is that we can take the decoherence pointer as definite by stipulation , and that decoherence then guarantees the objectivity of the macroworld,  which  resolves  the  measurement  problem  without  resorting  to  Copenhagen or neo-Copenhagen instrumentalism.

The reference is to a 1974 essay by Bell, "On wave-packet reduction in the Coleman-Hepp model," which I guess dates to long before people started talking about decoherence. The Bell paper can be found online (presumably illegally). It talks about a certain toy model, not about decoherence. The point he seems to be making is that it matters that the "collapse" described by this toy model only happens in the limit $t\rightarrow\infty$. If I'm understanding correctly what Bubb is saying, then I guess the idea would be that in decoherence, the off-diagonal elements of the density matrix fall off exponentially, but they never actually hit zero. If Bubb is saying that he considers this to be the strongest objection remaining to decoherence as an explanation of "collapse," then it would seem to me to be an extremely weak objection.
Please limit answers to the specific question asked above. I don't want to open up a can of worms about other questions such as whether some particular interpretation of quantum mechanics can/should/does/doesn't "explain" the Born rule. I'm also not interested in having decoherence explained to me. I think I already understand it at the level of Joos and Zeh, The emergence of classical properties through interaction with the environment, Z Phys B 59 (1985) 223, which should be sufficient for the present discussion. I'm also not interested in hearing people give yes/no answers as to whether decoherence does explain collapse, because obviously that will never lead to a conclusion that everyone accepts. I'm just asking for an outline of what reasons people do offer for objecting to this as a proposed mode of explanation. Also, I'm interested in whether my interpretation of Bubb's remark is correct.

A: The simplest way to phrase the main objection is that decoherence doesn't even try to solve anything beyond "for all practical purposes." It is a way of describing entanglement with the environment that is irreversible "in practice," but what may be impractical today may well be practical tomorrow (or for a more advanced civilization even today). As indicated elsewhere, the evolution is still understood to be unitary in principle.
Roger Penrose (2004), The Road to Reality, pp. 802-803:

...the environmental-decoherence viewpoint ... maintains that state
  vector reduction [the R process] can be understood as coming about
  because the environmental system under consideration becomes
  inextricably entangled with its environment.[...] We think of the
  environment as extremely complicated and essentially 'random' [...]
  Under normal circumstances, one must regard the density matrix as some
  kind of approximation to the whole quantum truth. For there is no
  general principle providing an absolute bar to extracting information
  from the environment.[...] Accordingly, such descriptions are referred
  to as FAPP [For All Practical Purposes]
Maybe a future technology could provide means whereby quantum phase
  relations can be monitored in detail, under circumstances where
  present-day technology would simply 'give up'. It would seem that the
  resort to a density-matrix description is a technology-dependent
  prescription! With better technology, the state-vector description
  could be maintained for longer, and the resort to a density matrix put
  off until things get really hopelessly messy!

Addendum
There are also attempts at demonstrating decoherence that is irreversible in principle. See related question: Can the Montevideo interpretation of quantum mechanics do what it claims?

A: I think most arguments in the literature can be boiled down to the point that decoherence does in no way touch the linearity of the Schrödinger equation, and thus cannot make an "or" from an "and".
This is complicated in the literature by very technical discussions, which I would like to avoid.
Let me explain the basic point in more details. A widely referenced statement of the measurement problem is given in the paper "Three measurement problems" by Tim Maudlin, section 1 (first two pages, whole paper). He considers a spin measurement apparatus, which has the property that if you put in an electron in spin+ eigenstate, a pointer points to the left, and if the electron comes in with a spin- eigenstate, a pointer points to the right. Now it follows simply from the linearity of the Schrödinger evolution that the initial state
$$\rm\frac{1}{\sqrt{2}} \left(\left|up\right>_e + \left|down\right>_e\right) \otimes \left|ready\right>_d $$
evolves to the final state, after measuring,
$$\rm\frac{1}{\sqrt{2}} \left(\left|up\right>_e \otimes \left|LEFT\right>_d + \left|down\right>_e \otimes \left|RIGHT\right>_d\right).   $$
This looks like a pointer pointing to the left and to the right, which cannot be true and is not what we see in labs or around us. We somehow have to make an "or" out of this "and to get the correct facts.
Among people who believe that this is a problem and that decoherence doesn't solve it, the prevailing point of view seems to be the one given in a letter by Adler, which also references other literature. To solve this problem, which is in fact the so-called measurement problem, there are several options now:

*

*change the Schrödinger equation (done in so-called collapse models)

*add additional local beables (in Bell's words)/ things other than the wave function to the theory, as done in de-Broglie-Bohm theory

*postulate that measurements actually don't have unique outcomes and we somehow only perceive single outcomes when we do experiments (the many-worlds-path).

For many practical purposes, the collapse postulate of the Copenhagen interpretation works fine. Now if you look for an explanation of the collapse, one of the three options above would serve as one.
Decoherence can only explain why the collapse works well: Because the wave function parts that are disregarded won't interfere again with the ones we keep, the collapse is fine. So decoherence explains why you can, in many worlds, separate the worlds and say they do not come in contact again. In de-Broglie-Bohm, it explains why you can effectively collapse the wave function after a measurement. But the collapse itself is not explained, there is still the sum in the above formula, still an "and", and how to get a definite result from it can only go along one of the three lines I sketched.

A: Decoherence turns pure states into mixed states that follow classical probabilities. It does not cover the projection itself that turns the mixed states into individual (pure) eigenstates


text:
Q: MaxSteps and Computing time issue for Solving Differential equation in Mathematica When we solve differential equation numerically using NDSolve then sometimes we get error like NDSolve::mxst: Maximum steps reached
According to Mathematica docs the solution is to increase MaxSteps. For example if you used MaxSteps -> 100 and limit of x 0 to 100 but Mathematica calculated up to the x=50 then increasing steps MaxSteps -> 200  will solve your problem.
My problem is what i got from mathematica is -
During evaluation of In[212]:= NDSolve::mxst:
     Maximum number of 10000 steps reached
     at the point x == 2.1685790754404513`*^-14.

So even if i want to got from limit 0 to 2 for x then my steps should be 10^14 times larger. It will take a huge huge computing time. How much it may take for core i3 processor? Is there any other way to compute quickly or solve this problem of maxsteps in any other way?
My ODE:
v[x_] := {v1[x], v2[x]} ;
ini = v[0] == {1, 0};
soln = NDSolve[LogicalExpand[I v'[x] == H.v[x] && ini], {v1, v2}, {x, x1, x2}]

where H is matrix

A: NDSolve uses adaptive methods to obtain a good solution.  It dynamically changes the step size during integration.
I recommend you take a look at the Advanced Numerical Differential Equation Solving tutorial (ODE section), which has a very detailed description of how NDSolve work, what methods are available, and how you can tweak them.
You can start with
NDSolve[..., Method -> {"FixedStep", Method -> "ExplicitEuler"}, StartingStepSize ->  ... ]

to figure out what is going on (this will likely not give you a precise solution though).  There's a good chance that your differential equation is very troublesome to solve, so automatic method selection will not work well.  In this case you'll need to study the methods available, and make a suitable choice yourself.


text: Q: Configuring wireless router to give priority to particular computer I have a DLINK DIR-651 and I'm wondering if it's possible to configure it so that one particular computer gets priority. In other words it gets more bandwidth. What would be the steps to take? I tried adding the computer to DMZ but speeds went way down. I don't care about security (through the router), the computer has it's own security software.


text:
Q: Manage multiple app config files during development I'm building an application that is used by several different customers.  Each customer has a fair amount of custom business logic, which I have cleverly refactored out into an assembly that gets loaded at runtime.  The name of that assembly, along with a number of other customer-specific settings, are stored in the application's configuration file.
Right now, here's what I have to do in order to debug the application for customer foo:

*

*Go to the filesystem in my project directory and delete app.config

*Copy app.config.foo to app.config.foo - Copy.

*Rename app.config.foo - Copy as app.config.

*Tell Windows that yes, I want to change the file's extension.

*Switch back to Visual Studio.

*Open the Settings.settings item in my project.

*Click "Yes" 13 or 14 times as VS asks me if I want to use the new settings that have been changed in app.config.

*Close Settings.settings.

Okay!  Now I'm ready to debug!
It seems to me that the rigamarole of opening Settings.settings is, or ought to be, unnecessary:  I don't need the default values in Settings.cs to be regenerated, because I don't use them.  But it's the only way I know of to make VS aware of the fact that the app.config file has changed, so that the build will copy it to the output directory.
There's got to be an easier way of doing this.  What is it?

A: You can also let Visual Studio automate Robert`s approach by:

*

*Define a Build Configuration for each client

*In the post build event, simply xcopy app.config.xxx to your bin folder. Where XXX is the name of a Build Config accessible in VS. Something like: xcopy app.config.$(ConfigurationName)  $(OutDir)/app.config

VS will drop a distinct build for your clients in separate folders, aolong with the proper config file.
bin/Client1/
bin/Client2/

A: You can refer this post for some good practices : Managing Multiple Configuration File Environments with Pre-Build Events

A: Thinking about the mess of managing multiple configuration files I made this tool: http://envride.codeplex.com/
Its purpose its exactly to make it easier to manage multiple configuration files in an automated way. I would be very pleased if you would take a look at it.

A: A couple of people suggested using multiple VS configurations, which I think would have worked, except that it would require me to rebuild the solution every time I switched between configurations.
What I did instead seemed a little stupid while I was doing it, but I've been using it for nearly a year now and it works extremely smoothly.  In my project directly, I create a separate app.config.XXX file for each customer.  The actual app.config file is used solely to generate Settings.cs - it has all of the correct setting names and their default values.  It doesn't get copied to the build directories, ever.
Then I wrote a little program that lets me select a customer, and that simply goes through the directories for each project and, if I selected customer XXX, copies app.config.XXX to bin\debug\myprogram.exe.config and bin\release\myprogram.exe.config.  As long as this program knows where the root of the solution is (I have to be a little careful whenever I branch the code), it works like a charm.

A: This thread is too old to represent current tools in VS.

*

*You can use an addon that acts similar to web.debug.config but for app.config.

https://marketplace.visualstudio.com/items?itemName=GolanAvraham.ConfigurationTransform

*And for the same app.config transformations without addon.

https://www.linkedin.com/pulse/multi-appconfig-visual-studio-2017-benjamin-davis/

A: You may opt to define multiple Visual Studio solution configurations, one for each customer, and have customised MSBuild targets for your Windows app project.
I have documented the steps of how I handled this here. Multiple app.config files for deploying to different environments

A: After a little digging and work around I got my Test project working with multiple configurations,

*

*In the Configuration Manager, create the configurations you need

*Copy paste your app.config and add the name of the configuration, in my case is AHI, FIV, MGC, so my config files look like: App.AHI.config, App.MGC.config, App.FIV.Config. You can name it how ever you wanted, but keep the same convention

*Add a Post-Build event. In my case it would look like:  xcopy $(ProjectDir)app.$(ConfigurationName).config $(TargetDir)$(TargetName).dll.config /y

here is my post, so you can read it with more details
Running a Test Project with Multiple Configurations


text:
Q: How to change the image icon of line share plugin I have embedded this plugin from line.

This appears the line image icon. I want to change it according to my own custom image saved on my local folder but it didn't take effect since it is a frame.
Does anybody know?

A: If that service does not offer any possibility to change this in either any type of account settings, or via an additional parameter - then you are basically out of luck.
The Same Origin Policy prevents you from interacting with the content of an iframe that was loaded from a different domain via your own scripting, and you can not apply CSS across frame borders either.

You could try an position your own icon on top of the iframe, and use pointer-events: none to let any clicks pass right through it. But depending on the type of service and whether they have any "security" measures implemented, that might get flagged as a "click jacking" attempt - and if not by them, then maybe by certain browsers or extensions. I would not really recommend it. Even if it might work now, that could change at some point.


text:
Q: Android application with different package name but same code did not installing on one device I am working on an android application. Meanwhile i got chance to work on another application similar to first. I have just copy my previous code to new
project.
1) src files
2) res files
3) manifest
4) build.gradle
and then I change packagename from com.abc to com.xyz in
1) build.gradle
2) Manifest
3) src files
Now i have installed first app in my device and try to install second one but it does not work.
Same error also occur when i have installed second app and try to install first one.
Here is the error

Is there any other thing i need to change apart from packagename??

A: There may be different issues, but try this:
go to gradle and change applicationId, another reason could be conflicting of authorithies in apps, refer to these:
Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER
INSTALL_FAILED_CONFLICTING_PROVIDER in Android
http://gradlewhy.ghost.io/overcoming-install-failed-conflicting-provider/

A: I have the same issue in the same case and I solved it by adding applicationId. In my case problem was in permission.MAPS_RECEIVE, I saw that in error logs. So I did next:
AndroidManifest.xml:
<permission
        android:name="${applicationId}.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />


text:
Q: PowerMock raises exception when @PrepareForTest annotation passes argument is child (extended) class I am using PowerMock for test my codes. I examined many test codes but I couldn't find the answer about the problem below. I also tried different version of power mock but did not work.
public class TestParent {

}

public class TestChild extends TestParent {

    public void foo() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.getDayOfYear());
    }

}

When I pass normal class to @PrepareForTest, test is working properly.
@RunWith(PowerMockRunner.class)
@PrepareForTest({TestParent.class})
public class ActionTest {

      @Test
      public void testFunc() {
          System.out.println("test !!!");
      }
  }

But when I pass TestChild it is raising an exception
@RunWith(PowerMockRunner.class)
@PrepareForTest({TestChild.class})
public class ActionTest {

    @Test
    public void testFunc() {
        System.out.println("test !!!");
    }
}

java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=testFunc]
      at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:83)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:74)
      at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:526)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
      at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

This is my pom file
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.4</version>
        <scope>test</scope>
    </dependency>
     <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>


text:
Q: Do weak equivalences in a model category admit a calculus of fractions? Suppose it is given a model category $M$, $W$ being the set of its weak equivalences. One can define the localization of $M$ along $W$, denoted by $W^{-1}M$. In order to work with $W^{-1}M$, it would be of great help if $W$ admitted a calculus of fractions. So, my question is: is that true in general, or perhaps under some appropriate assumptions? I suspect the answer in general is "no", but I really hope it is "yes under appropriate assumptions": I'm currently working on dg-categories and craving for a "simple" description of the category $\mathrm{Ho}(\mathbf{dg\text{-}cat})$ of small dg-categories localized along quasi-equivalences.
Thanks in advance for any answer!

A: At the end I'll give you a reference to a counterexample in the paper of Meier and Ozornova. But before that, I want to talk in the other direction: besides the 3-arrow calculus that Charles Rezk mentions, there's another sense in which $W$ "almost" admits a calulus of fractions. It's a result in the same paper.
Recall the functor $\mathrm{Ex}: \mathsf{sSet} \to \mathsf{sSet}$, which is right adjoint to barycentric subdivision. There is a canonical natural transformation $1 \Rightarrow \mathrm{Ex}$, allowing to define maps $\mathrm{Ex}^n \to \mathrm{Ex}^{n+1}$ for every $n$, and most famously the colimit $\mathrm{Ex}^\infty$ was shown by Kan to be a fibrant replacement functor for the Kan-Quillen model structure on $\mathsf{sSet}$; in particular $\mathrm{Ex}^\infty X$ is a Kan complex for every simplicial set $X$ (I don't know if this extends further -- is $\mathrm{Ex}^\infty f$ a Kan fibration for every simplicial map $f$? Is $\mathrm{Ex}F$ injective-fibrant for every diagram $F$?). But moreover, a functor $F: \mathcal{C} \to \mathcal{D}$ between categories is fibrant in the Thomason model structure on $\mathsf{Cat}$ iff $\mathrm{Ex}^2 F$ is a Kan fibration (where we identify a category with its nerve).
All of this is just to motivate looking at $\mathrm{Ex}^2 \mathcal{C}$ for a category $\mathcal{C}$. Meier and Ozornova show that if $W$ is the category of weak equivalences in a model category (actually, only a substantially weaker structure called a "partial model category" is necessary), then $\mathrm{Ex}^2 W$ is a Kan complex (i.e. $W$ is Thomason-fibrant).
Why am I telling you this? Well, Meier and Ozornova also show something surprisingly (to me) clean:

Theorem: If $\mathcal{C}$ is a category, then $\mathrm{Ex}^1 \mathcal{C}$ is a Kan complex if and only if $\mathcal{C}$ admits a left calculus of fractions.

It follows that $\mathcal{C}$ admits a two-sided calculus of fractions if and only if both $\mathrm{Ex}^1 \mathcal{C}$ and $\mathrm{Ex}^1 \mathcal{C}^\mathrm{op}$ are Kan complexes. Meier and Ozornova also suggest (Question 2 at the end) that there might be notions of ``$n+1$-arrow calculus" giving clean characterizations of $\mathrm{Ex}^n \mathcal{C}$ being a Kan complex -- which in particular would recover the result that the weak equivalences in a model category admit a 3-arrow calculus, since they are Kan after applying $\mathrm{Ex}^2$.
Finally, Meier and Ozornova provide examples answering your actual question in the negative. Finite sets and injections (Example 5.1) form a partial model category whose weak equivalences do not admit a left calculus of fractions. More pertinently (Example 5.3), $\mathsf{Cat}$ with the Thomason model structure is itself a model category which does not admit a calculus of left fractions.
 Note, though, that the weak equivalences in a left (resp. right) proper model category admits a left resp. right) caculus of fractions.

A: I'm writing this answer to consolidate and make precise some of the claims found in the comments to this question and the other MO question that David White linked to.
Short answer: you have to restrict to fibrant (or, dually, cofibrant) objects, and then quotient by the appropriate homotopies before obtaining a calculus of fractions.
Let $M$ be a model category, and $W$ its weak equivalences. Let $M_f$ denote the full subcategory of fibrant objects.
Then $M_f$ is a category of fibrant objects, with fibrations and weak equivalences coming from $M$. In any category of fibrant objects, we can define homotopies between maps$^\dagger$. Let $M_f / \sim $ be the category obtained by quotienting out the homotopies.
Then (the image of) $W$ admits a calculus of fractions (i.e. is a multiplicative system) in $M_f / \sim$, and further $\text{Ho}(M) \cong \text{Ho}(M_f) \cong \text{Ho}(M_f/ \sim)$. This is shown in the ncatlab entry I linked.
In many model categories (including $\textbf{dg-cat}$ and $\textbf{Ch}(R)$ with the projective model structure), all objects are fibrant, so $M_f = M$, and thus $M/\sim$ admits a calculus of fractions. But I have not found a reference that shows that $M/\sim$ always admits a calculus of fractions. If this is in fact true, it would be great if someone could provide a reference!
$^\dagger$ Note that the notion of right homotopy is the same in model categories as well as categories of fibrant objects, but (as far as I can tell) the notion of homotopy does not appear to be the same.


text:
Q: .NET Can't connect to MDF on another machine I have a simple Windows Forms project, which is linked to another project, a class library called "Model". This Model project uses LINQ-to-SQL to connect to a MDF database. When I test it locally, it works just fine, but when I try it on another machine, even though I have the .NET framework installed, it cannot connect, I get a timeout and an error: "Error occurred while establishing a connection to SQL Server"

The connection string I'm using to connect is Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient
I made a dummy repo to share the code, it can be found here: https://github.com/gosukiwi/TestConnect.
Maybe I should use an SQL server or an Access database instead? Cheers.

A: I think you'll find these helpful:
http://blogs.msdn.com/b/sqlexpress/archive/2011/12/09/using-localdb-with-full-iis-part-1-user-profile.aspx
http://blogs.msdn.com/b/sqlexpress/archive/2011/12/09/using-localdb-with-full-iis-part-2-instance-ownership.aspx
I tend to use LocalDB when developing but then shift to our live servers SQL Server instance on production deployment.
What you're trying to do is possible, but requires loading the user profile. I've also seen some suggestions on changing the identityType of the application for a quick fix:  How to deploy ASP.NET MVC 4 application using localDB to local IIS on Windows 7? but i'd suggest doing a good read up.


text:
Q: Android: Skobbler, how to limit map view in an area? I'm new not only on Skobbler but also for Map. At this time, i'm trying to create a mapp app that show only an area.
And, what i want are:

*

*User can't move out of that area.

*Don't load any thing (title, .. )outside that area.

*User can view and zoom in only.

I tried with bound like below but it not work:
SKBoundingBox boundingBox = new SKBoundingBox(47.087426, 8.257230, 46.874277, 8.637632);
mapView.fitBoundingBox(boundingBox, 0, 0);

Could you give some hint, please?

A: Currently the SDK does not support limiting map operations to a bounding box.
As a workaround, whenever the map region that is visible on the screen changes (as a result of panning, zooming or rotation) and it goes outside the defined bounding box the map will switch back to the last visible region that was inside that bounding box:
public class MapActivity extends Activity implements SKMapSurfaceListener, ... {

...
// the box inside which map operations are allowed
private SKBoundingBox box = new SKBoundingBox(47.087426, 8.257230, 46.874277, 8.637632);

// last region that was visible on the screen and was inside the box
private SKCoordinateRegion lastValidRegion = null;

...

@Override
    public void onSurfaceCreated(SKMapViewHolder mapHolder) {
...
// position the map somewhere inside your box
mapView.centerMapOnPosition(new SKCoordinate(8.304354, 47.050253));
}

...

// checks if a given region is inside the bounding box
private boolean isInBoundingBox(SKCoordinateRegion newRegion) {
        SKBoundingBox newBoundingBox = mapView.getBoundingBoxForRegion(newRegion);
        if (newBoundingBox.getTopLeftLatitude() > box.getTopLeftLatitude() || newBoundingBox.getBottomRightLatitude() < box.getBottomRightLatitude() ||
                newBoundingBox.getTopLeftLongitude() < box.getTopLeftLongitude() || newBoundingBox.getBottomRightLongitude() > box.getBottomRightLongitude()) {
            return false;
        }
        return true;
    }

@Override
    public void onMapRegionChanged(SKCoordinateRegion mapRegion) {
        boolean inBoundingBox = isInBoundingBox(mapRegion);
        if (inBoundingBox) {
// if mapRegion is valid save it
            if (lastValidRegion == null) {
                lastValidRegion = new SKCoordinateRegion(mapRegion.getCenter(), mapRegion.getZoomLevel());
            } else {
                lastValidRegion.setCenter(mapRegion.getCenter());
                lastValidRegion.setZoomLevel(mapRegion.getZoomLevel());
            }
        } else {
// if mapRegion is invalid reposition the map inside the bounding box
            if (lastValidRegion != null) {
                mapView.changeMapVisibleRegion(lastValidRegion, false);
            }
        }
    }

}

Also, if needed, limits can also be applied to zoom levels using the SKMapSettings.setZoomLimits(...) method.


text:
Q: How do we achieve Currency Conversion in Hive? I would like to convert the  salary for all employees to  USD
Lets say I have a Hive table 'emp'
id    name        currency_code   salary_as_per_currency_code
100   Surender    EUR             10
101   Raja        INR             100
102   Ajay        USD             5

I need to write a select query that should give me the  below result
My expected output is
id    name        currency_code   salary_as_per_currency_code     salary_in_USD
100   Surender    EUR             10                              $10.92
101   Raja        INR             100                             $1.496
102   Ajay        USD             5                               $5

My table has more Currency_code such as NZD,CAD,JPY and all.
Is there any generic builtin function in hive to do that?
Please help me on giving me a possible route to find a solution for this

A: There is no builtin function available for this conversion, but you can create your own UDF in hive. Refer the below link, which will guide you to create UDFs in hive.
UDF tutorial
all you need to do is to write your conversion logic in the below block,
public class currency_conversion extends  UDF {
public Text evaluate(String currency_code, String salary_as_per_currency_code){
----- write your logic here---
    if (currency_code.contains("INR")){
        --write your conversion logic here---
    }
}}

Let me know if any queries you have.


text:
Q: Swift: Array fine grained observation using didSet If we provide a didSet observer on an Array property in swift class then we will be able to observe changes in the array as a whole How we can do a fine grained observation on array where we be able to track insertions , updations and deletions ? It seems merely using didSet observer alone will not help. Any idea how it can be done ? I came across a link
that seems to explain the thing that I am looking for but it is somewhat complex to understand. Can anybody provide a simple example to solve this problem ?
Thanks

A: If you want to investigate the 'old' value before the property is set (to calculate a diff), you need to use willSet, not didSet. In didSet it is too late to calculate changes (obviously ...)
Sample:
class AWrap {
  var values : [ String ] = [] {
    willSet {
      print("values: \(values)")
      print("   new: \(newValue)")

      let old = Set(values)
      let new = Set(newValue)
      let newElements  = new.subtracting(old)
      let goneElements = old.subtracting(new)
      print("     +: \(newElements)")
      print("     -: \(goneElements)")
    }
  }
}

Running that:
let a = AWrap()
a.values.append("2")
a.values.append("3")
a.values.remove(at:0)

Gives:
values: []
   new: ["2"]
     +: ["2"]
     -: []
values: ["2"]
   new: ["2", "3"]
     +: ["3"]
     -: []
values: ["2", "3"]
   new: ["3"]
     +: []
     -: ["2"]

A: You can generalize the detection in an extension to make it easier to manage if you're going to do this in several  places:
 extension Array where Element:Comparable
 {
    func changesFrom(old:[Element]) -> [(index:Int, mod:String, old:Element, new:Element, desc:String)]
    {
       var changes:[(index:Int, mod:String, old:Element, new:Element, desc:String)]

           changes  =  zip(old,self).enumerate()
                      .filter{ $1.0 != $1.1 }
                      .map{ ($0, "∆", $1.0, $1.1 , "\($1.0) -> \($1.1)") }
           changes +=  (old.count..<max(old.count,self.count))
                      .map{ ($0, "+", self[$0], self[$0], "\(self[$0])") }
           changes +=  (self.count..<max(old.count,self.count))
                      .map{ ($0, "-", old[$0], old[$0], "\(old[$0])" ) }
       return changes
    }

    func printChangesFrom(old:[Element])
    {
       for changed in changesFrom(old)
       {
         print( "[\(changed.index)] \(changed.mod) \(changed.desc)" )
       }
    }
 }

 class ContainsArray
 {
    var array  = [1,2,3,4]
    {
       didSet
       {
         array.printChangesFrom(oldValue)
       }
    }
 }

 var CA = ContainsArray()

 print("change an element")
 CA.array[2] = 7

 //[2] ∆ 3 -> 7

 print("change multiple elements")
 CA.array.sortInPlace(<)

 //[2] ∆ 7 -> 4
 //[3] ∆ 4 -> 7

 print("add elements")
 CA.array += [9,12,14]

 //[4] + 9
 //[5] + 12
 //[6] + 14

 print("remove Elements")
 CA.array.removeLast(3)

 //[4] - 9
 //[5] - 12
 //[6] - 14


text:
Q: Ошибки в функции - Unity Имеется функция:
    public GameObject toObjects(string object) {
    if (object == "sun") return SunObject;
    }

Но юнити выдает 4 ошибки:
Identifier expected - x2
Syntax error, ' , ' expected
Invalid expression term 'object'
Я задал строковый тип, непонятно почему он все равно ругается на тип, и точно так же с остальными ошибками. В чем проблема?

A: *

*Вы выбрали неудачное имя строковому аргументу функции object. Попали в зарезервированное слово. Вот список зарезервированных в сишарп слов.

*У Вас в сигнатуре метода указано что он возвращает GameObject, соответственно все ветви выполнения должны что-то возвращать, нужно добавить хотя бы return null; в конце функции.


text:
Q: Give internal users access to the customer portal by default? By default, the customer portal is accessed via portal user accounts. Salesforce internal users have a separate, non-portal contact for logging into Salesforce via a standard SF splash page.
To configure an internal user as a portal user requires giving that user a separate login with a new username and password. This creates confusion and frustration for these users if they wish to switch between normal day to day work in SF, and visiting the portal or helping a customer.
Community users can easily be added to the default access for standard users, but I have not yet found a way to do this for portal access.
What am I missing?


text:
Q: Error when we use pandas "apply" and "lambda" with Django We need to push a custom code from front end (Django) to back-end (Visual studio code which executes the python code). We are getting the below mentioned error when we use pandas "apply" and "lambda".
e.g
exec('''DFrame=pd.DataFrame({'A':['11','2','3'],'B':['X','Y','Z']})
print(DFrame.head())
def DD(X,Y):
 return X+Y
DFrame['C']=DFrame.apply(lambda x: DD(x['A'], x['B']), axis=1)
print(DFrame.head())''')

Error we are getting:

NameError: name 'DD' is not defined

Can anyone please suggest a workaround for this?

A: Since you are using apply you can use either DD or lambda. For example, only using lambda:
df = pd.DataFrame({'A':['11','2','3'],'B':['1','2','3']})
df['C'] = df.apply(lambda x: x['A'] + x['B'], axis=1)

The output of df would be:
    A  B    C
0  11  1  111
1   2  2   22
2   3  3   33


text:
Q: PM2 How to start nextjs project in prod mode? I want to run a project in pm2.
My folder structure:
screen with my folder structure
My package.json:
"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p 7777",
    "type-check": "tsc",
    "gensitemap": "node generate-sitemap.mjs",
    "prod": "yarn && npm run build && npm run start"
  },

My ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'core',
      script: 'yarn --cwd core prod',
      watch: false,
    },
  ],
};

When, I started pm2 start ecosystem.config.js
I got the following error in the logs
error - Invalid project directory provided, no such directory: D:\React\MyProject\src\core\prod
I tried different ways to run in production mode.
It came out only in dev mode to run


text:
Q: How do you print a hash in Django 1.7 and store it in a database? I created a hash that I am going to use later for confirmation email logic like this:
import hashlib, datetime, random

def hash(request):
    username = 'johndoe' #inserted line to simplify the code
    random_str = str(random.random()).encode('utf-8')
    salt = hashlib.sha1(random_str).hexdigest()[:5]
    salted = (salt + username).encode('utf-8')
    activation_key = hashlib.sha1(salted).hexdigest()
    return render_to_response('ftest/display.html', activation_key)

My first question is how do I print this in the html so that I can see it when the html renders?
This doesn't seem to work in my display.html :
<p> This is the activation key {{activation_key}} </p>

Next, how would I define this hash field in the database? Would it just be a charfield like:
hash = models.CharField(max_length=200)

A: render_to_response expects a dict :
return render_to_response('ftest/display.html', {'activation_key': activation_key})

A CharField is the right way to go.


text:
Q: Cross Platform Coloured text in C I was wondering how you could print coloured text in a cross platform manner in C. I have looked at all the other answers on the forum, but none of them work during my testing (on Windows). For C++, I have the working code in Fig 1, however when converting the code to C and assigning the strings to a variable I get the error \u001b is not a valid universal character (Fig 2).
Fig 1
namespace Fore {
    const std::string BLACK = "\u001b[30m";
    // Rest of code is not included since it is just a repetition of the above code with background and style ANSI codes as well.

Fig 2
Image here since I don't have enough reputation to embed images yet.

A: C and C++ have different rules for "universal character names" (UCNs), which is the official name for \u and \U sequences. (They're not the same as "escape sequences" because UCNs can be used outside quoted literals, for example in identifier names.)
In C, the rule is:

A universal character name shall not designate a code point where the hexadecimal value is:

*

*less than 00A0 other than 0024 ($), 0040 (@), or 0060 (`);

*in the range D800 through DFFF inclusive; or

*greater than 10FFFF82)

So in C, you can't use UCNs for control characters, which is what the error message is telling you.
C++ is more generous; it allows you to use UCNs for control characters and other characters with small codepoints, but only inside string and character literals. (C++ also prohibits surrogate codepoints and excessively large codes, the second and third points in the above list.)
Both C and C++ allow you to use octal escape sequences (\033) or hexadecimal escapes sequences (\x1B). I'd personally recommend the latter, but \033 is common because hexadecimal escapes were not in the very earliest versions of C, and so \033 became a common idiom.
None of this is really platform-independent. Lots of platforms have consoles which don't interpret ANSI style codes.

A: The way \uxxxx sequences are interpreted by the compiler as input source text, before the text is tokenized.  You have included a control character (not a compiler escape sequence) inside a string literal (like you had keyed it literally, in the string).  Just change the control character by an escape sequence, as in:
    const std::string BLACK = "\x1b[30m";

or, more portably (the octal representation is included in the first C compilers, while the \xAB notation was introduced with ANSI-C):
    const std::string BLACK = "\033[30m";

both sequences indicate to the compiler that you want to put the equivalent character in the compiler output, but they are four character sequences, not a single one.  And both work in C/C++.
BTW, a portable way to do coloured output is to use a library like termcap (part of curses) that determines the terminal type from the running environment, and so, selects the appropiate sequence for the used terminal.  Look at the manual pages for termcap (curs_termpcap(3X)) for info about the termcap library.  If you need more advanced functions (like cursor addressing or windows) then the full ncurses library should be the option.  This library was developed when the vi editor was born, in an age in which the amount of terminals of different classes and control languages was in use.


text:
Q: Create unit test for archive function fs I have the following function which is working as expected. Now I want to create unit test for it. The problem is that I'm using the file system and I am not able to figure out how to do it with some mocks or any other solution. Any idea how this can be done simply in Go?
Should I really create a files and check then with unit test? I'm afraid that in some system it will work and some it breaks (winodos/ mac/linux)
This is the working function:
func Zipper(src string,artifact string,target string) error {

    zf, err := os.Create(artifact)
    if err != nil {
        return err
    }
    defer zf.Close()

    ziper := zip.NewWriter(zf)
    defer ziper.Close()

    fileInfo, err := os.Stat(src)
    if err != nil {
        return err
    }

    var bs string
    if fileInfo.IsDir(); len(target) > 0 {
        bs = target
    } else {
        bs = filepath.Base(src)
    }

    if bs != "" {
        bs += "/"
    }

    filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }

        if info.IsDir() {
            return nil
        }

        header, err := zip.FileInfoHeader(info)
        if err != nil {
            return err
        }

        if bs != "" {
            header.Name = filepath.Join(strings.TrimPrefix(path, bs))
        }

        header.Method = zip.Deflate

        writer, err := ziper.CreateHeader(header)
        if err != nil {
            return err
        }

        file, err := os.Open(path)
        if err != nil {
            return err
        }
        defer file.Close()
        _, err = io.Copy(writer, file)
        return err
    })

    return err
}

I read the following but it not much helping in my case
How to mock/abstract filesystem in go?

A: The simplest way to test a function that depends on the filesystem, is to add some set-up and tear-down around each test, which puts the necessary files in place before running the test, then removes them after running the test.
func TestZipper(t *testing.T) {
    // Create temporary files
    defer func() {
        // Clean up temporary files
    }()
    t.Run("group", func(t *testing.T) { // This is necessary so the above defer function doesn't run too soon
        // your actual tests
    })
}

A: I know that "doesn't access the file system" is part of the definition of "unit test" to a lot of people. If your profession is not in finding and defending definitions: Forget that restriction. Filesystem access is fast and fine and the go tooling even treats folders named "testdata" special: Such folders are supposed to contain test data to be used during tests.
Go (and their users) aren't very pedantic in distinguishing "unit" from "integration" tests. Take a look at the stdlib of how to test such stuff. It is more important to write relevant tests than getting childish on fs access. (Note that a file system and a database are technically external systems, but in real life you cannot compile Go code without a file system, so isolating the test from this "external system" is ridiculous.)

A: Well, you might look for a way to manipulate filesystem in a safe way or look for a solution somewhere else. What is the responsibility of this function? Shall it prepare a zip file or write it to filesystem?
I suggest that you should take out file creation out of this function and change the function to:
func Zipper(src string, dst io.Writer, target string) error {
    ziper := zip.NewWriter(dst)
    defer ziper.Close()

This way, for a test purpose you can provide a simple buffer, while in production use your beloved filesystem!


text:
Q: Unable to bind jibx idea tool
Error:Jibx Compiler: Error running binding compiler
  org.jibx.runtime.JiBXException: Binding .DS_Store is unusable because of validation errors
      at org.jibx.binding.Utility.loadBinding(Utility.java:358)
      at org.jibx.binding.Utility.loadFileBinding(Utility.java:420)
      at org.jibx.binding.Compile.compile(Compile.java:217)
      at com.adamweigold.jibx.compiler.JibxBuilder.build(JibxBuilder.java:72)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runModuleLevelBuilders(IncProjectBuilder.java:1230)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuildersForChunk(IncProjectBuilder.java:904)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildTargetsChunk(IncProjectBuilder.java:976)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunkIfAffected(IncProjectBuilder.java:870)
      at org.jetbrains.jps.incremental.IncProjectBuilder.buildChunks(IncProjectBuilder.java:695)
      at org.jetbrains.jps.incremental.IncProjectBuilder.runBuild(IncProjectBuilder.java:386)
      at org.jetbrains.jps.incremental.IncProjectBuilder.build(IncProjectBuilder.java:193)
      at org.jetbrains.jps.cmdline.BuildRunner.runBuild(BuildRunner.java:137)
      at org.jetbrains.jps.cmdline.BuildSession.runBuild(BuildSession.java:294)
      at org.jetbrains.jps.cmdline.BuildSession.run(BuildSession.java:125)
      at org.jetbrains.jps.cmdline.BuildMain$MyMessageHandler$1.run(BuildMain.java:232)
      at org.jetbrains.jps.service.impl.SharedThreadPoolImpl$1.run(SharedThreadPoolImpl.java:44)
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
      at java.util.concurrent.FutureTask.run(FutureTask.java:262)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      at java.lang.Thread.run(Thread.java:745)

A: In the Apple OS X operating system, .DS_Store is a file that stores custom attributes of its containing folder, such as the position of icons or the choice of a background image. It does not any role in building of any project or code. hence it is also usually git-ignored. Since it only stores metaData, hence this problem was solved by deleting all the .DS_Store folder in directory.
.DS_Store files impose additional burden on revision control process: They are frequently changed and therefore appear in commits, unless specifically excluded
.DS_Store files have been known to adversely affect copy operations.
These reasons also may add to execution of XML script


text:
Q: Can a Xamarin / C# / Android app easily talk to a local Oracle Server? Using Visual Studio 2017 / Xamarin with C# in an Android app, can the app easily talk to an Oracle Server running on our local Windows domain? And can this be done with freely available drivers? Or is a 3rd party driver required?
Currently, my company develops Windows apps on Visual Studio 2013. Connecting to Oracle using the Oracle native .NET driver is very easy. But we are looking to develop some apps to run on a handheld barcode scanner running Android. Before we make the investment in VS 2017 and the Android devices, we would like to be sure it is technically feasible.


text:
Q: Why does my instance of Axios not return the response in a caught error? I am currently working on a project to create a client for the Udemy instructor API.
I've written the client in Vue, using Axios as my HTTP client.
I have abstracted the different API requests into functions in an ES6-ified API wrapper library (Udemy.js) to allow them to be easily reused.
Udemy.js first initialises an instance of Axios, then exports API functions that use that instance as a base as promises.
Below is taken from the file, though I have removed all but one of the functions the module exports for ease of reading (and obviously redacted the API token). The endpoint URI contains "message-threadssss" — this is deliberate, to cause the server to return 404:

import axios from 'axios';

const token = '***************************';
const axiosOptions = {
  baseURL: 'https://www.udemy.com/instructor-api/v1',
  timeout: 10000,
  headers: {
    Accept: '*/*',
    'Content-Type': 'application/json;charset=utf-8',
    Authorization: `Bearer ${token}`,
  },
};

const axiosInstance = axios.create(axiosOptions);

export default {
  postMessage(messageThreadId, messageBody) {
    return axiosInstance
            .post(`/message-threadssss/${messageThreadId}/messages/`, {
              content: messageBody,
            })
            .then(response => response.data)
            .catch(error => error);
  },
}

UdemyApi.postMessage(threadId, threadReply);
.then((response) => {
        this.isLoading = false;
        this.sentReply = response;
        this.replyBody = '';
        this.$root.$emit('reply-sent', {
          threadId: this.thread.id,
          sentReply: this.sentReply,
        });
      })
      .catch((error) => {
        if (error.response) {
          // Case 1 (Server returned error)
          console.log(error.response.data);
          console.log(error.response.status);
          console.log(error.response.headers);
        } else if (error.request) {
          // Case 2 (Pre-response error)
          console.log(error.request);
        } else {
          // Case 3 (Mysterious error)
          console.log('Error:', error.message);
        }
        this.$root.$emit('show-snackbar', {
          message: `Failed to send. ${error} `,
          actionText: 'Understood. :(',
        });
        this.isLoading = false;
      });

The request sends without a problem, and if the request is a success (i.e. 2xx), the Vue component is able to access the response data in the then() block.
When the server returns an error (404 in this instance), I would expect the caught error to contain a response object (Case 1).
Instead though, no response object is returned with the error (Case 2), which prevents me from handling it correctly. This happens when the request does cause the server to respond with a 404 error:
HTTP/2.0 404 Not Found
content-type: text/json

I've read that if Axios has interceptors applied to it, that can lead to this issue, but in this case, I've not applied any interceptors.
All in all, I'm at a bit of a loss. How do I get the server's response into my Vue component?
Edit (6th Feb)
I didn't include the all-useful console output in my initial post, so here it is. The console.log() line executed is the Case 2 line (just one console log entry is added, not prefixed with "Error: ", as would be the case in Case 3):
12:22:28.748
XMLHttpRequest
    mozAnon: false
    mozSystem: false
    onabort: null
    onerror: function handleError()
    onload: null
    onloadend: null
    onloadstart: null
    onprogress: null
    onreadystatechange: function handleLoad()
    ontimeout: function handleTimeout()
    readyState: 4
    response: ""
    responseText: ""
    responseType: ""
    responseURL: ""
    responseXML: null
    status: 0
    statusText: ""
    timeout: 100000
    upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }
    withCredentials: false
    <prototype>: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … }
replybox.vue:72

Edit 2 (6th Feb)
If I remove the then() and catch() from the postMessage() definition to look like this:
 postMessage(messageThreadId, messageBody) {
    return axiosInstance
            .post(`/message-threadssss/${messageThreadId}/messages/`, {
              content: messageBody,
            });
  },

And then simplify the catch() block of the postMessage() call to just output the error object to look like this:
    .catch((error) => {
        console.log(error);
        this.$root.$emit('show-snackbar', {
          message: `Failed to send. ${error} `,
          actionText: 'Understood. :(',
        });
        this.isLoading = false;
      });

The console outputs:
12:38:51.888 Error: "Network Error"
    createError webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15
    handleError webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:87:14
replybox.vue:62

Edit 3 (6th Jan)
I realised in my previous edit, I omitted the output of error.request after I'd removed .then and .catch from my postMessage definition. If I re-add console.log(error.request); to the .catch block of the call in my component, this is the output:
12:58:55.436
XMLHttpRequest
    mozAnon: false
    mozSystem: false
    onabort: null
    onerror: function handleError()
    onload: null
    onloadend: null
    onloadstart: null
    onprogress: null
    onreadystatechange: function handleLoad()
    ontimeout: function handleTimeout()
    readyState: 4
    response: ""
    responseText: ""
    responseType: ""
    responseURL: ""
    responseXML: null
    status: 0
    statusText: ""
    timeout: 100000
    upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }
    withCredentials: false
    <prototype>: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … }

Edit 4 (6th Feb)
To confirm or rule out my implementation of my API abstraction layer, I directly invoked an Axios instance in my component:
const token = '*********************';
const axiosOptions = {
  baseURL: 'https://www.udemy.com/instructor-api/v1',
  timeout: 100000,
  headers: {
    Accept: '*/*',
    'Content-Type': 'application/json;charset=utf-8',
    Authorization: `Bearer ${token}`,
  },
};
const axiosInstance = axios.create(axiosOptions);
axiosInstance
.post(`/message-threadssss/${this.thread.id}/messages/`, {
  content: this.replyBody,
})
.then((response) => {
  this.isLoading = false;
  this.sentReply = response;
  this.replyBody = '';
  this.$root.$emit('reply-sent', {
    threadId: this.thread.id,
    sentReply: this.sentReply,
  });
})
.catch((error) => {
  console.log('Error obj: ', error);
  console.log('Request error obj: ', error.request);
  this.$root.$emit('show-snackbar', {
    message: `Failed to send. ${error} `,
    actionText: 'Understood. :(',
  });
  this.isLoading = false;
  this.axiosResult = error;
});

As before, the server returned the expected 404, and the .catch block in my component caught the error.
As before though, the response was missing from the caught error
13:25:45.783 Error obj:  Error: "Network Error"
    createError webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15
    handleError webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:87:14
replybox.vue:79

13:25:45.786 Request error obj:
XMLHttpRequest
    mozAnon: false
    mozSystem: false
    onabort: null
    onerror: function handleError()
    onload: null
    onloadend: null
    onloadstart: null
    onprogress: null
    onreadystatechange: function handleLoad()
    ontimeout: function handleTimeout()
    readyState: 4
    response: ""
    responseText: ""
    responseType: ""
    responseURL: ""
    responseXML: null
    status: 0
    statusText: ""
    timeout: 100000
    upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }
    withCredentials: false
    <prototype>: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … }
replybox.vue:80

A: I'm pretty sure all you need to do is remove the .then and .catch from your postMessage function and you should be good to go
postMessage(messageThreadId, messageBody) {
  return axiosInstance
     .post(`/message-threadssss/${messageThreadId}/messages/`, {
        content: messageBody,
      })
}

This way, postMessage is returning a promise. And when you actually call postMessage you can use .then and .catch

A: So, the answer it seems was actually the result of the API I was calling not serving the correct CORS headers with error responses (so CORS was only allowed for 2xx responses).
Consequently, Axios was unable to access the response.
I'll need to work around a general ambiguous error for the moment, but solution going forwards lies with developers of the API serving CORS with both success and error responses.
Many thanks to Bergi for their help, which ultimately led me to the cause of the issue.


text:
Q: XAML - Way to find which button is clicked I am developing Windows Store App.
I am loading XAML code dynamically from C# code behind file. So, I could not add click event to buttons.
Is there any way to get to know which button is clicked using button names with out the click event?

A: You should look into the MVVM and Command patterns for WPF development. The click event handler is outdated Windows Forms programming. In WPF, the command pattern is represented by the ICommand interface. Each button has a Command property where you can bind a command object.

A: How are you loading XAML code dynamically? You can load XAML dynamically, locate all button instances, and add event listeners for "Tapped" event.
var grid = Xaml.LoadXaml("<Grid><Button x:Name='BLAH' /><Button x:Name='BLAH2'></Grid");
foreach(var button in VisualHelper.FindVIsualCHildren<Button>(grid))
  button.Tapped += delegate(object sender, TappedEventArgs a)
  {
        var btn = sender as BUtton;
   }

You can find useful stuff from this toolkit: http://winrtxamltoolkit.codeplex.com/


text:
Q: How to add a letter in a field using AWK I have a gtf file with 100K rows and I want to simply add a letter 'm' to its first field:
chr1    HAVANA  gene    3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; gene_type "TEC"; gene_name "4933401J01Rik"; level 2; havana_gene "OTTMUSG00000049935.1";
chr1    HAVANA  transcript      3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; transcript_id "ENSMUST00000193812.1"; gene_type "TEC"; gene_name "4933401J01Rik"; transcript_type "TEC"; tr
chr1    HAVANA  exon    3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; transcript_id "ENSMUST00000193812.1"; gene_type "TEC"; gene_name "4933401J01Rik"; transcript_type "TEC"; transcript
chr1    ENSEMBL gene    3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; gene_type "snRNA"; gene_name "Gm26206"; level 3;
chr1    ENSEMBL transcript      3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; transcript_id "ENSMUST00000082908.1"; gene_type "snRNA"; gene_name "Gm26206"; transcript_type "snRNA"; tran
chr1    ENSEMBL exon    3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; transcript_id "ENSMUST00000082908.1"; gene_type "snRNA"; gene_name "Gm26206"; transcript_type "snRNA"; transcript_n
chr1    HAVANA  gene    3205901 3671498 .       -       .       gene_id "ENSMUSG00000051951.5"; gene_type "protein_coding"; gene_name "Xkr4"; level 2; havana_gene "OTTMUSG00000026353.2";

A desired output would be:
mchr1    HAVANA  gene    3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; gene_type "TEC"; gene_name "4933401J01Rik"; level 2; havana_gene "OTTMUSG00000049935.1";
mchr1    HAVANA  transcript      3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; transcript_id "ENSMUST00000193812.1"; gene_type "TEC"; gene_name "4933401J01Rik"; transcript_type "TEC"; tr
mchr1    HAVANA  exon    3073253 3074322 .       +       .       gene_id "ENSMUSG00000102693.1"; transcript_id "ENSMUST00000193812.1"; gene_type "TEC"; gene_name "4933401J01Rik"; transcript_type "TEC"; transcript
mchr1    ENSEMBL gene    3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; gene_type "snRNA"; gene_name "Gm26206"; level 3;
mchr1    ENSEMBL transcript      3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; transcript_id "ENSMUST00000082908.1"; gene_type "snRNA"; gene_name "Gm26206"; transcript_type "snRNA"; tran
mchr1    ENSEMBL exon    3102016 3102125 .       +       .       gene_id "ENSMUSG00000064842.1"; transcript_id "ENSMUST00000082908.1"; gene_type "snRNA"; gene_name "Gm26206"; transcript_type "snRNA"; transcript_n
mchr1    HAVANA  gene    3205901 3671498 .       -       .       gene_id "ENSMUSG00000051951.5"; gene_type "protein_coding"; gene_name "Xkr4"; level 2; havana_gene "OTTMUSG00000026353.2";

A: You may  use awk to add letter to the start of the row. Here $0 means the entire row.
echo "hey there" |awk '{$0="m"$0}1'
mhey there

or sed : here ^ represent start of the line.  If you want to directly reflect the changes into the file then use -i or -i.bak flag with sed command.
echo "hey there" |sed 's/^/m/'
mhey there

A: Adding here 1 more way, where not editing or adding character to line.
awk '{print "m"$0}' Input_file

A: This thing is better with sed:
sed -e 's/^/m/' file

Add -i to change inplace.  (-i '' for macos)
Using awk, can do it like this:
awk 'sub(/^/,"m")' file


text:
Q: javascript removeChild then replace this with new text using insertBefore I want to create a function in an external javascript file that I can reuse later (i.e. a modular function that is general enough to be used in whatever javascript it is needed in).  I want to do this with pure JavaScript, not using jQuery or innerHTML.
I want this modular function to do the following:
  1) remove an element of a child
  2) replace this child with the new child value
For example say you had this code:

This text needs to be removed

This is the paragraph that follows the replaced paragraph

So I need to:
  1) parentNode.removeChild(removeMe);
  2) var replacementParagraph = document.createElement('p');
  3) var replacementParagraphText =document.createTextNode("This is the replacementParagraph text);
  4) replacementParagraph.appendChild(replacementParagraphText);

Now I just need to figure out how to write the modular function sort of like below:
function removeReplace (parameter, parameter) {
   1) remove the child of the paragraph with the id of "removeMe"
   2) use insertBefore(newText, nextPara) to replace the child that was removed in step 1
}

Thank you so much for your help, Jason

A: Oh, it's much easier because this function already exists natively: .replaceChild(). Actually you've already got the algorithm, you just would need to write it in javascript:
function replaceElementByParagraph(id, text) {
    var toremove = document.getElementById(id);
    if (!toremove) // in case no element was found:
        return false; // abort
    var para = document.createElement('p');
    para.appendChild(document.createTextNode(text));
    return toremove.parentNode.replaceChild(para, toremove);
}


text:
Q: Создаёт ли копию new Function() и нагружает ли она память для серверного ПО? Всем привет !
начал писать простенький TCP сервер
и столкнулся с очень любопытной ситуацией
посоветовали использовать интересный метод , но ранее
я никогда него не использовал и не знаю как он работает
да и как называется тоже
но суть в том что условно можно вызвать весь класс как функцию
типа такого new Function()
в общем при инициализации выполняется твоя функция и сразу IDisposable её убивает
у меня есть class Session
в нём я слушаю клиента по TCP
после того как я получил от него пакет , полученный массив buffer отправляю в функцию Handler
при каждом новом клиенте , я заношу его в ClientsManager
в таком случае у меня создаётся много копий Session под каждого клиента
using System;
using System.Net.Sockets;

namespace server
{
    class Session : IDisposable
    {
        private byte[] buffer;
        private Socket socket { get; set; }
        public Session(Socket socket)
        {
            this.socket = socket;
            socket.ReceiveTimeout = 1000;
            ClientsManager.online++;
            buffer = new byte[2];
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, End2Bytes, null);
        }
        private void End2Bytes(IAsyncResult result)
        {
            try
            {
                if (socket.EndReceive(result) >= 2)
                {
                    var length = BitConverter.ToUInt16(buffer, 0);
                    buffer = new byte[length];
                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, EndReadBytes, null);
                }
                else
                {
                    Disconnect(); // Отключаем клиента с не понятными пакетами
                    Console.WriteLine("socket.EndReceive(result) < 2"); // Пакеты меньше 2 байт
                }
            }
            catch (Exception e) // Удаленный хост принудительно разорвал существующее подключение
            {
                Console.WriteLine(e);
            }
        }
        private void EndReadBytes(IAsyncResult result)
        {
            try
            {
                if (socket.EndReceive(result) == buffer.Length && buffer.Length >= 2) new Handler(buffer); // было Handler(buffer);
                buffer = new byte[2];
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, End2Bytes, null);
            }
            catch (Exception e) // Удаленный хост разорвал существующее подключение
            {
                Console.WriteLine(e);
            }
        }
        private void Disconnect()
        {
            socket.BeginDisconnect(false, EndDisconnect, null);
        }
        private void EndDisconnect(IAsyncResult result)
        {
            socket.EndDisconnect(result);
            socket.Disconnect(false);
            ClientsManager.getInstance().clients.Remove(this);
            ClientsManager.online--;
            Dispose();
        }
        public void Dispose()
        {
            socket = null;
            buffer = null;
        }
        ~Session()
        {
            Dispose();
        }
        //private void Handler(byte[] buffer) // Перенесён в класс Handler
        //{
        //}
    }
}

изначально я держал в классе Session функцию Handler()
и посоветовали мне вынести Handler в отдельный класс , молвь зачем ты память забиваешь одним и тем же Handler'ом ?
представь - сколько клиентов столько копий Обработчика (Handler'a)
вынести его в отдельный класс
и вызывай его не Handler(buffer); а new Handler(buffer);
ну а в классе Обработчика напиши вот так :
using System.IO;
namespace server
{
    class Handler
    {
        public Handler(byte[] buffer)
        {
            using (var br = new BinaryReader(new MemoryStream(buffer)))
            {
                var opcode = br.ReadUInt16();
                switch (opcode)
                {
                    case 0000: { break; } // Disconnect
                    case 0001: { break; } // Version
                    case 0002: { break; } // Check Login & Password // Answer ID
                    default: { Console.WriteLine("Unknown OpCode : " + opcode ) ; break; }
                }
            }
        }
    }
}

в общем собственно вопрос :
при вызове команды new Handler(buffer)
я вызываю функцию из другого класса ?
или создаётся копия у каждой сессии ?
по суть это же очень большая нагрузка будет на сервер
когда существует 100 клиентов , у каждого своя сессия , и каждая сессия
создаёт каждый раз новый Handler что бы обработать 1 пакет
а от одного клиента в 1 секунду прилетает около 60 пакетов
или он просто вызывает как функцию ?
можно было бы создать публичный статический класс
в нём public static void Get(buffer)
и вызывать в сессии просто как Handler.Get(buffer)
но тогда мне кажется будет забитый поток
то есть пока сессия к примеру игрока A запускает Handler.Get(buffer)
в это время начинает действовать сессия игрока B и ждёт пока Handler.Get(buffer) освободится от игрока A
или я заблуждаюсь ?
что посоветуете ?
и разъясните что такое new Function()
как он работает ? или это по факту одно и тоже что статическая функция в другом классе
или при вызове Handler.Get(buffer) тоже будет создаваться копия ?
тогда какой лучше для производительности ?

и что лучше использовать , как по производительней ?
1) обработчик прям в классе session
2) создавать новый класс и во время инициализации обрабатывать ?
3) или сделать статическую функцию в
другом классе и вызывать его из каждой сессии ?

A: Вам насоветовали что-то странное (ну или вы не поняли совета).
Методы не "занимают память" внутри экзепляров класса. Т.е. ваш
private void Handler(byte[] buffer) // Перенесён в класс Handler
{
}

не займет "дополнительную память внутри каждого Session". Код сам по себе - общий для всех объектов Session. Память для каждого экземпляра занимают только поля класса. Вот ваши поля класса Session:
private byte[] buffer;
private Socket socket { get; set; }

А вот выделение Handler в отдельный класс, да еще и создание его для каждого вызова (через new) - действительно создает новые экзепляры Handler для каждого вызова new Handler, отъедая при этом память (правда, ненадолго, и незначительно). Т.е. второй вариант хуже (чуть-чуть) по памяти, чем первый.


text:
Q: ImageView in Xamarin.iOS LaunchScreens: Set image I want to change/set the image in my launch screen for my Xamarin.iOS App.
Opening LaunchScreen.storyboard in my Visual Studio 2017 (Win10), I get the storyboard editor as expected.
But if I want to change (or even set) the Image-Property of the default  ImageView (or a newly added one), the default file open dialogs comes up - and no matter what image file I select, nothing changes.
Do the images for the launch screen storyboard comply some criteria? e.g. filetype? location?
Update:
This is the property I try to set with an image:

As files I tried several PNG images - all working well as images in my normal Xamarin Views or as Icons.

A: I think your problem is that you can try this way,rebuild your project when you create a new xarmain.ios project.
 Try the following steps


text:
Q: For equation $A\cdot x=0$, what conditions on matrix $A$ will ensure that $x$ is not a positive or negative vector? Let $A$ be a $m\times n$ matrix and $x$ be a $n\times 1$ vector. Consider equation $A\times x=0$.
Under what conditions, $x$ is not a positive or negative vector? That is, we cannot have all entries of $x$ are positive or all are negative.
I guess it's about the eigenvalues of $A^TA$. Perhaps, they can't be all positive or all negative? This is just my guess and I have been alway from linear algebra for a long time. Please correct me if I am wrong. Thank you.

A: The absence of a positive (and negaitve) solutions to $Ax=0$ can be approached via convex duality where it is equivalent to the existing of a solution to the dual system of (in this case linear) constraints. Namely, one can use Farkas lemma.
We want the following system
$$
Ax=0,x>0
$$
to have no solution. Introducing the notation $e$ for the vector of all ones
$$
e=\begin{bmatrix}1\\1\\\vdots\\1\end{bmatrix}
$$
the system may equivalently be rewritten as the second alternative in the link above
$$
\begin{cases}
Ax\ge 0,\\
-Ax\ge 0,\\
x\ge t\cdot e,\\
t>0
\end{cases}
\qquad\Leftrightarrow\qquad
\begin{cases}
\begin{bmatrix}
A & 0\\-A & 0\\I & -e
\end{bmatrix}
\begin{bmatrix}x\\t\end{bmatrix}\ge 0,\\
\begin{bmatrix}0 & -1\end{bmatrix}\begin{bmatrix}x\\t\end{bmatrix}<0.
\end{cases}
$$
Here zero blocks are columns/rows of corresponding dimensions to fit the block matrix.
Farkas lemma gives then the necessary and sufficient condition as that there exists a solution to the dual (first) alternative in the link
$$
\begin{cases}
\begin{bmatrix}
A^T & -A^T & I\\0 & 0 & -e^T
\end{bmatrix}
\begin{bmatrix}u\\v\\w\end{bmatrix}=
\begin{bmatrix}0\\-1\end{bmatrix},\\u,v,w\ge 0
\end{cases}\qquad\Leftrightarrow\qquad
\begin{cases}
A^T(v-u)=w,\\
e^Tw=1,\\
u,v,w\ge 0.
\end{cases}
$$
Introducing the notation $d=v-u$ we get rid of the positivity condition (the standard procedure in the linear programming), and the system becomes
$$
\begin{cases}
A^Td=w\ge 0,\\
e^Tw=1.
\end{cases}
$$
The last condition is the normalization which is equivalent to saying that $w\ne 0$ (because then we can always scale the solution by $e^Tw$). Therefore we arrive to the equivalent condition that

there must exist a solution to the following system
  $$
A^Td\ge 0,\quad A^Td\ne 0.
$$

Interpretaion: it is the same as $d^TA\ge 0,\ne 0$, that is, there exists a linear combination of the rows of $A$ that is nonnegative and nonzero. It is easy to see that it is necessary (see the comment from Петя Нарышкин): $Ax=0$ $\Rightarrow$ $\underbrace{d^TA}_{\ge 0,\ne 0}x=0$ $\Rightarrow$ $x\not> 0$.
A test for that can be implemented e.g. as LP
$$
\gamma=\max_{d,w} e^Tw\quad\text{ subject to }A^Td=w,\ w\ge 0,\ -1\le d_i\le 1.
$$
If $\gamma>0$ then it is ok.


text:
Q: Attaching onclick on JQUERY I have a problem since I wanted to attach the onclick alert function on an  tag.
This thing doesn't work. The alert('hi') doesn't appear. Did I miss something?
    $(document).ready(function(){
        const requiredBy = true;
                if(requiredBy){
                    var banner = $(".bannerLink");
                    if(banner.length==0){
                        var pdpHead = $("[replaceclass='PDPHeadReplace']");
                        if(pdpHead.length!=0){
                            pdpHead.prepend('<div class="bannerLink"></div>');
                            banner = pdpHead.find(".bannerLink");
                        }
                    }
                    if(banner.length!=0){
                        banner.append("<a href='#' onclick='alert('hi')'><img src='https://test.com' style='margin-top:5px;' ></a>");
                        $('.helloDiv').css({ 'display' : 'block', 'padding-top': '1rem'});
                    }
                }
    });

A: You can use onclick='alert("hi")' for escaping "
Code:
banner.append("");

Edit: I changed < and > to < and > so that the element will not be appended as text

A: There are two issues here.

*

*First, you haven't skip the special characters to not append the link as text not html

*Second, you need to skip the nested " double quote inside the alert

    $(document).ready(function(){
        const requiredBy = true;
                if(requiredBy){
                    var banner = $(".bannerLink");
                    if(banner.length==0){
                        var pdpHead = $("[replaceclass='PDPHeadReplace']");
                        if(pdpHead.length!=0){
                            pdpHead.prepend('<div class="bannerLink"></div>');
                            banner = pdpHead.find(".bannerLink");
                        }
                    }
                    if(banner.length!=0){
                        banner.append("link<img src='https://test.com' style='margin-top:5px;' ");
                        $('.helloDiv').css({ 'display' : 'block', 'padding-top': '1rem'});
                    }
                }
    });


text:
Q: Prove ${x \choose k}1/x^k < {y \choose k}1/y^k$ given that $x < y$ and $x, y \in \mathbb{N}$ I am struggling with this proof because of the $1 / x^k$ and $1 / y^k$ part. Proving the inequality of the combinations just boils down to axioms, but I'm not sure how to prove the entire statement. I tried assuming that $y = x + a$ for some $a \in \mathbb{N}$ and then using induction for $k+1$, but I don't know if that's the correct way to do it.

A: Rewrite the inequality as
$$
\frac{y^kx(x-1)\ldots(x-k+1)}{k!} < \frac{x^ky(y-1)\ldots(y-k+1)}{k!}.
$$
Cancelling $k!$ on both sides and rearranging gives
$$
\left(1-\frac{1}{x}\right)\ldots\left(1-(\frac{k-1}{x})\right) < \left(1-\frac{1}{y}\right)\ldots\left(1-(\frac{k-1}{y})\right),
$$
which holds because $x < y$.
(I assumed that $k$ is a natural number that is not more than $x$ or $y$.)


text:
Q: Get the smallest value of value in checkbox using JavaScript I would like to get the smallest value using JavaScript when I had choose more than 10 item. But I couldn't get the result based on my code. I think the error was in "price[i]" but I don't know how to write it correctly.
And here is my code. What is the correct way to get the smallest value?
<!DOCTYPE html>

<form name="frm1">

<input type="checkbox" name="item" value="100"/>Pan     RM 100

<input type="checkbox" name="item" value="50"/>Fork     RM 50

<input type="checkbox" name="item" value="200"/>Stove   RM 200

<input type="checkbox" name="item" value="10"/>Pen      RM 10

<input type="checkbox" name="item" value="60"/>Mouse    RM 60

<input type="checkbox" name="item" value="40"/>Keyboard RM 40

<input type="checkbox" name="item" value="30"/>Glue     RM 30

<input type="checkbox" name="item" value="210"/>Speaker RM 210

<input type="checkbox" name="item" value="300"/>Case    RM 300

<input type="checkbox" name="item" value="80"/>Cable    RM 80

<input type="checkbox" name="item" value="110"/>Extention   RM 110

<input type="checkbox" name="item" value="400"/>Redmi   RM400

<input type="button" name="subbtn" value="Send" onclick="getprice();"/>

</form>

A: Here is your code updated. I change some part to make it easier and clearer.
All the values of the checked checkboxes are stored inside checkedValues array
This code is using Array#filter(), Array#map(), Array#reduce() and math.min.apply

function getprice() {
  let checkedValues = Array.from(document.frm1.item).filter(i=>i.checked).map(i=>+i.value);

  let total = checkedValues.length === 0 ? 0 : checkedValues.reduce((a, b) =>a+b);
  document.getElementById("totalprice").innerHTML = "Total Price : RM " + total.toFixed(2);
  document.getElementById("totalitem").innerHTML = "Total item: " + checkedValues.length;

  if (total >= 300 && checkedValues.length >= 10) {
    let min = Math.min.apply(Math, checkedValues);
    document.getElementById("smallestp").innerHTML = "Smallest price : RM " + min.toFixed(2);
  }
}
<form name="frm1">

  <input type="checkbox" name="item" value="100" />Pan RM 100

  <input type="checkbox" name="item" value="50" />Fork RM 50

  <input type="checkbox" name="item" value="200" />Stove RM 200

  <input type="checkbox" name="item" value="10" />Pen RM 10

  <input type="checkbox" name="item" value="60" />Mouse RM 60

  <input type="checkbox" name="item" value="40" />Keyboard RM 40

  <input type="checkbox" name="item" value="30" />Glue RM 30

  <input type="checkbox" name="item" value="210" />Speaker RM 210

  <input type="checkbox" name="item" value="300" />Case RM 300

  <input type="checkbox" name="item" value="80" />Cable RM 80

  <input type="checkbox" name="item" value="110" />Extention RM 110

  <input type="checkbox" name="item" value="400" />Redmi RM400

<input type="button" name="subbtn" value="Send" onclick="getprice();" />

</form>

A: I've used Array#filter to filter all checked checkboxes, then mapped it with Array#map to get value of each checked checkbox. Then - used Math.min.apply to get the lowest value.

function getprice() {
  var total = 0.00,
    i, count = 0,
    min = 0;

  for (i = 0; i < document.frm1.item.length; i++) {
    if (document.frm1.item[i].checked) {
      total = total + parseInt(document.frm1.item[i].value);
      count = count + 1;
    }
  }
  document.getElementById("totalprice").innerHTML = "Total Price : RM " + total.toFixed(2);
  document.getElementById("totalitem").innerHTML = "Total item: " + count;
  var checked = document.getElementsByName('item')

  if (total >= 300 && count >= 10) {
    var elems = Array.from(checked).filter(v => v.checked).map(c => Number(c.value));
    var cheapest = Math.min.apply([], elems);
    document.getElementById("smallestp").innerHTML = "Smallest price : RM " + cheapest.toFixed(2);
  }
}
<form name="frm1">

  <input type="checkbox" name="item" value="100" />Pan RM 100

  <input type="checkbox" name="item" value="50" />Fork RM 50

  <input type="checkbox" name="item" value="200" />Stove RM 200

  <input type="checkbox" name="item" value="10" />Pen RM 10

  <input type="checkbox" name="item" value="60" />Mouse RM 60

  <input type="checkbox" name="item" value="40" />Keyboard RM 40

  <input type="checkbox" name="item" value="30" />Glue RM 30

  <input type="checkbox" name="item" value="210" />Speaker RM 210

  <input type="checkbox" name="item" value="300" />Case RM 300

  <input type="checkbox" name="item" value="80" />Cable RM 80

  <input type="checkbox" name="item" value="110" />Extention RM 110

  <input type="checkbox" name="item" value="400" />Redmi RM400

<input type="button" name="subbtn" value="Send" onclick="getprice();" />

</form>


text:
Q: How to pass Nullable Bit type value into to SQL Server stored procedure? I want to pass null value to where clause  bit type variable to get all rows in a table. But also when I pass true or false where clause should work in order to that.
Error:

Type of conditional expression cannot be determined because
  there is no implicit conversion between 'bool?' and 'System.DBNull'

Stored procedure:
CREATE PROCEDURE [dbo].[SelectAllUIDs]
    @enable bit
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        [UID], [fEnable] [Enable],
        [AddedDate] [Added Date]
    FROM
        [VehicleService].[dbo].[NFCCard]
    WHERE
        fEnable = @enable OR fEnable IS NOT NULL
    ORDER BY
        NfcKy
END

C# code:
 public DataSet SelectUid(bool? status)
 {
        DataSet ds = new DataSet();

        try
        {
            SqlCommand com = new SqlCommand("SelectAllUIDs", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.Add(new SqlParameter("@enable", SqlDbType.Bit)
                                   { Value = status != null ? status : DBNull.Value });

            SqlDataAdapter adp = new SqlDataAdapter(com);
            adp.Fill(ds);
        }
        catch (Exception ex)
        {
            ds = null;
            throw ex;
        }
        return ds;
    }

Calling:
DataSet ds = SelectUid(null); // should return all rows

DataSet ds = SelectUid(true); // should return fEnable = true rows

DataSet ds = SelectUid(false); // should return fEnable = false rows

A: You can use the ?? operator to provide an alternative for when the status is null.  Like @user2864740 commented, both sides have to be compatible types.  This won't work:
var x = true ?? DBNull.Value;  // "no implicit conversion" error

The left hand value of ?? is a bool, but the right hand value is not.  So the compiler will complain DBNull.Value cannot be "implicitly cast" to bool.  To solve this, cast the left hand side to object:
var x = (object) true ?? DBNull.Value;

Now ?? will evaluate to an object, which can contain both a bool and a DNull.Value.  Applying that to your problem, you get:
com.Parameters.AddWithValue("@parname", (object) status ?? DBNull.Value);

A: I have a Nullable project, the above code generates compiler warnings and use this pattern
static object Nullable(bool? value)
{
    if (value is null)
        return DBNull.Value;
    else
        return value.Value;
}
static object Nullable(int? value)
{
    if (value is null)
        return DBNull.Value;
    else
        return value.Value;
}

The compiler knows what to pick so that gets solved without any issue during compile time no matter how many nullable data types I use.
my parameters I declare like this
com.Parameters.Add(
new SqlParameter("parameterName", SqlDbType.Bit) { Value  = Nullable(visitStat.Interactive), IsNullable=true });

I like to reduce reflection when I can and AddWithValue will cause reflection in MS code and you usually end up with the wrong data type in your parameterised queries when there is no need for it as you know the datatype when you write the code.
using reflection-based SQLParameter constructors is not too smart as when you do that SQL server will cast it into the proper data type in the execution plan making it a Row-By-Row operation. Particularly bad when using TSQL data types like SmallDatetime, date, TinyInt, CHAR, and VarChar data types as they always come out wrong.
You see this when passing strings as they always get reflected in nvarchar(max) compare an indexed email field with a nvarchar(max) parameter...  have a look at implicit conversions, we know the data type it needs, the few extra characters we need to type in our program code are worth the hassle when "they say" that the "database is to slow" when it starts bigger than the tiny developer database that probably fits in memory.
Just because you can make a 1 liner in your code doesn't make it performant


text:
Q: Lebesgue–Stieltjes integration with discontinuous function My question comes from the book Credit risk modeling: Valuation and hedging by Tomasz R. Bielecki and Marek Rutkowski, Page 137 at the bottom. It is easily described as follows:
Consider a probability space $(\Omega,\mathcal{F},\mathbb{P})$. Let $\tau:\Omega\rightarrow\mathbb{R}_+$ be a non-negative random variable defined on $(\Omega,\mathcal{F},\mathbb{P})$ with $\mathbb{P}(\tau=0)=0$ and $\mathbb{P}(\tau>t)>0$ for all $t\in\mathbb{R}_+$. Its cdf is $F(t)=\mathbb{P}(\tau\leq t)$. Define its hazard function $\Gamma(t)$ as
$$
\Gamma(t)=-\ln (1-F(t)) \quad\text{or}\quad F(t)=1-e^{-\Gamma(t)}
$$
Then, both $F(t)$ and $\Gamma(t)$ are right-continuous. Let $H_t=\mathbb{I}_{\{\tau\leq t\}}$ be a jump process and let $L_t=(1-H_t)e^{\Gamma(t)}$.
The question involves applying the product rule to $L_t$ when $\Gamma(t)$ is discontinuous. The book gives the following calculation:
$$
\begin{split}
L_t & = L_0+\int_{]0,t]}(1-H_u)de^{\Gamma(u)}-\int_{]0,t]}e^{\Gamma(u_{-})}dH_u
\\
& = 1 + \int_{]0,t]}e^{\Gamma(u_{-})}((1-H_u)d\Gamma(u)-dH_u)+\sum_{s\leq t,s<\tau}(\Delta e^{\Gamma(s)}-e^{\Gamma(s_{-})}\Delta\Gamma(s))
\end{split}
$$
where $\Delta e^{\Gamma(s)}=e^{\Gamma(s)}-e^{\Gamma(s_{-})}$ and $\Delta\Gamma(s)=\Gamma(s)-\Gamma(s_{-})$.
However, I am not sure how the last term is obtained: $\sum_{s\leq t,s<\tau}(\Delta e^{\Gamma(s)}-e^{\Gamma(s_{-})}\Delta\Gamma(s))$. $\Delta e^{\Gamma(s)}$ seems reasonable to me, but where does $-e^{\Gamma(s_{-})}\Delta\Gamma(s)$ come from? And why does it have a negative sign?
Thank you very much in advance!
UPDATE:
I think I got it. The first term $\Delta e^{\Gamma(s)}$ takes care of jumps in $e^{\Gamma(u)}$ due to jumps in $\Gamma(u)$. After this, the integral should be over $\Gamma(u)^c$, i.e. the continuous part of $\Gamma$. Hence, in order to write it as an integral over $\Gamma(u)$ instead, jumps in $\Gamma(u)$ should be subtracted, which is done by the second term $e^{\Gamma(s_{-})}\Delta\Gamma(s)$:
$$
\begin{split}
\int_{]0,t]}(1-H_u)de^{\Gamma(u)} &=\int_{]0,t]}(1-H_u)d(e^{\Gamma(u)})^c+\sum_{s\leq t,s<\tau}\Delta e^{\Gamma(s)} \\
&=\int_{]0,t]}e^{\Gamma(u)}(1-H_u)d\Gamma(u)^c+\sum_{s\leq t,s<\tau}\Delta e^{\Gamma(s)} \\
&=\int_{]0,t]}e^{\Gamma(u_{-})}(1-H_u)d\Gamma(u)+\sum_{s\leq t,s<\tau}(\Delta e^{\Gamma(s)}-e^{\Gamma(s_{-})}\Delta\Gamma(s))
\end{split}
$$