text:
Q: Как в Visual Studio 2013 добавить кнопку? Где эти панели, чтоб перетащил кнопку, кликнул по ней и прописал код, как в старом добром бейсике 6.0?
Ох уж этот бейсик 6.0. Не придумали еще программу лучше тебя...
A: Visual Studio может работать с четырьмя разными языками + к каждому есть несколько видов проектов. В зависимости от проекта, студия располагает различными инструментами. Поэтому уточняйте, с чем работать собираетесь.
Методом научного тыка и дедукции, я так полагаю язык Visual Basic .NET и проект Windows Forms Application? Тогда так: View -> Toolbox (ctrl+alt+x)


text:
Q: Graphing - area of a triangle Question:
If the area of a triangle formed by the points $(2a,b),  (a + b, 2b + a),  (2b,2a)$ is $\lambda$, then what is the area of the triangle whose vertices are $(a+b,a-b),(3b-a,b+3a) and (3a-b,3b-a)$ ?
I attempted to find a relation between the two sets of vertices, but was unable to do so. How exactly would I proceed with this question?

A: If you are familiar with determinants then the area of a triangle formed by points with vertices $(x_i,y_i)$ with $i=1,2,3$ is given by
$$
\text{Area} = \frac{1}{2}\left|
\begin{array}{ccc}
1 & x_1 & y_1\\
1 & x_2 & y_2\\
1 & x_3 & y_3\\
\end{array}
\right|
$$
Using this you can express the area of the first triangle as well as the second triangle. Then use the properties of determinants to get a relation between the two.
Note: The area of the second will be $4$ times that of the first.

A: Let $P=(2a,b), \;Q=(a+b,2b+a), \;R=(2b,2a)$ and
$u=\vec{PQ}=\langle b-a,b+a\rangle$ and $v=\vec{QR}=\langle b-a, a-2b\rangle$.
Similarly, let $P_1=(a+b,a-b), \;Q_1=(3b-a,b+3a), \;R_1=(3a-b,3b-a)$ and
$u_1=\vec{P_1Q_1}=\langle 2b-2a, 2b+2a\rangle$ and $v_1=\vec{P_1R_1}=\langle 2a-2b, 4b-2a\rangle$.
Then $A_1=\frac{1}{2}||u\times v||=\lambda$ and $A_2=\frac{1}{2}||u_1\times v_1||=4\lambda$ since $u_1=2u$ and $v_1=-2v$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compiled Expression Tree slow due to JIT_MethodAccessCheck We're using compiled Expression Trees to generate code dynamically; some information only available to us at runtime enables us to (in theory) write simpler, faster code.
We do get a performance boost in many cases.
However, in some cases we get a performance hit. In such cases, the Visual Studio Profiler shows that the difference in performance is due to this method (which doesn't show up at all in statically compiled code)
JIT_MethodAccessCheck

What does this method do? (Google doesn't have much to say about it).
Can I optimize it away somehow?

A: JIT_MethodAccessCheck method performs security checks such as SecurityTransparent, APTCA and class access checks as mentioned by @xanatos.
Class access checks include SecurityCritical, SecuritySafeCritical, attached profiler bypass and LinkDemand. More details can be found at coreclr jithelpers.cpp.
Since coreclr is compatible with CLR, we can safely assume that the checks are in the same manner in both of them.

A: Use the code snippet in this answer to compile expression trees instead, it gets rid of the checks across method boundaries:
Why is JIT_MethodAccessAllowedBySecurity taking so much time?


text:
Q: construct a ring homomorphism This is an assignment question, please give hints only thank you!
Construct a ring homomorphism $f: R \rightarrow S$ such that $\ker(f)$ is a maximal ideal, and $S$ is not a field.
I know that $I\subseteq R$ is a maximal ideal iff $R/I$ is a field.
I thought of $R$ being $\mathbb{Z}/n\mathbb{Z}$, but then $\ker(f)$ would have to be $n\mathbb{Z}$ and n would have to be a prime number. Then, what would be a suitable $S$ in this case?

A: The hint you ask for:  the map doesn't have to be surjective.

The solution (for others looking at the question): Just let $R=\Bbb Z$ and $S=\Bbb Z\oplus \Bbb Z/p$ and map

$$\phi:\begin{cases}\Bbb Z\to \Bbb Z\oplus \Bbb Z/p\\ x\mapsto (0, x\mod p)\end{cases}$$

Clearly $S$ is not a field, and clearly the kernel is $(p)$ which is a maximal ideal of $R$.
The main trick of it:  don't demand that $S=\text{Im}( \phi)$ is the full image, surjective homomorphisms won't work since the first isomorphism theorem tells you the image is a field. But the image doesn't have to be the full co-domain, so we just slap on an extra $\Bbb Z$ to make it not a field.

Edit (addendum): In the case this is demanded to be a unital homomorphism, you just tweak things and let $R=\Bbb Z/p$ and $S=\Bbb Z/p\oplus\Bbb Z/p$. Then let
$$\phi:\begin{cases} R\to S \\ x\mapsto (x,x)\end{cases}$$
Here the kernel is $\{0\}$ because the map is injective, and again $S$ is not a field since $(0,1)\cdot (1,0)=(0,0)$.


text:
Q: Will multiple solutions for speeding up Dijkstra lower performance? I have implemented a generic Dijkstra search:
public void search(Vertex source) {
    source.minDistance = 0;

    PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
    vertexQueue.add(source);

    while (!vertexQueue.isEmpty()) {
        Vertex u = vertexQueue.poll();

        for (Edge e : u.edges) {
            Vertex v = e.target;

            int weight = e.weight;
            int distance = u.minDistance + weight;

            if (distance < v.minDistance) {
                vertexQueue.remove(v);

                v.minDistance = distance ;
                v.previous = u;

                vertexQueue.add(v);
            }
        }
     }
}

Ways for speeding up include:

*

*Fibonacci heaps

*Bi-directional search

This search will be used as a basis for implementing k-shortest path using Yen's algorithm.
Will applying BOTH speed-ups at the same time on the algorithm improve the search time or will there be some performance loss because both are being used?
Also, are there further speed-ups that can be implemented?

A: java.util.PriorityQueue.remove is an O(n) operation. If you want to use this PriorityQueue, it is better to permit duplicate vertices in the PriorityQueue, but only process a Vertex the first time it is polled:
class Vertex {
    // existing members

    boolean visited;
}

and
        Vertex u = vertexQueue.poll();
        if (u.visited) continue;
        u.visited = true;

While this will increase the size of the priority queue by a factor of up to d (the maximum node degree), and therefore change the runtime to O(dn log(nd)), i.e. O(dn (log n + log d)), this is probabaly acceptable if d is small. In particular, if d is constant (which it is in many real world path finding problems), this algorithm is O(n log n).
Using a pointer based heap implementation such as fibonacci heap would permit to efficiently prevent duplicates in the heap by offering a cost reduction operation, but a pointer based data structure has a poorer constant factor than an array backed priority queue. Moreover, a fibonacci heap is steeper by a constant factor, requiring more nodes to be touched in each operation. Therefore, I suspect it will actually be slower than a binary heap with duplicates (assuming the node is reasonably small).
With bidirectional search, I assume you mean running Dijkstra from both ends in "parallel", until the two meet? This optimization would be independent of improvements in the queue representation, and can well be combined.
Another possible improvement is calling Dijkstra less often, by leveraging the similarity of subsequent Dijkstra invocations by Yen's algorithm. Might it be worthwhile to amend Dijkstra so we could rewind it, rather than start anew from scratch? Alas, I don't quite understand Yen algorithm, so I can not assess whether this would help.

A: I actually do think that using a Fibonacci heap would be faster, although you may only notice if you call this function many times. Using back tracking as well would also probably help even more.
However, I would recommend that instead of using Yen's algorithm, use the K* algorithm which basically allows you to use A* for the k-shortest path problem! K* has some other benefits as well in particular memory usage for very large graphs.
You can find a free copy of the paper here: (I think there is a newer longer version of this paper as well) K∗: A Directed On-The-Fly Algorithm for Finding the k Shortest Paths
Hope this helps.


text:
Q: Netbeans libraries contains different jar/class than directed to I have been trying to follow the Getting Started with JAX-WS Web Services. I had a lot of trouble because JDK 6 has JAX-WS 2.1 but METRO has JAX-WS 2.2 . So with a lot of searching I found out that something called "endorsed" exists. I try to work with apache and I found out about the JAX-WS clash (see PS2 hyperlink 3). Now I have an endorsed folder with 2 .jar files in it: "C:\Program Files\Java\jdk1.6.0_21\jre\lib\endorsed" containing "jaxb-api.jar" and "jaxws-api.jar". And finally everything seemed to work, but unfortunately only for the 'server-application'. After a lot of searching and copying different files to the endorsed folder and again and again... ...I started to think something is wrong with Netbeans instead of me being stupid. So i downloaded a java decompiler (see PS2 hyperlink 4), and looked in the jar-files in the endorsed folder. Btw, the errors I am recievin in Netbeans are that the javax.xml.ws.Service does not also contain the following constructor:
protected Service(URL wsdlDocumentLocation, QName serviceName, WebServiceFeature[] features)

but only the following constructor:
protected Service(URL wsdlDocumentLocation, QName serviceName)

I set a in netbeans to contain the two jar files in the endorsed folder, but when I expand them and open the 'Service' class, the constructor with 3 arguments is not there. BUT(here comes the strange part) when I decompile the class service in the jar file "jaxws-api.jar" in the endorsed file, it DOES contain that constructor.
So netbeans does not use the jar file referenced to by a library? Or what is going on(and more importantly, how can I fix it)?
I checked where the class is located by "Service.class.getClassLoader()" (pasted it from somewhere I cant remember):
System.out.println(System.getProperty("java.endorsed.dirs"));
final URL location;
final String classLocation = Service.class.getName().replace('.', '/') + ".class";
final ClassLoader loader = Service.class.getClassLoader();
if(loader == null){
    System.out.println("Cannot load the class");
}else{
    location = loader.getResource(classLocation);
    System.out.println("Class " + location);
}

But this gives me the output:"C:\Program Files\Java\jdk1.6.0_21\jre\lib\endorsed" and on the second line "Cannot load the class".
So while running, it cant load the class, but netbeans shows in its projects window in the proyect->Libraries when I expand the library containing the 'endorsed jar-files' to the Service class that it is there. And when I open it I get no error, just not the file containing the right constructor
To summarize: I think that netbeans ignores the jar file I tell it to use and gets its own jar file somewhere, but does not show it to me...
PS: some specs
Product Version: NetBeans IDE 7.0 (Build 201104080000)
Java: 1.6.0_21; Java HotSpot(TM) 64-Bit Server VM 17.0-b17
System: Windows 7 version 6.1 running on amd64;
Tests with Apache Tomcat 7.0.11 (I don't think this is of any use)
Hope to solve this mystery,
Tjen
PS2: i can only post 2 hyperlinks so here are number 3 and 4 (include your own http://):
3: weblogs.java.net/blog/ramapulavarthi/archive/2009/04/tip_for_using_j.html
4: java.decompiler.free.fr/?q=jdgui


text:
Q: how does docker-swarm expose port? After I deploy a docker application using docker-swarm, the application is accessible from $mac-host-ip:8481, and then I noticed the following from my host (Mac),
$ sudo lsof -PiTCP -sTCP:LISTEN |grep 8481
dockerd   1882   root   97u  IPv6 287775      0t0  TCP *:8481 (LISTEN)

$ docker ps --filter publish=8481
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

$ docker ps --filter expose=8481
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

is this expected for compose applications?
thanks!

A: When ingress is used, the port gets published directly on the service, you'll see that under docker service ls under the ports column. The published port is forwarded to the VIP assigned to the service, which (at last check, it's been a while since I've dug) is then forwarded to one of the containers in the service using IPVS.
$ docker service create -p 8080:80 --name nginx-test nginx
mvwgqaolsjbiqsoo4d1ett20v
overall progress: 1 out of 1 tasks
1/1: running   [==================================================>]
verify: Service converged

$ docker service ls | grep nginx-test
mvwgqaolsjbi        nginx-test                 replicated          1/1                 nginx:latest                                       *:8080->80/tcp

You can also go see published ports with a service inspect, e.g. the following loops through all services to show their ports:
docker service ls -q | while read service_id; do
  docker service inspect $service_id -f \
    '{{.Spec.Name}} - {{range .Spec.EndpointSpec.Ports}}{{.PublishedPort}} {{end}}'
done | sort


text:
Q: Show that Möbius functions can be uniquely decomposed as $f=R\circ L \circ T$
A Möbius map is a rational function of the form $$z\mapsto \frac{az+b}{cz+d} \,,$$ where $ad-bc\ne0$ and $a,b,c,d \in \mathbb{C}$.
Show that Möbius functions can be uniquely decomposed as $f=R\circ L \circ T$, where $R$ corresponds to a rigid rotation of the sphere, $L(z)=\alpha z$ for some $\alpha>0$, and $T(z)=z+\beta$, where $\beta\in \mathbb{C}$. (Hint: first consider the case $f(\infty)=\infty$; the general case can be reduced to this case by postcomposing $f$ with a rigid rotation.)

The question didn't really tell me what a rigid rotation of sphere is, by googling I found a rigid rotation is $f(z)=\gamma z$ where $|\gamma|=1$.
Starting with hint, assume $f(\infty)=\infty$, then $c=0$, so what I've been doing is, set $f(z)=(az+b)/d$, and then try to solve the question using simple algebra. For example, I was thinking of picking $\alpha = 1/d$ and $\beta=b$. Then rotate $z/d \mapsto az/d$. But then $\alpha>0$ means it's a real number where $1/d$ is not necessarily a real number.

A: Let $f$ be an arbitrary Möbius transformation, and let $f(\infty) = P$ in the Riemann sphere. If $P=\infty$, then set the rotation $R$ equal to the identity.
If not, first note that if we have two distinct points $P$ and $Q$ on the unit sphere, there is a circle's worth of rotations of the sphere sending $P$ to $Q$. (You can see this either geometrically or with basic linear algebra. The rotations of the sphere must map oriented orthonormal basis to oriented orthonormal basis. Once we assign the value on the first basis vector, the value on the second basis vector is free to be in any circle orthogonal to that value. Assigning this determines the rotation uniquely.) In particular, since $Q=\infty$ is fixed by multiplication by $e^{i\theta}$, if $\rho$ is a rotation of the sphere carrying $P=f(\infty)$ to $\infty$, then all such possible rotations are given by $e^{i\theta}\rho$ for some $\theta$.
Consider, then, the Möbius transformation $\rho^{-1}\circ f$. Since it sends $\infty$ to $\infty$, it must be of the form $z\mapsto az+b$ for some $a,b\in\Bbb C$, $a\ne 0$. (As you observed, we must have $c=0$, and you can absorb the nonzero constant $d$ into $a$ and $b$ by dividing.) There is a unique $\theta$ so that $a=\alpha e^{i\theta}$ for some positive real number $\alpha$. Then $az+b = e^{i\theta}\alpha z + b = e^{i\theta}\alpha(z+\beta)$ for $\beta = b/a$.
Finally, set $R=e^{i\theta}\rho$, $L(z)=\alpha z$, and $T(z) = z+\beta$, with $\rho$, $\alpha$, and $\beta$ as already prescribed. Then $\rho^{-1}\circ f = e^{i\theta}L\circ T$, and so $f = R\circ L\circ T$, and all three functions are uniquely determined.

A: Make $$T(z)=cz+d\\L(z)=\frac 1z\\R(z)=sz+t$$ we have
$$R\circ L \circ T(z)=R\circ L(cz+d)=R\left(\frac{1}{cz+d}\right)=\frac{s}{cz+d}+t=\frac{tcz+td+s}{cz+d}$$ Now solving $tc=a$ and $td+s=b$ in other words $t=\dfrac ac$ and $s=b-\dfrac{ad}{c}$ we are done.


text:
Q: How to add image to sql ? I have converted image to NSdata this is the Query
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;

// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];

// Initialize the results array.
if (self.arrResults != nil) {
    [self.arrResults removeAllObjects];
    self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];

// Initialize the column names array.
if (self.arrColumnNames != nil) {
    [self.arrColumnNames removeAllObjects];
    self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];

// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
    // Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
    sqlite3_stmt *compiledStatement;

    // Load all data from database to memory.
    BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
    if(prepareStatementResult == SQLITE_OK) {
        // Check if the query is non-executable.
        if (!queryExecutable){
            // In this case data must be loaded from the database.

            // Declare an array to keep the data for each fetched row.
            NSMutableArray *arrDataRow;

            // Loop through the results and add them to the results array row by row.
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Initialize the mutable array that will contain the data of a fetched row.
                arrDataRow = [[NSMutableArray alloc] init];

                // Get the total number of columns.
                int totalColumns = sqlite3_column_count(compiledStatement);

                // Go through all columns and fetch each column data.
                for (int i=0; i<totalColumns; i++){
                    // Convert the column data to text (characters).
                    char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);

                    // If there are contents in the currenct column (field) then add them to the current row array.
                    if (dbDataAsChars != NULL) {
                        // Convert the characters to string.
                        [arrDataRow addObject:[NSString  stringWithUTF8String:dbDataAsChars]];
                    }

                    // Keep the current column name.
                    if (self.arrColumnNames.count != totalColumns) {
                        dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
                        [self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
                    }
                }

                // Store each fetched data row in the results array, but first check if there is actually data.
                if (arrDataRow.count > 0) {
                    [self.arrResults addObject:arrDataRow];
                }
            }
        }
        else {
            // This is the case of an executable query (insert, update, ...).

            // Execute the query.
            BOOL executeQueryResults = sqlite3_step(compiledStatement);
            if (executeQueryResults == SQLITE_DONE) {
                // Keep the affected rows.
                self.affectedRows = sqlite3_changes(sqlite3Database);

                // Keep the last inserted row ID.
                self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
            }
            else {

                NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
            }
        }
    }
    else {

        NSLog(@"%s", sqlite3_errmsg(sqlite3Database));
    }

    sqlite3_finalize(compiledStatement);

}

sqlite3_close(sqlite3Database);
}

and this i am inserting the the value
NSString *query;
if (self.recordIDToEdit == -1) {
    query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', '%@', %d )", self.txtFirstname.text, self.txtLastname.text, [self.txtAge.text intValue]];

}
else{
    query = [NSString stringWithFormat:@"update peopleInfo set firstname='%@', lastname='%@', age=%d where peopleInfoID=%d", self.txtFirstname.text, self.txtLastname.text, self.txtAge.text.intValue, self.recordIDToEdit];
}

A: You just don't need to add image in database. put your image in HomeDirectory and just save ImageUrl in database. so you can manage it easily.

A: I give you detailed answer.If you want to save image into database kindly save the image into document directory first then pass the document directory path to the SQLite db.
I have separate file(NSObject Class) for saving image into document directory.
PhotoPath.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface PhotoPath : NSObject

+(NSString*)getSavedPhotoPath:(UIImage*)image;
+(NSString*)getphotopath;
+(NSString *)applicationDocumentsdirectory;
+(void)ensureDirs:(NSString*)path;
+(NSString*)getCurrentTime;
+(NSString*)getCurrentDate;

@end

PhotoPath.m
#import "PhotoPath.h"

@implementation PhotoPath

+(NSString*)getSavedPhotoPath:(UIImage*)image
{
    NSString *path =nil;
    NSString *file_name = [[self getCurrentDate]stringByAppendingString:[self getCurrentTime]];
    file_name =[file_name stringByAppendingPathExtension:@"jpeg"];
    path =[[self getphotopath]stringByAppendingPathComponent:file_name];
    NSData *imgData =UIImageJPEGRepresentation(image, 0.4);
    [imgData writeToFile:path atomically:YES];
    return path;
}

+(NSString*)getphotopath
{
    //CREATE PHOTO PATH FOR SAVED IMAGES
    NSString *path = [[self applicationDocumentsdirectory]stringByAppendingPathComponent:@"photosOne"];
    [self ensureDirs:path];
    return path;
}

+(NSString *)applicationDocumentsdirectory
{
    int i=0;
    NSArray *paths1 =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath =([paths1 count] >i) ? [paths1 objectAtIndex:i] : nil;
    return basePath;
}

+(void)ensureDirs:(NSString*)path
{
    //Get Directory in FileManager
    NSFileManager *fileManager =[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path])
     return;
   [fileManager createDirectoryAtPath:path  withIntermediateDirectories:NO attributes:nil error:nil];
}

+(NSString*)getCurrentTime
{
    //Get Current Time for saving Images
    NSString *path =nil;
    NSDateFormatter *timeFormatter =[[NSDateFormatter alloc]init];
    [timeFormatter setDateFormat:@"HH:mm:ss.SSS"];
    NSDate *now = [[NSDate alloc]init];
    NSString *str_time = [timeFormatter stringFromDate:now];
    NSString *curr_time;
    curr_time =[str_time stringByReplacingOccurrencesOfString:@"." withString:@""];
    path = [NSString stringWithFormat:@"%@",curr_time];
    return  path;
}

+(NSString*)getCurrentDate
{
    NSString *today =nil;
    NSDateFormatter *dateFormatter1;
    dateFormatter1 =[[NSDateFormatter alloc]init];
    [dateFormatter1 setDateFormat:@"d MMM yyyy"];
    NSDate *now =[[NSDate alloc]init];
    NSLocale *usLocale =[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    [dateFormatter1 setLocale:usLocale];
    NSString *str_date =[dateFormatter1 stringFromDate:now];
    today=[NSString stringWithFormat:@"%@",str_date];
    return today;
}

@end

ViewController.h
#import <UIKit/UIKit.h>
#import "PhotoPath.h"
@interface ViewController : UIViewController<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
   PhotoPath *path;
}
@property(nonatomic,retain)NSMutableArray *arrImg;
@property (strong, nonatomic) IBOutlet UIImageView *imgPick;
- (IBAction)actionSaveImageIntoSQLite:(id)sender;
@end

ViewController.m
#import "ViewController.h"
interface ViewController ()
@end
@implementation ViewController
@synthesize arrImg,imgPick;

- (void)viewDidLoad
{
  [super viewDidLoad];
   UITapGestureRecognizer *tapImage =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapDetect)];
   tapImage.numberOfTapsRequired =1;
   tapImage.numberOfTouchesRequired =1;
   imgPick.userInteractionEnabled =YES;
   [imgPick addGestureRecognizer:tapImage];
}

-(void)tapDetect
{
    UIImagePickerController *picker =[[UIImagePickerController alloc]init];
    picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate =self;
    [self presentViewController:picker animated:NO completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
    imgPick.image=image;
    [arrImg addObject:image];
    picker.delegate =self;
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)actionSaveImageIntoSQLite:(id)sender
{
   NSMutableArray *arrAllImgPath =[[NSMutableArray alloc]init];
   for (UIImage *img in arrImg)
   {
      NSString *strImgPath =[PhotoPath getSavedPhotoPath:img];
      [arrAllImgPath addObject:strImgPath];
   }
   NSLog(@"The path is - %@",arrAllImgPath);
   for (int i=0; i<[arrAllImgPath count]; i++)
   {
      NSString *strImgPathURL = [arrAllImgPath objectAtIndex:i];
      [SqliteDB insertDataintoDB:strImgPathURL];
   }
}
@end

When you fetch image from SQLite DB
NSString *localPath=[NSString stringWithFormat:@"%@",[arrSQLiteDBImg objectAtIndex:i]];
NSURL *urlString=[NSURL fileURLWithPath:localPath];
NSData *data = [NSData dataWithContentsOfURL:urlString];
UIImage *img = [[UIImage alloc] initWithData:data] ;


text:
Q: Python SQLite3 AUTOINCREMENT Error I am making a shopping list program for my mum with Python, SQLite3 and Bottle,
I am making a table to put all my items into but the item_id with AUTOINCREMENT on the column it doesn't work:
c.execute("""CREATE TABLE categories (
            category_id INTEGER NOT NULL,
            category_name TEXT PRIMARY KEY NOT NULL)""")

c.execute("""CREATE TABLE products (
            item_name TEXT PRIMARY KEY NOT NULL,
            item_category_id INTEGER NOT NULL)""")

c.execute("""CREATE TABLE shopping_products (
            item_id INTEGER AUTOINCREMENT,
            item_name TEXT PRIMARY KEY NOT NULL,
            item_category_id INTEGER NOT NULL,
            item_quantity INTEGER NOT NULL,
            item_date INTEGER NOT NULL)""")

On the shopping_products table the AUTOINCREMENT keep returning this error:
sqlite3.OperationalError: near "AUTOINCREMENT": syntax error

A: A few points:

*

*Are you sure you need AUTOINCREMENT? It's not normally required in SQLite:

*

*The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.

*In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer.

*On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.

*If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic ROWID assignment algorithm to prevent the reuse of ROWIDs over the lifetime of the database. In other words, the purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from previously deleted rows.

As long as you're not worried about reusing ROWIDs from previously deleted rows INTEGER PRIMARY KEY should be fine.

*If you do want to use AUTOINCREMENT with SQLite it must be on an INTEGER PRIMARY KEY column, e.g.
item_id INTEGER PRIMARY KEY AUTOINCREMENT

*Your shopping_products table has a TEXT PRIMARY KEY on item_name.
You can't have two primary keys, so if you want item_id to have AUTOINCREMENT you'll need to stop using item_name as your primary key. An item name would be a strange primary key anyway.


text:
Q: Can't go through a Haskell tutorial I'm quite new to Haskell – I know its syntax and not really much more, so I assumed the best way to get a bit more information is to follow some tutorials from Haskell wiki.
I found this one:
https://wiki.haskell.org/How_to_write_a_Haskell_program
Unfortunatelly, when I reach item (2.9), my results diverge from what's shown on the website. When I type cabal install --enable-tests, I get:
Resolving dependencies...
Configuring haq-0.1.0.0...
Building haq-0.1.0.0...
Preprocessing executable 'haq' for haq-0.1.0.0...
Linking dist/dist-sandbox-2a06ecba/build/haq/haq ...
Preprocessing test suite 'tests' for haq-0.1.0.0...
<command line>: cannot satisfy -package-id haq-0.1.0.0-inplace
    (use -v for more information)
Failed to install haq-0.1.0.0
cabal: Error: some packages failed to install:
haq-0.1.0.0 failed during the building phase. The exception was:
ExitFailure 1

There are really two questions:

*

*How can I solve this problem and make it compile?

*Where does this -inplace appended to my package's version come from? I tried adding it in cabal file, but that didn't help either.
I'll be happy to post more details if needed. My code is pretty much the same as the instructions in the tutorial say.
EDIT
Here's my .cabal file:
name:                haq
version:             0.1.0.0
description:         Super cool mega lambdas
license:             GPL
author:              Alojzy Leszcz
build-type:          Simple
cabal-version:       >=1.10

executable haq
  main-is:             Haq.hs
  build-depends:       base >=4.8 && <4.9
  default-language:    Haskell2010

test-suite tests
  ghc-options:         -Wall
  default-extensions:  OverloadedStrings
  type:                exitcode-stdio-1.0
  main-is:             HSpecTests.hs
  build-depends:       base,
                       haq,
                       hspec >= 1.8
  default-language:    Haskell2010

A: The haq in the build-depends section refers to a library, but your .cabal file does not specify how to build a library - ie. it doesn' have a library section.
You'll see what the library section should look like in section 3.2 of that wiki page: (link)

A: OK - managed to come up with the valid configuration. Thanks for the hint.
Here's my cabal file:
-- Initial haq.cabal generated by cabal init.  For further documentation,
-- see http://haskell.org/cabal/users-guide/

name:                main
version:             0.1.0.0
license:             GPL-2
license-file:        LICENSE
author:              Bogdan Baranski
build-type:          Simple
cabal-version:       >=1.10

library
  build-depends:       base >=4.8 && <4.9
  exposed-modules:     Main
  default-language:    Haskell2010

executable main
  main-is:             Main.hs
  build-depends:       base >=4.8 && <4.9
  default-language:    Haskell2010

test-suite tests
  ghc-options:         -Wall
  default-extensions:  OverloadedStrings
  type:                exitcode-stdio-1.0
  main-is:             HSpecTests.hs
  build-depends:       base,
                       main,
                       hspec >= 1.8
  default-language:    Haskell2010

Also, I had to rename file to "Main.hs" in order to make it consistent with the module defined inside (I noticed that Haskell is very sensitive about this convention: a module "Module" must be defined in a file "Module.hs").


text:
Q: Upgrade processor in Dell Inspiron E1705 I'm looking to upgrade the processor in my older Dell Inspiron E1705.  The laptop is currently running an Intel T2400 @ 1.83GHZ.  First, is this something that is even possible to do?  Second, what processors are still for sale that would be a great upgrade?

A: Check the motherboard, look for what does it support. Then just go to eBay or a trusted site where you can buy used mobile CPUs and get one which is supported by the motherboard/chipset.
Also, check with Google. Try typing Inspiron E1705 cpu upgrade and such. Someone may have done this already and got some info about what works and what does not.


text:
Q: How do you select form elements in JQuery based upon an html table? I am working on some ASP.NET web forms which involves some dynamic generation, and I need to add some onClick helpers on the client side.  I have a basic outline of something working, except for one huge problem.
There are multiple HTML tables, each generated by a different ASP.NET web control.  Each table can contain overlapping field names, which is causing a problem with my JQuery click event handlers.  The click event handler is linking to unintended form fields in addition to the intended form field.
I have provided a simplified sample version of the code below.  This code is trying to set the value of textbox box1 when a particular radiobutton is selected in the table with id=thing1.  Obviously, the jquery code will be triggered for the form fields in both tables.
The tables are dynamically added to the webpage based upon different conditions.  It is possible that no tables will be loaded, only 1 table, or both tables might load.  In the future, other tables could be added.  Each table comes from a different .net web control.
Other than renaming the form fields to make sure they are unique across all user controls, is there a way to have JQuery act only on the intended form fields?  In other words, could the table ID be incorporated into the JQuery code in a manner that does not become a nightmare to maintain later?

        <radiobuttonlist id="radio1"/>
          <listitem>yes</listitem>
          <listitem>no</listitem>

        <textbox id="box1"/>

        <radiobuttonlist id="radio1"/>
          <listitem>yes</listitem>
          <listitem>no</listitem>

        <textbox id="box1"/>

A: Apply classes to the tables, then specify your jquery selector to look for the form fields within a specific table, e.g. i think this would work
$(".table1 [id$=radio1_0]")

youthen just need to set the css class propertyon the relevent controls.

A: There are several ways to traverse the DOM using jQuery, so you can get a reference to the proper relative element.
One way is to traverse up to the parent table element, then .find() the relative element you're looking for.


text:
Q: How would I return this "clubName" array to ensure the "choice -1" is used I wanted to pass the "result" of "You Chose : abc" to a return type, so I can then pass it into my serialized method, so that I can then serialize that chosen team. I know how to return an array, but how would I return an array -1 ?
Code snippets are as follows :
public class Display{
public String[] printGreeting(int choice, String[] clubName) {

    result = clubName;
    System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

    if (choice >= 1 && choice <= 20) {
    System.out.println("You chose: " + clubName[choice - 1]); // return the clubName -1
    }
    return result; // how to declare return statement ?
    }
}

Here is my serialize code, not sure how I would pass the array, via an alias or use object ?
public class Serialize
{
   public void Serialize() // receive return type from printGreeting();
   {

// how to put object info into files, rather than declare here ?

     try
      {
         FileOutputStream fileOut = new FileOutputStream("/home/cg/root/club.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
     out.writeObject(club);

         out.close();
         fileOut.close();

      System.out.printf("Serialized data is saved in C:/tmp/club.ser");
      }catch(IOException i)
      {
          i.printStackTrace();
      }

   }
}

Any help with this would be greatly appreciated :)

A: Here you declare to return an array of String[]:
public String[] printGreeting(int choice, String[] clubName) {
    // ↑ here you say this method MUST return an array if Strings

What you need is

*

*assign the user's choice to returned variable

*return just ONE String

public String printGreeting(int choice, String[] clubName) {
    result = clubName;
    System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

    if (choice >= 1 && choice <= 20) {
        // assign choice to result
        result = clubName[choice - 1];
        // print choice
        System.out.println("You chose: " + result); // return the clubName -1
    }

    // return the chosen club name
    return result;
}

Actually, I don't know why result is a class attibute (but i cannot see declaration),  what does not make much sense if you want to return it, I will code the method as:
public String printGreeting(int choice, String[] clubName) {
    System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); // ??

    if (choice >= 1 && choice <= 20) {
        choice --; // if choice is valid, get the array position.
        // print choice
        System.out.println("You chose: " + clubName[choice]);
        return clubName[choice];
    }

    // if the choice is not correct, return null or "" as you want
    return null;
}

UPDATE

Could anyone advise how I would pass that returned String to my serialize method, I think I know how to serialize it, but not 100% sure on parameter passing.

*

*I don't get exactly what you want to achieve, maybe would be better to rephrase question with your target clear, and your tries.

*Serialize (shortly), in Java is make an object's attributes convertible to Strings, then, a String either an String[] array does not need to be serialized.

*As long as Display methods are not static, you must create an instance of Display to execute as follow:
public class Main {
    public static void main(String [] args) {

        // create an instance of Display class
        Display d = new Display();

        // get the needed values to pass to printGreeting method:
        String[] clubs = {"club one", "club two" // put 20 clubs

        // get the index from the user
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number 1: ");
        while (!sc.hasNextInt()) sc.next();
        int choice = sc.nextInt();

        // call the method and get the return:
        String result = d.printGreeting(choice, clubs)

        // then get a serializer and execute method:
        Serialize s = new Serialize();
        s.serialize(result);
    }
}

*change the method Serialize.serialize() to Serialize.serialize(String) as follows:
public class Serialize
{
    public void serialize(String club)
    //                    ↑ receive return type from printGreeting();
    {
         // your serialize code
    }
}

A: What do you want to return? The club name (String) or the whole array?
It's not clear in your code if result is an array or a String, you simply say result = clubName. If it's an array it should be String[] result = clubName;, if you want to return a String it should be String result = clubName[choice -1];, in that case you have to change the method to public String printGreeting(int choice, String[] clubName) and you can return result;


text:
Q: Adjust the Bounding Box on new Master shapes I want to create custom master shapes in a stencil. Specifically, I'm creating valves similar to those found in Process Engineering > Valves and Fittings
I want the bounding box when you drop the shape to be a perfect square around the center of the valve, similar to the Powered Valve shape. Once I get this to work, it should align properly with other valves.

A: If you want to build your shape from scratch:

*

*Create a rectangle the size of your intended bounding box.

*Click Home / Arrange / Group / Convert to Group

*Open the ShapeSheet of you new group shape and set the LockCalcWH cell in the Protection section to 1 (this will prevent the bounding box from resizing when geometry sits outside of the intended area.)

*Position your valve shape over the group shape then drag select all of them and a click Group / Add to Group
If you're wanting to modify the 'wrong' shape from your image, (ie where the alignment box completely encloses all of the sub-shapes / geometry) - then you'll need to change the geometry of sub-shape sizes which are probably defined relative to the size of the outer (group) shape.  If it is already a group shape, you might find it easier to ungroup and then follow the steps above to regroup.
Bear in mind that if you ungroup you will lose any Shape Data and referencing cells defined in the group shape and these will need to be reapplied to the new group.


text:
Q: After Linux resumes from sleep, the screen only turn on when I move the mouse (or when a visual component changes) I bought a recent notebook with the settings mentioned below and I couldn't make any Linux work on it, they all have the same behavior after returning from the suspension of only turning on the screen when a visual component changes, e.g. a new character entered by the keyboard; cursor position by mouse/touchpad movement; new log lines appearing in terminal; progress bar loading (this one keeps the screen lit without blinking); when the browser page is loading or a video is playing (also keeps the screen lit without blinking).
Avell A57 HYB Notebook Technical Specifications:

*

*Processor: i7-12700H

*Video Card: GTX 1650 Black 144 Hz

*Memory: 32 GB (2x16)

*Storage: NVMe 500GB

I have already tried the following:

*

*Different distributions: openSUSE, Ubuntu, Pop!_OS

*Different Desktop Environments: Gnome and KDE

*Different Display Server Protocols: X11 and Wayland

*Different video drivers: generic and official from Nvidia

Besides these isolated changes I tried to follow the openSUSE documentation to use only NVIDIA or only Intel.

*

*https://en.opensuse.org/SDB:NVIDIA_drivers

*https://en.opensuse.org/SDB:NVIDIA_SUSE_Prime
As prerequisites, I installed some packages and disabled Wayland.
# zypper install x11-video-nvidiaG06 nvidia-glG06 suse-prime bbswitch bbswitch-kmp-default
# sed -ri 's/#?WaylandEnable=.*/WaylandEnable=false/' /etc/gdm/custom.conf

Then I tried using intel, intel2 and offload modes. Both modes made that when trying to get out of sleep the screen was just black and it was necessary to restart the system. After using prime-select unset to remove the configuration the behavior was still black screen.
The log of these tests follows (generated with prime-select log-view):
##SUSEPrime logfile##
[ 11:15:01 ] Boot: setting-up  card
[ 11:15:01 ] HotSwitch: completed!
[ 11:26:39 ] user_logout_waiter: started
[ 11:30:13 ] user_logout_waiter: X restart detected, preparing switch to intel
[ 11:30:14 ] NVIDIA card will be switched off, NVIDIA offloading will not be available
[ 11:30:14 ] trying switch OFF nvidia: [bbswitch] NVIDIA card is OFF
[ 11:30:14 ] Intel card correctly set
[ 11:30:14 ] HotSwitch: starting Display Manager
[ 11:30:15 ] HotSwitch: completed!
[ 11:41:07 ] Boot: setting-up intel card
[ 11:41:07 ] NVIDIA card will be switched off, NVIDIA offloading will not be available
[ 11:41:07 ] trying switch OFF nvidia: [bbswitch] NVIDIA card is OFF
[ 11:41:07 ] Intel card correctly set
[ 11:41:07 ] HotSwitch: completed!
[ 11:47:05 ] Boot: setting-up intel card
[ 11:47:05 ] NVIDIA card will be switched off, NVIDIA offloading will not be available
[ 11:47:05 ] trying switch OFF nvidia: [bbswitch] NVIDIA card is OFF
[ 11:47:05 ] Intel card correctly set
[ 11:47:05 ] HotSwitch: completed!
[ 11:49:10 ] user_logout_waiter: started
[ 11:49:19 ] user_logout_waiter: X restart detected, preparing switch to intel2
[ 11:49:19 ] NVIDIA card will be switched off, NVIDIA offloading will not be available
[ 11:49:20 ] trying switch OFF nvidia: [bbswitch] NVIDIA card is OFF
[ 11:49:20 ] Intel card correctly set
[ 11:49:20 ] HotSwitch: starting Display Manager
[ 11:49:20 ] HotSwitch: completed!
[ 11:53:20 ] Boot: setting-up intel2 card
[ 11:53:20 ] NVIDIA card will be switched off, NVIDIA offloading will not be available
[ 11:53:20 ] trying switch OFF nvidia: [bbswitch] NVIDIA card is OFF
[ 11:53:20 ] Intel card correctly set
[ 11:53:20 ] HotSwitch: completed!
[ 11:58:49 ] user_logout_waiter: started
[ 11:58:57 ] user_logout_waiter: X restart detected, preparing switch to offload
[ 11:58:58 ] Using default intel modesetting driver for offloading.
[ 11:58:58 ] Unloading bbswitch and switching nvidia ON...
[ 11:58:58 ] Loading nvidia_modules
[ 11:58:59 ] Adding support for NVIDIA Prime Render Offload
[ 11:58:59 ] Intel card correctly set
[ 11:58:59 ] HotSwitch: starting Display Manager
[ 11:59:00 ] HotSwitch: completed!
[ 12:04:38 ] Boot: setting-up offload card
[ 12:04:38 ] Loading nvidia_modules
[ 12:04:39 ] Adding support for NVIDIA Prime Render Offload
[ 12:04:39 ] Intel card correctly set
[ 12:04:39 ] HotSwitch: completed!

Finally I tried to use nvidia mode and the result of this test was the notebook does not come back from sleep and does not start the graphical interface anymore after restart (it doesn't even show the login screen). Strangely the log says that bbswitch was not loaded despite being installed.
localhost:~ # prime-select nvidia
nvidia catched
Preparing first configuration
bbswitch not loaded

If you want energy saving bbswitch should be loaded in intel mode.
For this package 'bbswitch' needs to be installed on your system.
Or make use of DynamicPowerManagement on Turing GPUs or later by
switching to suse-prime's 'offload' or 'nvidia' mode.
Logout to switch graphics

The other TTYs (e.g. ctrl-alt-F3) have a flashing underscore. Entering recovery mode got stuck in the boot process as in the code below.
[    3.071418][   T537] RIP: 0033:0x7f6d3354f70e
[    3.071424][   T537] Code: 48 8b 0d 05 f7 0c 00 f7 d8 64 89 01 48 83 c8 ff c3 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 49 89 ca b8 af 00 00 00 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 8b 0d d2 f6 0c 00 f7 d8 64 89 01 48
[    3.071431][   T537] RSP: 002b:00007fff7d36ac68 EFLAGS: 00000246 ORIG_RAX: 00000000000000af
[    3.071437][   T537] RAX: ffffffffffffffda RBX: 0000564aff52fcf0 RCX: 00007f6d3354f70e
[    3.071441][   T537] RDX: 00007f6d3368105d RSI: 000000000069cd6b RDI: 00007f6d31e79010
[    3.071446][   T537] RBP: 00007f6d3368105d R08: 0000000000261000 R09: 85ebca77c2b2ae63
[    3.071450][   T537] R10: 0000000000041631 R11: 0000000000000246 R12: 0000000000020000
[    3.071454][   T537] R13: 0000000000000000 R14: 0000564aff5697f0 R15: 0000000000000000
[    3.071460][   T537] </TASK>
[    3.071463][   T537] ---[ end trace 0000000000000000 ]---
[    3.970405][   T537] [drm] Initialized i915 1.6.0 20201103 for 0000:00:02.0 on minor 1
[    3.973620][   T537] ACPI: video: Video Device [GFX0] (multi-head: yes  rom: no  post: no)
[    3.974339][   T537] input: Video Bus as /devices/LNXSYSTM:00/LNXSYBUS:00/PNP0A08:00/LNXVIDE0:00/input/input7
[    3.978723][   T139] fbcon: i915drmfb (fb0) is primary device
[    3.985978][   T139] Console: switching to colour frame buffer device 240x67
[    3.996316][   T139] i915 0000:00:02.0: [drm] fb0: i915drmfb frame buffer device


text:
Q: Highlight UITableViewCell on touch event in a composite UIView I have a UITableViewCell which is made up of a child container UIView and some other child components, such as labels, background, icons, etc...
Each UIImageView has also an highlight image set in Xcode IB.
The cell is assembled in a UIStoryBoard and has a segue connected to it, therefore I am not using the typical didSelect method of delegate.
This is the hierarchy:
UIViewController (serving as UITableView delegate)
--> UIView (main view)
    --> UITableView
        --> UItableViewCell
            --> UIView
                --> (several UIView, image, label, etc..)

I wonder how can I have my cell selected in this scenario. It is fine for me to highlight the whole cell, but I am also interested in knowing how to make a specific select.
For select/highlighting I mean, forget the standard blue or grey selection, but rather, recall all those specific images I mark as 'highlighted' in IB.
Platform target is iOS 5.
thanks

A: Your UIViewController file should implement UITableViewDelegate and UITableViewDataSource
@interface NameOfViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

Then you can override the table's methods. It sounds like you want to override didSelectRowAtIndexPath. I'm still a little unclear on exactly what you want to do, but it sounds like you will just use this method and either tell the cell it's highlighted or pass a message to the cell telling it to do something (like change its images). You will also need to subclass your cell and load it from a .xib file if you want to do this. Sorry if this sounds like a lot of work, but table views require a lot of code for customization beyond very basic stuff.


text:
Q: Save multiple ggplots using a for loop I want to automate the generation of a number of ggplots:
Generic dataset:
mydata<-data.frame(matrix(rnorm(100),ncol=5))
names(mydata)<-c("Tijd","X1","X2","X3","X4")

Specify variables to include:
Start=2
Stop=5

List to save the plots in:
gvec<-vector("list",length=length(Start:Stop))

Create plots:
for(i in Start:Stop){
  graphy<-ggplot(mydata,aes_string(x="Tijd",y=names(mydata)[i]))+geom_point()+mytheme
  gvec[[i-Start+1]]<-graphy
}

Save plots:
for(i in Start:Stop){
tiff(paste0("Test/Residu/Plots/Prei/mydata.",names(mydata)[i],"09.14.tiff"),width=720,height=720)
gvec[[i-Start+1]]
graphics.off()
}

The list of plots is generated; I can save the plots manually as well. However, using the last loop the files generated are all blank. I can't figure out the reason for this.
As per Roland's suggestion I tried
print(gvec[[i-Start+1]]) but I still get blank files as output.

A: You can create and export the plots within the same loop. The combined code would be:
for(i in Start:Stop){
  graphy<-ggplot(mydata,aes_string(x="Tijd",y=names(mydata)[i]))+geom_point()+mytheme
  tiff(paste0("Test/Residu/Plots/Prei/mydata.",names(mydata)[i],"09.14.tiff"),width=720,height=720)
  print(graphy)
  dev.off()
}

For a general case with stacked data, where the id variable correspond to the subgroup (country, individual, etc)):
for (i in 1:10) {
  mydata_id <- subset(mydata, id == i) # subselect group
  p <- ggplot(mydata_id, aes(x, y)) + geom_line() # create graph
  png(paste("plot_", i, ".png", sep = ""), width=600, height=500, res=120) # start export
  print(p)
  dev.off() # finish export
}

A: You can also use the ggsave function from ggplot2 library.
library(ggplot2)
data("iris")

# list of values to loop over
  uniq_species = unique(iris$Species)

# Loop

for (i in uniq_species) {

  temp_plot = ggplot(data= subset(iris, Species == i)) +
                  geom_point(size=3, aes(x=Petal.Length, y=Petal.Width )) +
                  ggtitle(i)

  ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}

A: Here is a fully reproducible example of creating ggplots in a loop.
# Plot separate ggplot figures in a loop.
library(ggplot2)

# Make list of variable names to loop over.
var_list = combn(names(iris)[1:3], 2, simplify=FALSE)

# Make plots.
plot_list = list()
for (i in 1:3) {
    p = ggplot(iris, aes_string(x=var_list[[i]][1], y=var_list[[i]][2])) +
        geom_point(size=3, aes(colour=Species))
    plot_list[[i]] = p
}

# Save plots to tiff. Makes a separate file for each plot.
for (i in 1:3) {
    file_name = paste("iris_plot_", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
}

# Another option: create pdf where each page is a separate plot.
pdf("plots.pdf")
for (i in 1:3) {
    print(plot_list[[i]])
}
dev.off()


text:
Q: Summon out of the world I have a command block with a /summon command in. When I run the command, it gives the result Cannot summon the object out of the world. However, when I move the command block closer to the summon location, it succeeds. Is there any way I can stop this (without moving the command block)?

A: The problem you're encountering is that the command block is trying to put an entity into an unloaded chunk. The only possible solution is to run the command when the player gets near the summon location.

A: You can force the chunks to load by using the /spreadplayers command to move an 'anchor' entity to that location first before summoning.

*

*Summoning the anchor.
/summon ArmorStand ~ ~1 ~ {Tags:["anchor"]}

*Spreading that anchor near the location.
/spreadplayers X Z 0 1 false @e[type=ArmorStand,tag=anchor]

*Summoning the mob.
/summon Villager X Y Z

Alternatively you could summon the mob at the spawn chunks, spread it to the desired location, and use a /tp command to reposition it correctly. However, if the chunks are already loaded by the player, that spread entity may not render immediately.


text:
Q: How do I use pcre_study with pcrecpp? I'm using Google's C++ interface to PCRE to match a single regex multiple times (possibly thousands of times). From reading the PCRE manual, it seems like a good idea to let PCRE 'study' (spend time optimizing) the regex, however, I can't seem to find a way to do that with the C++ wrapper. The pcrecpp.h doesn't mention studying at all.
Is using pcre_study() worthwile, and if so, how can it be combined with pcrecpp and its RE class?

A: From a quick scan of the PCRE++ source code, it appears that "studying" is impossible with this API because the compiled RE (pcre*) member of the RE wrapper object is private and there's no way to get it out or reset it.
If you want to know whether the studying optimization is worthwhile with your REs, the easiest option that I see is to copy pcrecpp.{cc,h} into your project and hack it in; the C++ API is just some thin wrapper code. You might even want to submit a patch upstream if, like me, you like to litter open source projects with your name and copyright ;)

A: For the benefit of people hitting on this question from a web search, I will point out that the ability to "study" an RE has been removed from PCRE2:

*Explicit "studying" of compiled patterns has been abolished - it now always
happens automatically. JIT compiling is done by calling a new function,
pcre2_jit_compile() after a successful return from pcre2_compile().

Reference: https://lists.exim.org/lurker/message/20150105.162835.0666407a.en.html


text: Q: Do gerrit code review support .gitattributes settings? do gerrit code review support .gitattributes? Does it support unset diff of files? Is there a setting that needs to be activated to enable it ? I tried unsetting diff on some files, it works fine on git diff, but still shows the diff on the change.


text:
Q: .NET WebClient: Where is DownloadString? I'm probably missing something here, but when I use WebClient and look for the DownloadString method (as found in a book example), I only see DownloadStringAsync.
What Import am I missing?

A: Are you using Silverlight? Only the Async version is available in Silverlight.  Otherwise, the .NET 4 Framework and below (except 1.x) have the DownloadString() method.
http://msdn.microsoft.com/en-us/library/ms144200.aspx

A: as indicated here, it looks like the DownloadString method is part of System.Net.

A: Well, I think you're creating a Silverlight application. In that case it is a normal thing: you will find usually only asynchronous methods in Silverlight applications; this makes your UI more responsive because operations will be executed in another thread without blocking it.
Try to create a desktop application (Console Application, WPF, etc.) and you will find the method you're looking for.


text: Q: Convertion OpenApi 3.0 yaml / json into word document I would like to convert openAPI yaml / json file into word document. Is there any way how to do it? I found only json to pdf solutions which look not very nice.


text:
Q: Rewrite all files from folder to another folder I want redirect all requested files from folder-a to folder-b. E.g. http://www.yoursite.com/folder-a/index.php to http://www.yoursite.com/folder-b/index.php.
How can I do that? I have verified if mod_rewrite works with this code:
RewriteEngine On
RewriteRule ^google.html$ http://www.google.com/ [R=301]

The structure on the webspace is the following:
.htacces
|-folder-a
|-folder-b
But if I want my folder redirect
RewriteEngine On
RewriteRule ^/folder-a/(.*)$ http://www.yoursite.com/folder-b/$1 [L,R=301]

the redirect doesn't work if I input the following URL:
http://www.yoursite.com/folder-a/
http://www.yoursite.com/folder-a/index.php
The redirect doesn't take place. I stay on the same page ... What I'm doing wrong? I also tried it with this htaccess:
Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^folder-a(.*)$ http://www.yoursite.com/folder-b$1 [L,R=301]

</IfModule>

If all this works I want to exclude some files. Eg. with this htaccess:
RedirectPermanent /folder-a/info.php /folder-b/new-info.php

Edit:
Now I tried this htaccess
redirectMatch 301 ^/folder-a/ http://www.yoursite.com/folder-b

This works, but I need something which takes the whole path and rewrite it to the new folder.
This for example doesn't work:
RewriteRule ^folder-a/(.*)$ folder-b/$1

Solution
I had an old htacess file in my folder-a so the redirect didn't worked. This is my final htaccess:
Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^folder-a/excludefile1.php http://www.yoursite.com/folder-b/newnameforfile1.php [L,R=301]
RewriteRule ^folder-a/excludefile2.php http://www.yoursite.com/folder-b/newnameforfile2.php [L,R=301]
RewriteRule ^folder-a/(.*)$ http://www.yoursite.com/folder-b/$1 [L,R=301]

</IfModule>

A: You probably need to put both rules in place: one for the empty folder and one for other files, and then the catch-all at the bottom.  This is not tested:
RewriteEngine On

RewriteRule ^folder-a/info.php http://www.yoursite.com/folder-b/new-info.php [L,R=301]
RewriteRule ^folder-a/ http://www.yoursite.com/folder-b/ [L,R=301]
RewriteRule ^folder-a/(.*)$ http://www.yoursite.com/folder-b/$1 [L,R=301]


text:
Q: Store PHP/SQL foreach form items in variables Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
    try {
        $result = $conn->query("SELECT * FROM $tableName");
                return ( $result->rowCount() > 0)
            ? $result
            : false;
    } catch(Exception $e) {
        return false;
    }
}

//form.php
<form action "index.php" method "POST" name='form1'>

      Name
      Number Entered

      <?php foreach($users as $user) : ?>

          <?php echo $user['FullName']; ?>

          <input type="int" name="NumberedEntered">

    <?php endforeach; ?>

  <input type="submit" value="submit">
</form>

//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
    echo $_REQUEST['NumberedEntered'];
    echo $_REQUEST['FullName'];
}

A: The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">

But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.

Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
  <form action="index.php" method="POST">

        <?php echo $user['FullName']; ?>
        <input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />

        <input name="NumberedEntered"/>

        <input type="submit" value="submit"/>

  </form>
<?php endforeach; ?>


text:
Q: What does "[w for w in word_tokens if..." mean in Python? I have a general question about the syntax used in Python. I am very new to programming so this might seem like a noob question, but I'm using pythons nltk, and in that there is a command which appears as follows...
word_tokens = word_tokenize(example_sent)

filtered_sentence = [w for w in word_tokens if not w in stop_words]

filtered_sentence = []

for w in word_tokens:
if w not in stop_words:
    filtered_sentence.append(w)

Is anyone able to explain the logic behind the "w for w in word_tokens"?
I have seen this in several forms, so can anyone break down what is happening here in the "X for X in X"?
Would just like some clarity on the concept used here, thanks in advance!

A: filtered_sentence = [w for w in word_tokens if not w in stop_words]

is equivalent to:
filtered_sentence = []
for w in word_tokens:
    if not w in stopwords:
        filtered_sentence.append(w)


text:
Q: delaying the sending of email messages without using Thread.Sleep c# I have a for loop which loops through and sends an email each loop. Right now im using thread.sleep() but I want the user to still be able to interact with the program, just delap that one loop. Is it possible to do this without using thread.sleep?

A: Are you running the loop on the UI thread?  If so, just use Task.Factory.StartNew to run your loop in a different thread. If you need to delay the email sending at that time, put a Thread.Sleep before you actually begin looping.
It will look something like this:
private void OnButtonClick(object sender, EventArgs e)
{
    //This code happens on the UI thread
    Task.Factory.StartNew(SendEmails);
}

private void SendEmails()
{
    Thread.Sleep(500);

    foreach(var email in emailAddresses) {
        SendEmail(email);
    }
}

A: You need to put the method of sending mail in separated thread to keep your GUI interactive .
Thread newThread = new Thread(new ThreadStart(SendMail));
newThread.Start();

public void SendMail()
{
    //Send mails here
}

A: You can spin off a new thread to send the emails so you don't lock the UI thread.

A: Try shifting the code to background Thread.


text:
Q: LINQ to XML: don't get XElement it should be easy but I don't really see my fault.
public static void Edit(string old, string neew, string type)
    {
        XElement root = XElement.Load(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Xml.xml");

        switch (type)
        {
            case "Customer":

                XElement name = root.Descendants("Data").Descendants("Customer")
                    .Where(x => x.Element("Name").Value.ToString() == old)
                    .FirstOrDefault();

                name.SetElementValue("Name", neew);
                break;

XElement name returns null, so I get a NullReferenceException. But I don't know, why it only returns null.
This is my Xml structure:
<Data>
            <Customer>
                <Name>CustomerA</Name>
                <IP>888.888.888.888</IP>
                <UserLogin>auser</UserLogin>
                <UserPw>apwd</UserPw>
            </Customer>
            <Customer>
                <Name>CustomerB</Name>
                <IP>102.16.70.181</IP>
                <UserLogin>buser</UserLogin>
                <UserPw>bpwd</UserPw>
            </Customer>
        </Data>

Maybe someone could open my eyes and help me? Or give a hint?

A: it seems Data is already your root element. You can use  root.Elements("Customer") or root.Descendants("Customer") instead.
Apart from that XElement.Value property is of type string, so you don't need to call ToString on it.Also you may consider using explicit casts like (string)x.Element("Name") == old to avoid exceptions if the elements isn't found.


text:
Q: Msi & exe singing Microsoft Authenticode requirments I am trying to sign my small application, following this tutorial:
In the tutorial they did not ask me to purchase Microsoft Authenticode Certificates
I need to Removes "Unknown Publisher" security warnings; after I signmy msi and exe files I still have "Unknown Publisher"
Can I sign my msi or exe without purchasing Microsoft Authenticode Certificates?
I know that I can sign Java, Authenticode, and AIR apps free: https://www.globalsign.com/en/code-signing/code-signing-tool/

A: No you can't remove "Unknown Publisher" security warnings without purchasing a code signing certificate.
The tutorial link describes how to create a test certificate. Quoting the first paragraph "If you use a test (self-created) certificate, the installation dialogs will display an "Unknown publisher" message."
When you purchase a code signing certificate, the certifying authority takes certain steps to verify your identity.  If those steps are passed, the certifying authority issues you a certificate signed by their private key.  The private key is kept secret.  When you install code signed software, the operating system extracts the code signature from the software and validates it against the public key provided by the certifying authority.  This is a simplification, the actual check involves a chain of certificates.  But the key point is: if you use a self signed test certificate, the operating system has no knowledge of the public key of the self signed test certificate so cannot validate against it.


text:
Q: Angular2 - Cross-Origin Request Blocked I'm trying to use the forecast API with my angular2 app. However, when i try to access the API I get a Cross-Origin Error. Any idea how i can fix this error ?
search(latitude: any, longitude: any){
        console.log(latitude);
        console.log(longitude);
        let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude ;
        console.log(body);
        this.http.get(body)
            .map(
                response => response.json()
            ).subscribe(
                data =>  console.log("Data: "+data),
                err =>  console.log("Error: "+err),
                () => console.log('Get Complete')
            );
    }

Error
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.forecast.io/forecast/APIKEY/37.8267,-122.423. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Update
Now using JSONP
    let body = 'https://api.forecast.io/forecast/APIKEY/'+latitude+','+longitude + '?callback=?' ;
    console.log(body);
    this.jsonp.get(body)
    .map(response => response.json())
    .subscribe(
            data =>  console.log("Data: "+data),
            err =>  console.log("Error: "+err),
            () => console.log('Get Complete')
    );

Error
Error0.def29191127bbc3e0100.hot-update.js:59:10
Object { _body: "JSONP injected script did not invok…", status: 200, ok: true, statusText: "Ok", headers: Object, type: 3, url: "https://api.forecast.io/forecast/60…" }0.def29191127bbc3e0100.hot-update.js:61:10
SyntaxError: expected expression, got '==='

A: For forecast.io, you should use JSONP. The easiest way to do this using jQuery is adding ?callback=? to request URL:
$.getJSON('https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + "?callback=?", function(data) {
   console.log(data);
});

I am no expert on Angular 2 but reading the docs it looks like you need to import the Jsonp and then add a callback. More documentation here -- see the section app/wiki/wikipedia.service.ts.
I think something like the code below will work for you
let body = "https://api.forecast.io/forecast/<API KEY>/' + latitude + ',' + longitude + '?callback=?'";
return this.jsonp
           .get(body)
           .map(response => <string[]> response.json()[1]);

A: Check out the cors bits on angular.io
https://angular.io/docs/ts/latest/guide/server-communication.html#!#cors
Something like the below (from above)
return this.jsonp
           .get(wikiUrl, { search: params })
           .map(response => <string[]> response.json()[1]);

A: You are getting this problem because the header you are sending does not match the headers in the backend.
Suppose you send the following headers:
contentHeaders = new Headers();
contentHeaders.append('Authorization', 'Your token used in app');
contentHeaders.append('Content-Type', 'application/json');
contentHeaders.append('Access-Control-Allow-Origin', '*');

So those headers like Authorization, Content-type, and Access-Control-Allow-Origin should match the allowed headers in your backend.
So in the backend Access-Control-Allow-Headers should have all above headers:
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Authorization, content-type, Access-Control-Allow-Origin");

So here in Access-Control-Allow-Headers you have to pass all headers which you send from frontend: 'Authorization', 'Content-type', and 'Access-Control-Allow-Origin'.
It will work perfectly when you use above concept.
Hope this post will helpful for you
Thanks


text: Q: How API call will be effected based on the data in the packets? I want to know the relation between API call and it's amount of data. Will API call time vary with the increase in amount of data etc. Thank you in advance.


text:
Q: Numpy: Perform an "Upsert" by adding columns based on others I have two numpy arrays, x and y. They each have 3 columns and the first two columns are identifying in the sense of a relational database compound primary key. I want to merge these two arrays based on these compound primary keys, while adding the third column where the two arrays overlap.
>>> x = np.array([[1, 2, 1.5], [3, 4, 2.5], [5, 6, 3.5]])
>>> x
array([[1. , 2. , 1.5],
       [3. , 4. , 2.5],
       [5. , 6. , 3.5]])
>>> y = np.array([[1, 2, 4.5], [3, 4, 5.5], [7, 8, 6.5]])
>>> y
array([[1. , 2. , 4.5],
       [3. , 4. , 5.5],
       [7. , 8. , 6.5]])

I need a method to create array z, which combines x and y like an upsert:
>>> z = np.array([[1, 2, 6.0], [3, 4, 7.0], [5, 6, 3.5], [7, 8, 6.5]])
>>> z
array([[1. , 2. , 6. ],
       [3. , 4. , 7. ],
       [5. , 6. , 3.5],
       [7. , 8. , 6.5]])

Is it possible to do this in Numpy?

A: This operation can be done in the following steps.

*

*Get a mask whether the first two columns are equal.

mask = x[:, :2] == y[:, :2]

*Update the existing values:

x[np.all(mask, axis=1), 2] = x[np.all(mask, axis=1), 2] + y[np.all(mask, axis=1), 2]

*Inserting non existing rows:

x = np.append(x, y[np.any(~mask, axis=1)], axis=0)

Edit: For unsorted arrays of different size.
In this case I couldn't find a way as clean as the above case.
But the following will perform the job for unsorted and nonequal size arrays.
import numpy as np

x = np.array([[1, 2, 1.5], [3, 4, 2.5], [5, 6, 3.5]])

y = np.array([[1, 2, 4.5], [7, 8, 6.5], [3, 4, 5.5], [8, 9, 7.5]])

print(x)
print(y)

non_existing_rows = []
# Update existing rows and store non existing rows.
for row in y:
    mask = np.all(x[:,:2] == row[:2], axis = 1)
    if np.all(~mask):
        # The row does not exist in x.
        non_existing_rows.append(row)
    else:
        # The row exists in x.
        x[mask,2] = x[mask,2] + row[2]
# Insert non existing rows.
x = np.append(x, non_existing_rows, axis=0)

print(x)

I assume that the size of x is bigger than y in general, so it is better to iterate over y.
Also appending operation is faster for lists, so it is better to first aggregate non existing rows in a list and then append them to the numpy array as a whole.


text:
Q: ExtJS 5 textfield bug (Chrome) I create simple application with window and 3 field:
Fiddle Link (Use Chrome)
When I enter a value in the field, it looks fine.

But when I change the focus,text in field moves down.

All fields work similarly.

After click on trigger (if field has it) text looks fine.

This bug only in Chrome.
IE, Opera, Firefox and Vivaldi work right.
How can I fix that?

A: It's a known bug for chrome. Take a look here for the workaround:
https://www.sencha.com/forum/showthread.php?301227-Visual-combobox-bug-in-Chrome-43.0.2357.65-m&p=1101244&viewfull=1#post1101244

A: Css fix:
.x-form-text { display: inline; }

Demo here: http://ext4all.com/post/extjs-5-textfield-chrome-bug-fix.html


text:
Q: Sending reports to different puppet master than $server There are two puppet masters. pupmasterone.localdomain and pupmastertwo.localdomain. pupmastertwo is fetching configuration from pupmasterone and sending its reports to pupmasterone. (This is normal behaviour)
If we change the report_server in pupmastertwo to report to itself, its throwing error.
puppet.conf (pupmastertwo)
[main]
report_server=pupmastertwo.localdomain
[agent]
server=pupmasterone.localdomain

Error:
Error: Could not send report: SSL_connect returned=1 errno=0 state=unknown state: sslv3 alert certificate unknown

How to get this working?


text:
Q: How to create a Ghost Monitor in Windows 10 Ive made some research on the web and didn't found any answers and as its always been welcoming here here's my question.
Question:
Is it possible to make a Ghost Monitor ("Fake Monitor/Secondary Monitor") on windows 10?  I found the following topic: Is there a way to fake a dual (second) monitor,but apparently its not working in Windows 10. Any other means of doing so without any third party software.


text:
Q: Amount of SUSY preseved by branes Consider 10d superstring theory, a D5 brane extended in the 012789 directions, and an NS5 brane extended in the 012345 directions. I have read that this configuration preserves 1/4 of the supersymmetries. I am trying to figure out why, but I am struggling.
My understanding is that, given background supercharges $Q_L$ and $Q_R$, branes preserve SUSY's of the form $\epsilon_LQ_L+\epsilon_RQ_R$, where for the D5 brane above, $$\epsilon_L=\gamma_0\gamma_1\gamma_2\gamma_7\gamma_8\gamma_9\epsilon_R$$ while for NS5 branes (I believe this can be shown by S-dualising the above), $$\epsilon_{L/R}=\pm\gamma_0\gamma_1\gamma_2\gamma_3\gamma_4\gamma_5\epsilon_{L/R}.$$
So I combine these two to find $$\epsilon_L=-\gamma_5\gamma_4\gamma_3\gamma_7\gamma_8\gamma_9\epsilon_R\tag{1}$$ where I used $\gamma_i^2=-1$. I am not quite sure how to proceed -- in fact, apparently the correct relation would be $$\epsilon_L=\gamma_0\gamma_1\gamma_2\gamma_6\epsilon_R\tag{2}$$ but I am not quite sure how to show this.

A: Turns out (as I imagined...) that it is nothing profound. Just multiply both sides of (1) by the chirality operator, $\gamma_{11}=\gamma_0\gamma_1\dots\gamma_9$. On the left-hand side, $\gamma_{11}\epsilon_L=\epsilon_L$. On the right hand side, the 3,4,5,7,8,9 gamma matrices within $\gamma_{11}$ annihilate those already present (since $\gamma^\mu\gamma^\mu=1\eta^{\mu\mu}$), leaving only the 0, 1, 2, and 6 gamma matrices and thus giving the result (2). I am leaving this here in case anyone else has the same issue I had.

Just to expand:
We have that $$\epsilon_L=\gamma_7\gamma_8\gamma_9\gamma_3\gamma_4\gamma_5\epsilon_L$$
Now $\gamma_7\gamma_8\gamma_9\gamma_3\gamma_4\gamma_5$ squares to $1$, so its eigenvalues are $\pm 1$; it is traceless, so half of its e-values are $1$ and half $-1$. Hence, the equation above preserves half of the components of $\epsilon_L$. $\epsilon_R$ is uniquely fixed in terms of $\epsilon_L$, so the total number of SUSY's preserved is $1/4$ of the original amount.


text:
Q: Convert entered number to Only 2 decimal in the Excel sheet in C# using Math.Round Function The Entered number in excel is converting to decimals but its giving so many decimal, want only 2 decimal places

 var selectedDate = ApplicationGlobals.SelectedProjectGroupDetails.SelectedDate.StartDate();
                var startDate = DateTime.Now.StartDate();

                var editableColumns = _canMaintainProjectDemandByProjectGroup ? (startDate.Year - selectedDate.Year) * 12 + startDate.Month - selectedDate.Month : _projectDemandByProjectGroupDataTable.Columns.Count;

                var projectDemandByProjectGroupSpreadSheetScript = string.Format(sb.ToString(), _spreadSheetId, _projectDemandByProjectGroupDataTable.Rows.Count + 1,
                    _projectDemandByProjectGroupDataTable.Columns.Count, _spreadSheetName, _columnAttributes, JsonConvert.SerializeObject(_projectDemandByProjectGroupDataTable),
                    _columnFields, _hiddenColumns, _fixedColumns, ApplicationGlobals.ActualsColumns, editableColumns);

                var minifier = new Microsoft.Ajax.Utilities.Minifier();
                return string.Format("<script>{0}</script>", minifier.MinifyJavaScript(projectDemandByProjectGroupSpreadSheetScript));

The Entered number in excel is converting to decimals but its giving so many decimal, want only 2 decimal places
toInt = function(num)
{
    return Math.round(num * Math.Pow(10,decimals));
}

if(employeeAddInfo != null)
{
    var resource = string.Format("{0} - {1}", employee.FullName, employee.EmpNo);
    var dataRow = new List<object> { x.EmployeeNumber, false, employee.DepartmentIdNo, employee.Department, resource, employee.FullName, x.EmployeeNumber, employeeAddInfo.Skill, employeeAddInfo.Rate };

    financialCalendarList.ForEach(a =>
    {
        dynamic displayValue = null;
        if (financialCalendarList.IndexOf(a) < ApplicationGlobals.ActualsColumns)
        {
            var totalQuantity = actualsListForEmployeeNotExistsInProjectDemand
                .Where(y => y.EmployeeNumber == x.EmployeeNumber)
                .Where(y => y.FiscalYear == a.Year).Where(y => y.FiscalPeriod == a.Month)
                .Sum(y => y.Quantity);

            displayValue = ApplicationGlobals.IsDisplayInEp ? Math.Round(totalQuantity / a.WorkingHours, 2, MidpointRounding.AwayFromZero) : totalQuantity;

        }
        dataRow.Add(displayValue == null ? 0 : string.Format("{0}({1})", displayValue, displayValue.ToString("F")));
    });
    dataTable.Rows.Add(dataRow.ToArray());
}


text:
Q: How can you see the actual hard link by ls? I run
ln /a/A /b/B

I would like to see at the folder a where the file A points to by ls.

A: There isn't really a well-defined answer to your question. Unlike symlinks, hardlinks are indistinguishable from the "original file".
Directory entries consist of a filename and a pointer to an inode. The inode in turn contains the file metadata and (pointers to) the actual file contents). Creating a hard link creates another directory entry that references the same inode. These references are unidirectional (in typical filesystems, at least) -- the inode only keeps a reference count. There is no intrinsic way to find out which is the "original" filename.
By the way, this is why the system call to "delete" a file is called unlink. It just removes a hardlink. The inode and attached data are deleted only if the inode's reference count drops to 0.
The only way to find the other references to a given inode is to exhaustively search over the file system checking which files refer to the inode in question. You can use 'test A -ef B' from the shell to perform this check.

A: This is somewhat of a comment to Torocoro-Macho's own answer and script, but it obviously won't fit in the comment box.

Rewrote your script with more straightforward ways to find the info, and thus a lot less process invocations.
#!/bin/sh
xPATH=$(readlink -f -- "${1}")
for xFILE in "${xPATH}"/*; do
    [ -d "${xFILE}" ] && continue
    [ ! -r "${xFILE}" ] && printf '"%s" is not readable.\n' "${xFILE}" 1>&2 && continue
    nLINKS=$(stat -c%h "${xFILE}")
    if [ ${nLINKS} -gt 1 ]; then
        iNODE=$(stat -c%i "${xFILE}")
        xDEVICE=$(stat -c%m "${xFILE}")
        printf '\nItem: %s[%d] = %s\n' "${xDEVICE}" "${iNODE}" "${xFILE}";
        find "${xDEVICE}" -inum ${iNODE} -not -path "${xFILE}" -printf '     -> %p\n' 2>/dev/null
    fi
done

I tried to keep it as similar to yours as possible for easy comparison.
Comments on this script and yours

*

*One should always avoid the $IFS magic if a glob suffices, since it is unnecessarily convoluted, and file names actually can contain newlines (but in practice mostly the first reason).

*You should avoid manually parsing ls and such output as much as possible, since it will sooner or later bite you.  For example: in your first awk line, you fail on all file names containing spaces.

*printf will often save troubles in the end since it is so robust with the %s syntax. It also gives you full control over the output, and is consistent across all systems, unlike echo.

*stat can save you a lot of logic in this case.

*GNU find is powerful.

*Your head and tail invocations could have been handled directly in awk with e.g. the exit command and/or selecting on the NR variable. This would save process invocations, which almost always betters performance severely in hard-working scripts.

*Your egreps could just as well be just grep.

A: UNIX has hard links and symbolic links (made with "ln" and "ln -s" respectively). Symbolic links are simply a file that contains the real path to another file and can cross filesystems.
Hard links have been around since the earliest days of UNIX (that I can remember anyway, and that's going back quite a while). They are two directory entries that reference the exact same underlying data. The data in a file is specified by its inode. Each file on a file system points to an inode but there's no requirement that each file point to a unique inode - that's where hard links come from.
Since inodes are unique only for a given filesystem, there's a limitation that hard links must be on the same filesystem (unlike symbolic links). Note that, unlike symbolic links, there is no privileged file - they are all equal. The data area will only be released when all the files using that inode are deleted (and all processes close it as well, but that's a different issue).
You can use the "ls -i" command to get the inode of a particular file. You can then use the "find <filesystemroot> -inum <inode>" command to find all files on the filesystem with that given inode.
Here's a script which does exactly that. You invoke it with:
findhardlinks ~/jquery.js

and it will find all files on that filesystem which are hard links for that file:
pax@daemonspawn:~# ./findhardlinks /home/pax/jquery.js
Processing '/home/pax/jquery.js'
   '/home/pax/jquery.js' has inode 5211995 on mount point '/'
       /home/common/jquery-1.2.6.min.js
       /home/pax/jquery.js

Here's the script.
#!/bin/bash
if [[ $# -lt 1 ]] ; then
    echo "Usage: findhardlinks <fileOrDirToFindFor> ..."
    exit 1
fi

while [[ $# -ge 1 ]] ; do
    echo "Processing '$1'"
    if [[ ! -r "$1" ]] ; then
        echo "   '$1' is not accessible"
    else
        numlinks=$(ls -ld "$1" | awk '{print $2}')
        inode=$(ls -id "$1" | awk '{print $1}' | head -1l)
        device=$(df "$1" | tail -1l | awk '{print $6}')
        echo "   '$1' has inode ${inode} on mount point '${device}'"
        find ${device} -inum ${inode} 2>/dev/null | sed 's/^/        /'
    fi
    shift
done

A: ls -l

The first column will represent permissions. The second column will be the number of sub-items (for directories) or the number of paths to the same data (hard links, including the original file) to the file. Eg:
-rw-r--r--@    2    [username]    [group]    [timestamp]     HardLink
-rw-r--r--@    2    [username]    [group]    [timestamp]     Original
               ^ Number of hard links to the data

A: You can configure ls to highlight hardlinks using an 'alias', but as stated before there is no way to show the 'source' of the hardlink which is why I append .hardlink to help with that.

Add the following somewhere in your .bashrc
alias ll='LC_COLLATE=C LS_COLORS="$LS_COLORS:mh=1;37" ls -lA --si --group-directories-first'

A: You can find inode number for your file with
ls -i

and
ls -l

shows references count  (number of hardlinks to a particular inode)
after you found inode number, you can search for all files with same inode:
find . -inum NUM

will show filenames for inode NUM in current dir (.)

A: Based on the findhardlinks script (renamed it to hard-links), this is what I have refactored and made it work.
Output:
# ./hard-links /root

Item: /[10145] = /root/.profile
    -> /proc/907/sched
    -> /<some-where>/.profile

Item: /[10144] = /root/.tested
    -> /proc/907/limits
    -> /<some-where else>/.bashrc
    -> /root/.testlnk

Item: /[10144] = /root/.testlnk
    -> /proc/907/limits
    -> /<another-place else>/.bashrc
    -> /root/.tested

# cat ./hard-links
#!/bin/bash
oIFS="${IFS}"; IFS=$'\n';
xPATH="${1}";
xFILES="`ls -al ${xPATH}|egrep "^-"|awk '{print $9}'`";
for xFILE in ${xFILES[@]}; do
  xITEM="${xPATH}/${xFILE}";
  if [[ ! -r "${xITEM}" ]] ; then
    echo "Path: '${xITEM}' is not accessible! ";
  else
    nLINKS=$(ls -ld "${xITEM}" | awk '{print $2}')
    if [ ${nLINKS} -gt 1 ]; then
      iNODE=$(ls -id "${xITEM}" | awk '{print $1}' | head -1l)
      xDEVICE=$(df "${xITEM}" | tail -1l | awk '{print $6}')
      echo -e "\nItem: ${xDEVICE}[$iNODE] = ${xITEM}";
      find ${xDEVICE} -inum ${iNODE} 2>/dev/null|egrep -v "${xITEM}"|sed 's/^/   -> /';
    fi
  fi
done
IFS="${oIFS}"; echo "";

A: How about the following simpler one? (Latter might replace the long scripts above!)
If you have a specific file <THEFILENAME>and want to know all its hardlinks spread over the directory <TARGETDIR>, (which can even be the entire filesystem denoted by /)
find <TARGETDIR> -type f -samefile  <THEFILENAME>

Extending the logic, if you want to know all the files in the <SOURCEDIR> having multiple hard-links spread over <TARGETDIR>:
find <SOURCEDIR> -type f -links +1   \
  -printf "\n\n %n HardLinks of file : %H/%f  \n"   \
  -exec find <TARGETDIR> -type f -samefile {} \;

A: There are a lot of answers with scripts to find all hardlinks in a filesystem.  Most of them do silly things like running find to scan the whole filesystem for -samefile for EACH multiply-linked file.  This is crazy; all you need is to sort on inode number and print duplicates.
With only one pass over the filesystem to find and group all sets of hardlinked files
find dirs   -xdev \! -type d -links +1 -printf '%20D %20i %p\n' |
    sort -n | uniq -w 42 --all-repeated=separate

This is much faster than the other answers for finding multiple sets of hardlinked files.
find /foo -samefile /bar is excellent for just one file.

*

*-xdev : limit to one filesystem.  Not strictly needed since we also print the FS-id to uniq on

*! -type d reject directories: the . and .. entries mean they're always linked.

*-links +1 : link count strictly > 1

*-printf ... print FS-id, inode number, and path.  (With padding to fixed column widths that we can tell uniq about.)

*sort -n | uniq ... numeric sort and uniquify on the first 42 columns, separating groups with a blank line

Using ! -type d -links +1 means that sort's input is only as big as the final output of uniq so we aren't doing a huge amount of string sorting.  Unless you run it on a subdirectory that only contains one of a set of hardlinks.  Anyway, this will use a LOT less CPU time re-traversing the filesystem than any other posted solution.
sample output:
...
            2429             76732484 /home/peter/weird-filenames/test/.hiddendir/foo bar
            2429             76732484 /home/peter/weird-filenames/test.orig/.hiddendir/foo bar

            2430             17961006 /usr/bin/pkg-config.real
            2430             17961006 /usr/bin/x86_64-pc-linux-gnu-pkg-config

            2430             36646920 /usr/lib/i386-linux-gnu/dri/i915_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/i965_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/nouveau_vieux_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/r200_dri.so
            2430             36646920 /usr/lib/i386-linux-gnu/dri/radeon_dri.so
...

TODO?: un-pad the output with awk or cut.  uniq has very limited field-selection support, so I pad the find output and use fixed-width.  20chars is wide enough for the maximum possible inode or device number (2^64-1 = 18446744073709551615).  XFS chooses inode numbers based on where on disk they're allocated, not contiguously from 0, so large XFS filesystems can have >32bit inode numbers even if they don't have billions of files.  Other filesystems might have 20-digit inode numbers even if they aren't gigantic.
TODO: sort groups of duplicates by path.  Having them sorted by mount point then inode number mixes things together, if you have a couple different subdirs that have lots of hardlinks.  (i.e. groups of dup-groups go together, but the output mixes them up).
A final sort -k 3 would sort lines separately, not groups of lines as a single record.  Preprocessing with something to transform a pair of newlines into a NUL byte, and using GNU sort --zero-terminated -k 3 might do the trick.  tr only operates on single characters, not 2->1 or 1->2 patterns, though.  perl would do it (or just parse and sort within perl or awk).  sed might also work.

A: A GUI solution gets really close to your question:
You cannot list the actual hardlinked files from "ls" because, as previous commentators have pointed out, the file "names" are mere aliases to the same data.  However, there actually is a GUI tool that gets really close to what you want which is to display a path listing of file names that point to the same data (as hardlinks) under linux, it is called FSLint.  The option you want is under "Name clashes" -> deselect "checkbox $PATH" in Search (XX) -> and select "Aliases" from drop-down box after "for..." towards the top-middle.
FSLint is very poorly documented but I found that making sure the limited directory tree under "Search path" with the checkbox selected for "Recurse?" and the aforementioned options, a listing of hardlinked data with paths and names that "point" to the same data are produced after the program searches.

A: This thread had been thoroughly chewed but I think I can still contribute.
You can find ALL of the Hardlinks of a file by using this command:
sudo find / - inum `ls -i | grep <file-name> | cut -d' ' -f1`

*

*replace <file-name> with your the name of your file.

Basically what it does is looking for the file name(grep) in the current directory(ls), separating the inum(cut). Then it passes the result of the inum(using ``) into the find command to look for all the files in the filesystem that correspond to the exact inum.
Note: This command uses sudo because it looks for ALL the files in the root(/). this can be changed to the any directory path.
The advantages of this to other answers are the use of simple and clear commands, would also reduce @zzr's answer to a single line of code.

A: i just needed to use something like this ...
alias ...='__ () { ls -ai "${@}" | while read _i_ _u_ ; do find ../.. -inum "${_i_}" -printf "${_u_}\t%p" ; echo ; done ; } ; __'

... gives a tabbed list of all names connected with the inodes that ls discovers with what ever arguments are given, from the relative location '../..' in this case. Not totally bullet proof, just a sketch that fitted my need to find the hard links in some directories i was untangling ...
most of the time there will just be 2 columns in the output, a name of the entry from 'ls', and then the relative path from 'find' to the same inode ... if 'find' finds other entries that are for the same inode, they will appear in 3rd or 4th or nth columns in the output


text:
Q: Zend Framework 2 InputFilter and form fields
*

*I have a 'users' table with many fields like username, name, email, password, sex, birthday, avatar, etc. I have described all of them in the Users model of my ZF2 application using the InputFilter.

The problem is the following:
 - I have some forms like main settings (with only the name, sex and birthday fields in) and I would like to edit only these three fields in the database via this form (and respectively to edit other fields like password and email in other forms in other pages of the site). However, it doesn't seem to work:
$request = $this->getRequest();
    if ($request->isPost()) {
        $users = new Users();
        $form->setInputFilter($users->getInputFilter());
        $form->setData($request->getPost());

        if ($form->isValid()) {
            $users->exchangeArray($form->getData());
            $this->getUsersTable()->editUser($users, $userInfo->user_id);
            $message = 'Профилът ви беше успешно променен!';
        }
    }

Here is the form that I want to update only the fields name, birthday and sex.
And here is the model:
public function editUser(Users $user, $userID) {
    $data = array(
        'name' => $user->name,
        'birthday' => $user->birthday,
        'sex' => $user->sex,
    );

    $this->tableGateway->update($data, array('user_id' => $userID));
}

$form->getMessages() returns an empty array and var_dump($form->isValid) returns boolean false. If I delete all other MySQL fields and filters in the InputFilter and I keep only the three fields (name, birthday and sex) in the model, it's all ok and the form validation works. But when I describe all other fields of the 'users' table in the model, it doesn't. Hope I explained it well. Any ideas?

A: You can use Validation Groups to only validate certain fields when you only want to save partial data:
http://framework.zend.com/manual/2.0/en/modules/zend.form.quick-start.html#validation-groups
for example:
$form->setValidationGroup('name', 'sex', 'birthday');
$form->setData($data);
if ($form->isValid()) {
    // Contains only the "name", "sex", "birthday"
    $data = $form->getData();
}


text:
Q: Separate opacity for border in rectangle - QML I want to change the opacity of the border in the rectangle but not change the opacity of the background rectangle.

A: I would recommend that you always start with the documentation and only then, in case of failure, with the help of the community. Moreover, the Qt/QML documentation is quite detailed and clear.
As for your case you have to play with the border color, or rather with the alpha component of the color, for example:
import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    width: 800
    height: 600
    visible: true
    title: qsTr("Border test")

    Flow {
        id: background
        anchors.fill: parent
        Repeater {
            id: repeater
            property int cols: Math.floor(background.width / 50);
            property int rows: Math.floor(background.height / 50);
            model: repeater.cols * repeater.rows
            delegate: Rectangle {
                width: 50
                height: width
                color: {
                    var row = Math.floor(index / repeater.cols);
                    var col = Math.floor(index % repeater.cols);
                    return row % 2 ? (col % 2 ? "#EFEFEF" : "#FFFFFF") : (col % 2 ? "#FFFFFF" : "#EFEFEF")
                }
            }
        }
    }

    Rectangle {
        width: 300
        height: 300
        anchors.centerIn: parent
        color: "orange"
        border.width: 50
        border.color: "#80306090" // the same will work with Qt.rgba(0.2, 0.4, 0.6, 0.5)
        radius: 25
    }
}


text:
Q: How can I completely delete PictureBox (+ release memory) I'm trying to delete my PictureBox completely as I don't need it anymore. I tried to use Dispose() method and this removed the PBox from the Form correctly, but not from the memory... After I applied Dispose(), I created a PBox and load the same image in it, then called Dispose() again and so on... What I see in the 'Diagnostic Tools / Process memory' window is the memory usage increased each time when I press the button (which create new PBox and load image into it), but the memory is never released... I also tried to use Controls.Remove() method but I got the same result!
So the question is: How can I release the memory and remove a PictureBox completely?
EDIT:
Ok.. after a while when the program used up about 1Gb of memory (by create PBox/Dispose cycle) the garbage collector activated itself and released almost all of the memory used by the program! I misunderstood how this works... I thought it should have ran each time after I use Dispose method.. so looks all good, but is there any way to release PBox from memory manually after I applied Dispose?

A: Generally, you should call Dispose and drop all references to the PictureBox. Some time later the GC will collect this PictureBox and free the memory. But it is no way to know, when exactly GC will run. So, the memory usage may increase for some time before GC will run - it is normal. In most cases you should not manually force GC to run, but in some specific cases you can do this with GC.Collect(); (but it strongly not recommended)
Update
You can't manually "collect/free" only specified object. Only force GC (and get all the possible problems, mentioned by the link above).
The better solution may be to rework your code to avoid recreation of ImageBoxes. You can try

*

*show/hide the single ImageBox and just replacing the image inside it

*cache the ImageBox object and add/remove it from the form with Controls.Add/Controls.Remove.

You will still get some memory traffic due to loading/disposing images, but it may be better then recreation of a whole ImageBox


text:
Q: Understanding the logic behind a piece of C code I would love if you guys could explain to me why the following piece of recursive code doesn't print the word 'test'. Thanks in advance.
void drawTetriminosEachPosition(int **tetriminos, char **dBoard, int **tBoard, int i){
  char c;
  char **dBoard2;

  if(tetriminos[i] == '\0')
  {
      return;
  }
  else
  {
     dBoard2 = dBoard;
     DrawTetrimino(tBoard, tetriminos[i], dBoard, i+65);
  }
  i++;
  return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));

  ft_putstr("test");
  if(checkChar(tBoard,tetriminos[i]))
  {
      dBoard = dBoard2;
      return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
  }
}

A: Statements after a return are never executed. Since the first
return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));

does not depend on any condition, the following code is not executed.

A: When control reaches return ... it simply returns and next lines are not executed. Maybe you missed some logic in between?
As of now you can delete this part  it doesn't matter
ft_putstr("test");
  if(checkChar(tBoard,tetriminos[i]))
  {
      dBoard = dBoard2;
      return (drawTetriminosEachPosition(tetriminos,dBoard,tBoard,i));
  }