qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
8,713,090
I'm trying to center the names(#box2) and the topic(#box1) on top of an image. ``` <?php require_once('seminar_config.php'); ?> <a href="print.certificate.php">Print</a> <body> <?php $participants = $db->get_results("SELECT participant FROM tbl_participants WHERE state=1"); $topics = $db->get_results("SELECT topic FROM tbl_topics"); if(!empty($participants)){ ?> <?php ob_start(); ?> <div id="container"> <img src="certificate.jpg"/> <?php foreach($topics as $a=>$b){ ?> <?php foreach($participants as $k=>$v){ ?> <img src="certificate.jpg"/> <div id="box1" class="common"><?php echo $b->topic; ?></div> <div id="box2" class="common"><?php echo $v->participant; ?></div> <?php } ?> <?php } ?> </div> <?php $_SESSION['certificates'] = ob_get_contents(); ?> <?php ob_flush(); ?> <?php } ?> </body> ``` And here's the script that creates the pdf: ``` <?php require_once('html2pdf/html2pdf.class.php'); ?> <?php $html2pdf = new HTML2PDF('L', 'A4', 'en'); $html2pdf->writeHTML('<style> #box1{ margin-top: 350px; } #box2{ margin-top: 200px; } .common{ height: 20px; left: 630px; right: 630px; text-align: center; position: absolute; left: 0; top: 0; font-size:20px; } </style>'. $_SESSION['certificates']); $html2pdf->Output('random.pdf'); ?> ``` I have no problem with the center positioning of the names and topic if I'm not using html2pdf to generate pdf files. But if I use html2pdf everything is ruined. Please help me center things in css when using html2pdf.
2012/01/03
[ "https://Stackoverflow.com/questions/8713090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225269/" ]
Old question, but I had similar problem today. Here is how I was able to solve it after trying every method in the history of html and css to center something. I used a table like JorisW: ``` <table style='width:100%' align='center'> <tr> <td> <img src="image.gif"> </td> </tr> </table> ```
Try using tables and inline css styles ``` <table align="left" width="100%" style="page-break-after:always; margin-top:25px; margin-left:25px; font-family:tahoma; font-size:20px; "> <tr><td>Your info</td></tr> </table> ```
39,927,079
I am unsure what is wrong with my code. I am trying to write a program that finds the prime factorization of a number, and iterates through numbers. My code is ``` import math import time def primfacfind(n1,n2): while n1 < n2: n = n1 primfac=[] time_start = time.clock() def primes(n): sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] print primes(n) def factfind(lsp,n): #finds factors of n among primes for i in lsp: if n%i==0: primfac.append(i) else: i+=1 factfind(primes(n),n) print primfac def simplify(lsp): for i in lsp: if lsp.count(i) > 1: i+=1 #should simplify to 3^2 instead of 3,3; unfinished time_end = time.clock() time_elapsed = time_end - time_start print time_elapsed n1+=1 print primfacfind(6,15) ``` The error given is ``` Traceback (most recent call last): File "python", line 15 sieve = [True] * n ^ IndentationError: expected an indented block ``` I've checked over my indentation again and again, and I am unsure as to what is wrong. The program worked when it was not in the overall function and while loop, but I don't see how that should make a difference. It would be appreciated if the answer code was as simple as possible to understand, as I am somewhat new to python. Any help with this error would be appreciated. Thanks!
2016/10/07
[ "https://Stackoverflow.com/questions/39927079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6723642/" ]
Download something like [Sublime](https://www.sublimetext.com/) and highlight the code. Spaces will be dots and tabs will be dashes.
I put that code in my editor and it compiled just fine. So I went to line 12 where you have `sieve = [True] * n` and got rid of the indentation so it was indented the same as the line above it `def primes(n):` and I was able to recreate your error. Perhaps try and add an additional indentation than you think. You can also try Enthought Canopy which is free if you go to a university if you want a different editor.
17,441,419
I am trying to get a list title, What I want is when I type in Edittext on home page then add into list after clicking on Ok button. Right now I don't know where to put my refresh method that I am calling from customAdapter class on Homepage Activity. Please view my HomePage Activity: ``` public class Main_Activity extends Activity implements OnClickListener { Button ok; EditText addTasklist; ListView list_tasklistname; TodoTask_Database db; CustomAdapter cAdapter; List<Tasks> list = new ArrayList<Tasks>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); ok = (Button)findViewById(R.id.add); ok.setOnClickListener(this); list_tasklistname = (ListView)findViewById(R.id.listview); db = new TodoTask_Database(getApplicationContext()); list = db.getAllTaskList(); CustomAdapter adapter = new CustomAdapter(Main_Activity.this, R.layout.tasklist_row, list); list_tasklistname.setAdapter(adapter); /*list_tasklistname.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View v, int position, long id) { } });*/ db.close(); } } @Override public void onClick(View v) { switch(v.getId()) { case R.id.add: addTasklist = (EditText)findViewById(R.id.addTasklist); if(addTasklist!=null) { String addtasktitle = addTasklist.getText().toString(); db = new TodoTask_Database(getApplicationContext()); db.addTaskList(addtasktitle); } break; } } } ``` Custom Adapter: ``` public class CustomAdapter extends ArrayAdapter<Tasks> { private List<Tasks> dataitem; private Activity activity; public CustomAdapter(Activity a, int textViewResourceId, List<Tasks> items) { super(a, textViewResourceId, items); this.dataitem = items; this.activity = a; } public static class ViewHolder{ public TextView tasklistTitle; public TextView createdDate; public CheckBox completedflag; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; ViewHolder holder; if (v == null) { LayoutInflater vi = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.tasklist_row, null); holder = new ViewHolder(); holder.tasklistTitle = (TextView) v.findViewById(R.id.tasklistTitle); holder.createdDate = (TextView) v.findViewById(R.id.createdDate); holder.completedflag = (CheckBox) v.findViewById(R.id.completedflag); v.setTag(holder); } else holder=(ViewHolder)v.getTag(); final Tasks custom = dataitem.get(position); if (custom != null) { holder.tasklistTitle.setText(custom.getTaskListTitle()); holder.createdDate.setText(custom.getTaskListCreated()); holder.completedflag.setText(custom.getTaskListCompletedFlag()); } return v; } // refresh Adapter Method calling in Homepage Activity public synchronized void refresAdapter(List<Tasks> dataitems) { dataitem.clear(); dataitem.addAll(dataitems); notifyDataSetChanged(); } } ```
2013/07/03
[ "https://Stackoverflow.com/questions/17441419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1927757/" ]
In `onclick` method you may call your refresh method `refresAdapter(List<Tasks> dataitems)` after `db.addTaskList(addtasktitle);` statement. Or simply you may write `adapter.notifyDataSetChanged()` after this `db.addTaskList(addtasktitle)`; statement
call this method `adapter.notifyDatasetChanged()` if you want to do it for the navigation drawer, do it in `draweropen` method
67,779,344
I am trying to compile an Alpine Go container which uses [GORM](https://gorm.io/docs/connecting_to_the_database.html#SQLite) and it's [SQLite driver](https://github.com/go-gorm/sqlite) for an in-memory database. This depends on CGO being enabled. My binary builds and executes fine using `go build .`, but when running my docker image (`docker build .` followed by `docker run $imagename`) I get the error message: ``` standard_init_linux.go:219: exec user process caused: no such file or directory ``` I am building on Windows 10 64 bit. I have gcc installed. Both `C:\TDM-GCC-64\bin` and `C:\cygwin64\bin` are in my $env:path. I have changed the line endings to Linux style (LF) for all files in the package. My docker file is as follows: ``` FROM golang:1.16.4-alpine AS builder RUN apk update \ && apk add --no-cache git \ && apk add --no-cache ca-certificates \ && apk add --update gcc musl-dev \ && update-ca-certificates # Create a user so that the image doens't run as root RUN adduser \ --disabled-password \ --gecos "" \ --home "/nonexistent" \ --shell "/sbin/nologin" \ --no-create-home \ --uid "100001" \ "appuser" # Set the working directory inside the container. WORKDIR $GOPATH/src/app # Copy all files from the current directory to the working directory COPY . . # Fetch dependencies. RUN go get -u -d -v # Go build the binary, specifying the final OS and architecture we're looking for RUN GOOS=linux CGO_ENABLED=1 GOARCH=amd64 go build -ldflags="-w -s" -o /go/bin/app -tags timetzdata FROM scratch # Import the user and group files from the builder. COPY --from=builder /etc/passwd /etc/passwd COPY --from=builder /etc/group /etc/group COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ # Copy our static executable. COPY --from=builder /go/bin/app/go/bin/app # Use the user that we've just created, one that isn't root USER appuser:appuser ENTRYPOINT ["/go/bin/app"] ``` Can you please help me understand why my docker image won't run? In case it's of any value, the line of Go code to open the DB is like so. As this works using Go build locally or using `go run .` I don't think this is relevant however. ``` db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{}) ```
2021/05/31
[ "https://Stackoverflow.com/questions/67779344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7125937/" ]
I'm not sure if this is what you ask, but you cannot (well, it depends...) reverse a hashing algorithm to acquire an original password from the hash. You do the opposite: hash password provided by the user and check if a resulting hash is the same as the one stored earlier: ``` if (user == "user" && password == md5("1234")) { ```
You should not store user credentials on the device, encrypted or not. If the user uninstalls your app or clears cache, they will be locked out. They also would not be able to log in from another device. Credentials should be handled by the server. To encrypt passwords you should use a library like bcrypt. It allows you to salt the hash, making it very difficult to decrypt. Again, this should be done in your backend. If you really want to do this on the device, this is a good resource <https://bignerdranch.com/blog/encrypting-shared-preferences-with-the-androidx-security-library/>
43,097,634
Im making a loading bar. And now i got an error when i click on download > > Uncaught TypeError: Cannot read property 'style' of null > > > I dont know what i am dong wrong please can someone help me here is my code ``` <a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default"> <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%"> <p class="text-center">0%</p> </div> </div></a> <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button> </div> <script type="text/javascript"> function move() { document.getElementById("headerTop").style.cursor = "wait"; var elem = document.getElementById("myBar"); var width = 0; var id = setInterval(frame, 1000); function frame() { if (width >= 99) { var number = random(99, 100) if(number = 99) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' ) document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over"; }else if (number = 100) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' ) document.getElementById("header").title = "download is ready"; } } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } </script> ``` F.Y.I i am using bootstrap for the styling
2017/03/29
[ "https://Stackoverflow.com/questions/43097634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7707983/" ]
I think the problem is with this line: ``` var elem = document.getElementById("myBar"); ``` You're selecting by Id but myBar is a class So you should select by classname You could also just select by id as you do below: ``` var elem document.getElementById("MyElement"); ``` That's probably the easiest thing to do.
**Observation :** There is no `id` with name `myBar` is available in your `DOM`. **Statement :** `var elem = document.getElementById("myBar")` will return null. Hence, you are getting below error as you are trying to access `style` property of `null`. > > Uncaught TypeError: Cannot read property 'style' of null > > >
43,097,634
Im making a loading bar. And now i got an error when i click on download > > Uncaught TypeError: Cannot read property 'style' of null > > > I dont know what i am dong wrong please can someone help me here is my code ``` <a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default"> <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%"> <p class="text-center">0%</p> </div> </div></a> <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button> </div> <script type="text/javascript"> function move() { document.getElementById("headerTop").style.cursor = "wait"; var elem = document.getElementById("myBar"); var width = 0; var id = setInterval(frame, 1000); function frame() { if (width >= 99) { var number = random(99, 100) if(number = 99) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' ) document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over"; }else if (number = 100) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' ) document.getElementById("header").title = "download is ready"; } } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } </script> ``` F.Y.I i am using bootstrap for the styling
2017/03/29
[ "https://Stackoverflow.com/questions/43097634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7707983/" ]
I think the problem is with this line: ``` var elem = document.getElementById("myBar"); ``` You're selecting by Id but myBar is a class So you should select by classname You could also just select by id as you do below: ``` var elem document.getElementById("MyElement"); ``` That's probably the easiest thing to do.
After Jonathan's correction, another issue might be that *elem*, *width* and *id* are defined in the parent move() function, and not in the child frame() function. ``` <script type="text/javascript"> function move() { document.getElementById("headerTop").style.cursor = "wait"; function frame() { var elem = document.getElementById("myElement"); var width = 0; var id = setInterval(frame, 1000); if (width >= 99) { var number = random(99, 100) if(number = 99) { clearInterval(id); document.getElementById("myElement").className = document.getElementById("myElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' ) document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over"; }else if (number = 100) { clearInterval(id); document.getElementById("myElement").className = document.getElementById("myElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' ) document.getElementById("header").title = "download is ready"; } } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } </script> ```
43,097,634
Im making a loading bar. And now i got an error when i click on download > > Uncaught TypeError: Cannot read property 'style' of null > > > I dont know what i am dong wrong please can someone help me here is my code ``` <a class="tooltip-test" id="header"><div class="progress" id="headerTop" style="cursor:default"> <div id="myElement" class="progress-bar bg-info progress-bar-striped progress-bar-animated myBar" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 0%"> <p class="text-center">0%</p> </div> </div></a> <button onclick="move()" type="button" class="btn btn-outline-primary btn-lg">download</button> </div> <script type="text/javascript"> function move() { document.getElementById("headerTop").style.cursor = "wait"; var elem = document.getElementById("myBar"); var width = 0; var id = setInterval(frame, 1000); function frame() { if (width >= 99) { var number = random(99, 100) if(number = 99) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' ) document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over"; }else if (number = 100) { clearInterval(id); document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' ) document.getElementById("header").title = "download is ready"; } } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } </script> ``` F.Y.I i am using bootstrap for the styling
2017/03/29
[ "https://Stackoverflow.com/questions/43097634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7707983/" ]
After Jonathan's correction, another issue might be that *elem*, *width* and *id* are defined in the parent move() function, and not in the child frame() function. ``` <script type="text/javascript"> function move() { document.getElementById("headerTop").style.cursor = "wait"; function frame() { var elem = document.getElementById("myElement"); var width = 0; var id = setInterval(frame, 1000); if (width >= 99) { var number = random(99, 100) if(number = 99) { clearInterval(id); document.getElementById("myElement").className = document.getElementById("myElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-danger' ) document.getElementById("header").title = "Oops looks like something has gone wrong reload the page to start over"; }else if (number = 100) { clearInterval(id); document.getElementById("myElement").className = document.getElementById("myElement").className.replace ( /(?:^|\s)bg-info(?!\S)/g , 'bg-success' ) document.getElementById("header").title = "download is ready"; } } else { width++; elem.style.width = width + '%'; elem.innerHTML = width * 1 + '%'; } } } </script> ```
**Observation :** There is no `id` with name `myBar` is available in your `DOM`. **Statement :** `var elem = document.getElementById("myBar")` will return null. Hence, you are getting below error as you are trying to access `style` property of `null`. > > Uncaught TypeError: Cannot read property 'style' of null > > >
56,953,249
Is there a shortcut similiar to `{` and `}` in vim? I.e. move to block start/end? Use case: Caret is at the beginning of tons of imports, want to move caret to next blank line after imports
2019/07/09
[ "https://Stackoverflow.com/questions/56953249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1576149/" ]
You can see the different kepmaps for the caret movement in the IntelliJ IDE by going to `File->Settings->Keymap`, where in the seach bar you type `Move Caret`. [![enter image description here](https://i.stack.imgur.com/Tkniy.png)](https://i.stack.imgur.com/Tkniy.png) In your case you can use `Ctrl+Up` to move the Caret Backwards and `Ctrl+Down` to move it forwards. There are many other bindings that you can use and see in that menu. You can even re-map them all you want!
In a code block, you can use "Code block start" and "Code block end" actions (Cmd-Alt-[, Cmd-Alt-] in the default Mac keymap, Ctrl-[ and Ctrl-] in the default keymap on other operating systems). This shortcut doesn't work in the import block, but normally this is not needed because the standard way to work with imports in IntelliJ is to use "Auto import" and "Optimize imports" actions, and you simply never put the caret in the import list.
39,297,989
i am trying my routing feature of abgular2 RC5, Please have look at below code. **app.component.ts** ``` import { Component,HostBinding } from '@angular/core'; import { ROUTER_DIRECTIVES } from "@angular/router"; @Component({ selector: 'my-app', template: ` <h1>My First Angular 2 App </h1> <router-outlet></router-outlet> ` }) export class AppComponent {} import { Component } from '@angular/core'; ``` **usercomp.ts** ``` @Component({ selector: 'user-comp', template: ` <h1>USER COMPONENT</h1> ` }) export class UserComponent {} ``` **homecomponent.ts** ``` import { Component } from '@angular/core'; @Component({ moduleId: module.id, selector: 'home-component', template: ` <h1>Home Component</h1> ` }) export class HomeComponent {} ``` **app.module.ts** ``` import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { Component } from '@angular/core'; import { AppComponent } from './app.component'; import { routing } from './approuter' import { ROUTER_DIRECTIVES } from '@angular/router' import { HomeComponent } from './homecomponent' import { UserComponent } from './usercomp' @NgModule({ imports: [ BrowserModule,routing ], declarations: [ AppComponent,HomeComponent,UserComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } ``` **approuter.ts** ``` import { RouterModule,Routes } from '@angular/router' const APP_ROUTES:Routes = [ { path:'user', component:'UserComponent' }, { path:'', component:'HomeComponent' } ]; export const routing = RouterModule.forRoot(APP_ROUTES); ``` ***ERROR*** [![enter image description here](https://i.stack.imgur.com/Prsps.jpg)](https://i.stack.imgur.com/Prsps.jpg) I tried exporting HomeComponent and UserComponent home component everywhere but unable to get rid of this code. With RC4 it worked fine the older way but not sure what wrong i did here, please have a look and let me know when i have mistaken..
2016/09/02
[ "https://Stackoverflow.com/questions/39297989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3109806/" ]
``` import { RouterModule,Routes } from '@angular/router' import { HomeComponent } from './homecomponent'; import { UserComponent } from './usercomp'; const APP_ROUTES:Routes = [ { path:'user', component: UserComponent }, { path:'', component: HomeComponent } ]; export const routing = RouterModule.forRoot(APP_ROUTES); ``` component accepts any component type, check class reference [here](https://angular.io/docs/ts/latest/api/router/index/Routes-type-alias.html)
I think you need to add pathMatch to your default route: ``` { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', loadChildren: './app/home/home.module#HomeModule' } ```
6,144
I'm currently in a weird situation - I have a large amount of accrued debt (85k principal, ~15k accrued interest so far), spread amongst multiple smaller student loans. Some are federal stafford loans, which were taken out at Max, and some are large private student loans. Currently, I'm paying them at minimum through each loan, and paying some money directly to the principal whenever I can. The problem is that with so many loans (8 different loans through four different lenders), it's very easy to forget and miss a payment, and I may have been late once or twice. (wince.) Ideally, I would pay a larger lump sum every month with a fixed rate consolidation loan - but I've done some investigation and the largest sum I could find through a reputable agency was for 25k. The other issue is that I currently don't have any collateral, and my cosigner is less than willing to sign again. What options are there for consolidating a large amount of student loan debt? Edit: I have considered federal consolidation for the Stafford loans, but that's only a drop in the bucket compared to the private loans.
2011/02/07
[ "https://money.stackexchange.com/questions/6144", "https://money.stackexchange.com", "https://money.stackexchange.com/users/2694/" ]
The U.S. Department of Ed offers Loan consolidation that you may want to take a look at: <https://loanconsolidation.ed.gov/AppEntry/apply-online/appindex.jsp> Going through a Government Agency as opposed to a private lender might reduce the burden (co-signers, collateral) you need to pass to get the loan.
I can't help you with consolidation, but I'd suggest automating as much of the payments as possible. * Do your lenders support automatic debit of your checking for the payments? * Can you use online bill pay to make the payments? If not, you might take a look at any of the numerous online banks that have online bill pay, and open an account with them. (E.g. ING Direct, Ally, etc.) You can set up the online account to pull from your current checking/savings account, and then make payments from that online account to your loans. When you have that set up, if there is some extra payment you want to make, you can set up an automatic additional periodic payment to get rid of one lender at a time until everything is paid off.
6,144
I'm currently in a weird situation - I have a large amount of accrued debt (85k principal, ~15k accrued interest so far), spread amongst multiple smaller student loans. Some are federal stafford loans, which were taken out at Max, and some are large private student loans. Currently, I'm paying them at minimum through each loan, and paying some money directly to the principal whenever I can. The problem is that with so many loans (8 different loans through four different lenders), it's very easy to forget and miss a payment, and I may have been late once or twice. (wince.) Ideally, I would pay a larger lump sum every month with a fixed rate consolidation loan - but I've done some investigation and the largest sum I could find through a reputable agency was for 25k. The other issue is that I currently don't have any collateral, and my cosigner is less than willing to sign again. What options are there for consolidating a large amount of student loan debt? Edit: I have considered federal consolidation for the Stafford loans, but that's only a drop in the bucket compared to the private loans.
2011/02/07
[ "https://money.stackexchange.com/questions/6144", "https://money.stackexchange.com", "https://money.stackexchange.com/users/2694/" ]
To add to @bstpierre's answer, you should automate all your loans except for the one with the highest interest rate. Leave that one manual, and pay the most you can afford each month, to pay it off as quickly as possible. Once you finish that loan, move to the next highest interest rate. Ultimately, this won't be quite as convenient as just having 1 loan. The differences are: 1. You need to set up all the automatic payments. This is probably comparable to in complexity of consolidating your loans. 2. Each time you finish one loan, you need to turn off an automatic payment, and start doing the next loan manually. If you organize yourself well initially, you'll know exactly what order to do the loans in, so this shouldn't take too long. However, unless your consolidated loan has the same interest rate of your cheapest current loan, you will likely save money over-all by using this method.
The U.S. Department of Ed offers Loan consolidation that you may want to take a look at: <https://loanconsolidation.ed.gov/AppEntry/apply-online/appindex.jsp> Going through a Government Agency as opposed to a private lender might reduce the burden (co-signers, collateral) you need to pass to get the loan.
6,144
I'm currently in a weird situation - I have a large amount of accrued debt (85k principal, ~15k accrued interest so far), spread amongst multiple smaller student loans. Some are federal stafford loans, which were taken out at Max, and some are large private student loans. Currently, I'm paying them at minimum through each loan, and paying some money directly to the principal whenever I can. The problem is that with so many loans (8 different loans through four different lenders), it's very easy to forget and miss a payment, and I may have been late once or twice. (wince.) Ideally, I would pay a larger lump sum every month with a fixed rate consolidation loan - but I've done some investigation and the largest sum I could find through a reputable agency was for 25k. The other issue is that I currently don't have any collateral, and my cosigner is less than willing to sign again. What options are there for consolidating a large amount of student loan debt? Edit: I have considered federal consolidation for the Stafford loans, but that's only a drop in the bucket compared to the private loans.
2011/02/07
[ "https://money.stackexchange.com/questions/6144", "https://money.stackexchange.com", "https://money.stackexchange.com/users/2694/" ]
To add to @bstpierre's answer, you should automate all your loans except for the one with the highest interest rate. Leave that one manual, and pay the most you can afford each month, to pay it off as quickly as possible. Once you finish that loan, move to the next highest interest rate. Ultimately, this won't be quite as convenient as just having 1 loan. The differences are: 1. You need to set up all the automatic payments. This is probably comparable to in complexity of consolidating your loans. 2. Each time you finish one loan, you need to turn off an automatic payment, and start doing the next loan manually. If you organize yourself well initially, you'll know exactly what order to do the loans in, so this shouldn't take too long. However, unless your consolidated loan has the same interest rate of your cheapest current loan, you will likely save money over-all by using this method.
I can't help you with consolidation, but I'd suggest automating as much of the payments as possible. * Do your lenders support automatic debit of your checking for the payments? * Can you use online bill pay to make the payments? If not, you might take a look at any of the numerous online banks that have online bill pay, and open an account with them. (E.g. ING Direct, Ally, etc.) You can set up the online account to pull from your current checking/savings account, and then make payments from that online account to your loans. When you have that set up, if there is some extra payment you want to make, you can set up an automatic additional periodic payment to get rid of one lender at a time until everything is paid off.
59,808,007
I'm working on this guessing game where the user needs to guess the word in under 6 tries. They have the ability to try and guess the whole word but if guessed incorrectly the game ends. When the game ends it gives them the option to play again. My problem is that when I try to guess the word for the second time it gives me an error only when I enter `n` character. I'm later going to replace add an array instead of the static BRAIN word and randomize it but I want to figure this out. Here is the code: ``` /* * WordGuess.java */ import java.util.Scanner; /** * Plays a word guessing game with one player. * */ public class WordGuess { //Main meathod public static void main(String[] arqs) { final String SECRET_WORD = "BRAIN"; final String FLAG = "!"; String wordSoFar = "", updatedWord = ""; String letterGuess, wordGuess = ""; int numGuesses = 0; String repeat = ""; Scanner input = new Scanner(System.in); /* begin game */ System. out. println ( "World Guess game. \n" ); do{ numGuesses = 0; wordSoFar = ""; updatedWord = ""; for (int i = 0; i < SECRET_WORD.length() ; i++) { wordSoFar += "-"; //word, as dashes } System.out.println("Your word is "); System.out.println(wordSoFar + "\n"); //displays dashes /* a11ow player to make guesses */ do{ System.out.print("Enter a letter (" + FLAG + " to guess entire world): "); letterGuess = input.nextLine(); letterGuess = letterGuess.toUpperCase() ; /* increment number of guesses */ //numGuesses += 1; /* player correctly guessed a letter--excract string in wordSoFar * up to the letter guessed and then append guessed. letter to that * string Next, extract rest of wordSoFar and append after the guessed * letter */ if (SECRET_WORD.indexOf(letterGuess) >= 0) { updatedWord = wordSoFar.substring(0, SECRET_WORD.indexOf(letterGuess)); updatedWord += letterGuess; updatedWord += wordSoFar.substring(SECRET_WORD.indexOf(letterGuess)+1, wordSoFar. length() ) ; wordSoFar = updatedWord; }else { numGuesses += 1; } /* display guessed letter instead of dash */ System.out.println(wordSoFar + "\n"); } while (!letterGuess.equals(FLAG) && !wordSoFar.equals(SECRET_WORD) && numGuesses < 6); /* finish game anil display message anil number of guesses */ if (letterGuess.equals(FLAG)) { System.out.println("What is your guess? "); wordGuess = input.nextLine() ; wordGuess = wordGuess.toUpperCase() ; } if (wordGuess.equals(SECRET_WORD) || wordSoFar.equals(SECRET_WORD)) { System.out.println ( "You won! " ) ; } else { System.out.println("Sorry. You 1ose."); } System.out.println("The secret word is " + SECRET_WORD); System.out.println("You made " + numGuesses + " mistake."); System.out.println("Would you like to play again?"); repeat = input.next(); }while(repeat.equalsIgnoreCase("Y")); System.out.println("GOOD BYE THANKS FOR PLAYING!"); } }//end of Word Guess class ```
2020/01/19
[ "https://Stackoverflow.com/questions/59808007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10939155/" ]
Before returning a widget in the future builder, you can check if the date condition is satisfied. ``` if (snapshot.data != null) { return Container( child: ListView.builder( itemCount: snapshot.data.length, itemBuilder: (BuildContext conxt, int index) { if(snapshot.data[index]['allocation_date'] == '2008-08-31'){ return Card(..... . . . else{ return Container(height: 0); //return a container with zero height in the else case because you cant return a null and your return must be a widget } . . . ```
You can create a filter icon above the listview, so you can use the date picker to select the date and based on the date you can filter the list and show it in your list view. let me know if this works for you. Thanks
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
Subversion is a version control system not a deployment system. Don't use it. Since you are doing everything manual right now (building & test) I would also deploy manually, that can also mean that you write some scripts that check the right version out from subversion and deploy it to whatever environment you want it to. If you want to automate more, I would recommend a CI server or some sort of deployment solution for that. We are starting to use Hudson for testing and deployment (at least for the sandbox environment). We don't intend to use it for production. Because we did not check into the promotion plugin yet. When researching CI servers, I noticed that commercial systems usually offer a better support for release management.
There are several ways that you can do this: **Use a build server** I've heard of teams using CCNET.net or FinalBuilder Server for this. Basically, what happens is that the build script has code to push the latest build, every time somebody makes a check in. I wouldn't recommend this for production though. This should work fine for a staging environment though. I'm not very familiar with build servers on Linux, but I know that there are a few. There's also Ant, and even Make scripts that could be used for this. **Put a working copy on the staging server** Just do a check out, and map the correct folder to be the root of the web app. Somebody on the team will have to manually update this working copy, but this gives you the flexibility to revert to a previous version if necessary. **Caveats** You'll need to make sure that you exclude the .svn folders when you pointing the website to the working copy. I wouldn't recommend using a Subversion hook script for this. You can pretty much use any scripting engine that available in Linux to do post-commit scripts. I typed "post-commit hook script linux" in Google, and got some good hits.
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
Subversion is a version control system not a deployment system. Don't use it. Since you are doing everything manual right now (building & test) I would also deploy manually, that can also mean that you write some scripts that check the right version out from subversion and deploy it to whatever environment you want it to. If you want to automate more, I would recommend a CI server or some sort of deployment solution for that. We are starting to use Hudson for testing and deployment (at least for the sandbox environment). We don't intend to use it for production. Because we did not check into the promotion plugin yet. When researching CI servers, I noticed that commercial systems usually offer a better support for release management.
This question is really a question about release procedures (and tools), rather than system administration, but here's my best answer: Any recent version of Subversion takes excellent care of your configuration management needs, but, like Peter said, it's not a deployment tool. One option would be to build deployment into your regular build infrastructure (e.g 'make deploy') and manage your deployment rules alongside your code. From a configuration management point of view, you need to keep track of everything your application needs to function, including code, external libraries (in specific versions), webserver, OS versions, etc. 'make deploy' should try to ensure all those things exist before it attempts to deploy a new version. Tools like Hudson can also handle deployment for you, but you'll still need to tell it what to do and I simply prefer to keep my configuration management procedures as simple as possible. One example would be to let Hudson invoke 'make deploy' but store no other information in Hudson that you'd need to recover to recreate on additional machines. How often are you going to be doing releases that need to be deployed? I would consider something along the lines of tagging your webapp into tags/ and having a post-commit mechanism that knows that tags/webapp-1.0.4 needs to be exported to your webroot. If your webapp is large, consider having the hook drop a special file in /tmp which a cronjob checks every minute and takes appropriate action on. If you want more detailed answer, please elaborate on your release schedule, size of codebase, choice of language, OS environment and dependencies.
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
Subversion is a version control system not a deployment system. Don't use it. Since you are doing everything manual right now (building & test) I would also deploy manually, that can also mean that you write some scripts that check the right version out from subversion and deploy it to whatever environment you want it to. If you want to automate more, I would recommend a CI server or some sort of deployment solution for that. We are starting to use Hudson for testing and deployment (at least for the sandbox environment). We don't intend to use it for production. Because we did not check into the promotion plugin yet. When researching CI servers, I noticed that commercial systems usually offer a better support for release management.
We also use Subversion to control our source, but use Webistrano to deploy from Subversion to our servers. [Webistrano](https://github.com/peritor/webistrano) is a web-frontend to [Capistrano](https://github.com/capistrano/capistrano/wiki), a popular deployment and automation tool in the Ruby community. It allows you to describe your deployment process in Ruby scripts (most functionality is built-in). It's quite flexible and easy to understand. Deploying and rolling back deploys is easy, as well as hooking in other tasks that need to be done, like flushing caches or migrating databases.
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
Subversion is a version control system not a deployment system. Don't use it. Since you are doing everything manual right now (building & test) I would also deploy manually, that can also mean that you write some scripts that check the right version out from subversion and deploy it to whatever environment you want it to. If you want to automate more, I would recommend a CI server or some sort of deployment solution for that. We are starting to use Hudson for testing and deployment (at least for the sandbox environment). We don't intend to use it for production. Because we did not check into the promotion plugin yet. When researching CI servers, I noticed that commercial systems usually offer a better support for release management.
I was able to do this by creating a fresh *post-commit* file with the following two lines: ``` #!/bin/bash ssh -i /path/to/key-file -pSSH-PORT user@hostname svn update /path/to/project/folder/ ```
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
There are several ways that you can do this: **Use a build server** I've heard of teams using CCNET.net or FinalBuilder Server for this. Basically, what happens is that the build script has code to push the latest build, every time somebody makes a check in. I wouldn't recommend this for production though. This should work fine for a staging environment though. I'm not very familiar with build servers on Linux, but I know that there are a few. There's also Ant, and even Make scripts that could be used for this. **Put a working copy on the staging server** Just do a check out, and map the correct folder to be the root of the web app. Somebody on the team will have to manually update this working copy, but this gives you the flexibility to revert to a previous version if necessary. **Caveats** You'll need to make sure that you exclude the .svn folders when you pointing the website to the working copy. I wouldn't recommend using a Subversion hook script for this. You can pretty much use any scripting engine that available in Linux to do post-commit scripts. I typed "post-commit hook script linux" in Google, and got some good hits.
We also use Subversion to control our source, but use Webistrano to deploy from Subversion to our servers. [Webistrano](https://github.com/peritor/webistrano) is a web-frontend to [Capistrano](https://github.com/capistrano/capistrano/wiki), a popular deployment and automation tool in the Ruby community. It allows you to describe your deployment process in Ruby scripts (most functionality is built-in). It's quite flexible and easy to understand. Deploying and rolling back deploys is easy, as well as hooking in other tasks that need to be done, like flushing caches or migrating databases.
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
There are several ways that you can do this: **Use a build server** I've heard of teams using CCNET.net or FinalBuilder Server for this. Basically, what happens is that the build script has code to push the latest build, every time somebody makes a check in. I wouldn't recommend this for production though. This should work fine for a staging environment though. I'm not very familiar with build servers on Linux, but I know that there are a few. There's also Ant, and even Make scripts that could be used for this. **Put a working copy on the staging server** Just do a check out, and map the correct folder to be the root of the web app. Somebody on the team will have to manually update this working copy, but this gives you the flexibility to revert to a previous version if necessary. **Caveats** You'll need to make sure that you exclude the .svn folders when you pointing the website to the working copy. I wouldn't recommend using a Subversion hook script for this. You can pretty much use any scripting engine that available in Linux to do post-commit scripts. I typed "post-commit hook script linux" in Google, and got some good hits.
I was able to do this by creating a fresh *post-commit* file with the following two lines: ``` #!/bin/bash ssh -i /path/to/key-file -pSSH-PORT user@hostname svn update /path/to/project/folder/ ```
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
This question is really a question about release procedures (and tools), rather than system administration, but here's my best answer: Any recent version of Subversion takes excellent care of your configuration management needs, but, like Peter said, it's not a deployment tool. One option would be to build deployment into your regular build infrastructure (e.g 'make deploy') and manage your deployment rules alongside your code. From a configuration management point of view, you need to keep track of everything your application needs to function, including code, external libraries (in specific versions), webserver, OS versions, etc. 'make deploy' should try to ensure all those things exist before it attempts to deploy a new version. Tools like Hudson can also handle deployment for you, but you'll still need to tell it what to do and I simply prefer to keep my configuration management procedures as simple as possible. One example would be to let Hudson invoke 'make deploy' but store no other information in Hudson that you'd need to recover to recreate on additional machines. How often are you going to be doing releases that need to be deployed? I would consider something along the lines of tagging your webapp into tags/ and having a post-commit mechanism that knows that tags/webapp-1.0.4 needs to be exported to your webroot. If your webapp is large, consider having the hook drop a special file in /tmp which a cronjob checks every minute and takes appropriate action on. If you want more detailed answer, please elaborate on your release schedule, size of codebase, choice of language, OS environment and dependencies.
We also use Subversion to control our source, but use Webistrano to deploy from Subversion to our servers. [Webistrano](https://github.com/peritor/webistrano) is a web-frontend to [Capistrano](https://github.com/capistrano/capistrano/wiki), a popular deployment and automation tool in the Ruby community. It allows you to describe your deployment process in Ruby scripts (most functionality is built-in). It's quite flexible and easy to understand. Deploying and rolling back deploys is easy, as well as hooking in other tasks that need to be done, like flushing caches or migrating databases.
97,022
We are building a web app and are almost ready to start deployment to a production server. We are using Subversion for version control and I'm now wondering what the best way would be to deploy to staging and later to production. Right now we develop and test with 2 persons locally on our own machines and commit to our staging server which is our SVN server. I know there is a post-commit.tmpl hook which can run a script? Does anyone know a good resource for that kind of scripts. Any tips are welcome! We are looking for an easy way to deploy and possibly revert our code to a previous version.
2009/12/23
[ "https://serverfault.com/questions/97022", "https://serverfault.com", "https://serverfault.com/users/29990/" ]
This question is really a question about release procedures (and tools), rather than system administration, but here's my best answer: Any recent version of Subversion takes excellent care of your configuration management needs, but, like Peter said, it's not a deployment tool. One option would be to build deployment into your regular build infrastructure (e.g 'make deploy') and manage your deployment rules alongside your code. From a configuration management point of view, you need to keep track of everything your application needs to function, including code, external libraries (in specific versions), webserver, OS versions, etc. 'make deploy' should try to ensure all those things exist before it attempts to deploy a new version. Tools like Hudson can also handle deployment for you, but you'll still need to tell it what to do and I simply prefer to keep my configuration management procedures as simple as possible. One example would be to let Hudson invoke 'make deploy' but store no other information in Hudson that you'd need to recover to recreate on additional machines. How often are you going to be doing releases that need to be deployed? I would consider something along the lines of tagging your webapp into tags/ and having a post-commit mechanism that knows that tags/webapp-1.0.4 needs to be exported to your webroot. If your webapp is large, consider having the hook drop a special file in /tmp which a cronjob checks every minute and takes appropriate action on. If you want more detailed answer, please elaborate on your release schedule, size of codebase, choice of language, OS environment and dependencies.
I was able to do this by creating a fresh *post-commit* file with the following two lines: ``` #!/bin/bash ssh -i /path/to/key-file -pSSH-PORT user@hostname svn update /path/to/project/folder/ ```
237,523
Lets say my multinomial logistic regression predict that a chance of a sample belonging to a each class is A=0.6, B=0.3, C=0.1 How do I threshold this values to get just binary prediction of a sample belonging to a class, taking in to an account imbalances of classes. I know what I would do if it's just a binary decision (threshold based on classes prevalence), or if the classes are balanced (classify to a class with highest probability). My end goal is to get 3x3 confusion matrix
2016/09/29
[ "https://stats.stackexchange.com/questions/237523", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/53084/" ]
According to @cangrejo's answer: <https://stats.stackexchange.com/a/310956/194535>, suppose the original output probability of your model is the vector $v$, and then you can define the prior distribution: $\pi=(\frac{1}{\theta\_1}, \frac{1}{\theta\_2},..., \frac{1}{\theta\_N})$, for $\theta\_i \in (0,1)$ and $\sum\_i\theta\_i = 1$, where $N$ is the total number of labeled classes, $i$ is the class index. Take $v' = v \odot \pi$ as the new output probability of your model, where $\odot$ denotes an element-wise product. Now, your question can be reformulate to this: Finding the $\pi$ which optimize the metrics you have specified (eg. `roc_auc_score`) from the new output probability model. Once you find it, the $\theta s (\theta\_1, \theta\_2, ..., \theta\_N)$ is your optimal threshold for each classes. The Code part: --- 1. Create a `proxyModel` class which takes your original model object as an argument and return a `proxyModel` object. When you called `predict_proba()` through the `proxyModel` object, it will calculate new probability automatically based on the threshold you specified: ``` class proxyModel(): def __init__(self, origin_model): self.origin_model = origin_model def predict_proba(self, x, threshold_list=None): # get origin probability ori_proba = self.origin_model.predict_proba(x) # set default threshold if threshold_list is None: threshold_list = np.full(ori_proba[0].shape, 1) # get the output shape of threshold_list output_shape = np.array(threshold_list).shape # element-wise divide by the threshold of each classes new_proba = np.divide(ori_proba, threshold_list) # calculate the norm (sum of new probability of each classes) norm = np.linalg.norm(new_proba, ord=1, axis=1) # reshape the norm norm = np.broadcast_to(np.array([norm]).T, (norm.shape[0],output_shape[0])) # renormalize the new probability new_proba = np.divide(new_proba, norm) return new_proba def predict(self, x, threshold_list=None): return np.argmax(self.predict_proba(x, threshold_list), axis=1) ``` 2. Implement a score function: ``` def scoreFunc(model, X, y_true, threshold_list): y_pred = model.predict(X, threshold_list=threshold_list) y_pred_proba = model.predict_proba(X, threshold_list=threshold_list) ###### metrics ###### from sklearn.metrics import accuracy_score from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score from sklearn.metrics import f1_score accuracy = accuracy_score(y_true, y_pred) roc_auc = roc_auc_score(y_true, y_pred_proba, average='macro') pr_auc = average_precision_score(y_true, y_pred_proba, average='macro') f1_value = f1_score(y_true, y_pred, average='macro') return accuracy, roc_auc, pr_auc, f1_value ``` 3. Define `weighted_score_with_threshold()` function, which takes the threshold as input and return weighted score: ``` def weighted_score_with_threshold(threshold, model, X_test, Y_test, metrics='accuracy', delta=5e-5): # if the sum of thresholds were not between 1+delta and 1-delta, # return infinity (just for reduce the search space of the minimizaiton algorithm, # because the sum of thresholds should be as close to 1 as possible). threshold_sum = np.sum(threshold) if threshold_sum > 1+delta: return np.inf if threshold_sum < 1-delta: return np.inf # to avoid objective function jump into nan solution if np.isnan(threshold_sum): print("threshold_sum is nan") return np.inf # renormalize: the sum of threshold should be 1 normalized_threshold = threshold/threshold_sum # calculate scores based on thresholds # suppose it'll return 4 scores in a tuple: (accuracy, roc_auc, pr_auc, f1) scores = scoreFunc(model, X_test, Y_test, threshold_list=normalized_threshold) scores = np.array(scores) weight = np.array([1,1,1,1]) # Give the metric you want to maximize a bigger weight: if metrics == 'accuracy': weight = np.array([10,1,1,1]) elif metrics == 'roc_auc': weight = np.array([1,10,1,1]) elif metrics == 'pr_auc': weight = np.array([1,1,10,1]) elif metrics == 'f1': weight = np.array([1,1,1,10]) elif 'all': weight = np.array([1,1,1,1]) # return negatitive weighted sum (because you want to maximize the sum, # it's equivalent to minimize the negative sum) return -np.dot(weight, scores) ``` 4. Use optimize algorithm `differential_evolution()` (better then fmin) to find the optimal threshold: ``` from scipy import optimize output_class_num = Y_test.shape[1] bounds = optimize.Bounds([1e-5]*output_class_num,[1]*output_class_num) pmodel = proxyModel(model) result = optimize.differential_evolution(weighted_score_with_threshold, bounds, args=(pmodel, X_test, Y_test, 'accuracy')) # calculate threshold threshold = result.x/np.sum(result.x) # print the optimized score print(scoreFunc(model, X_test, Y_test, threshold_list=threshold)) ```
This was helpful, thanks! But it is not applicable during model training. When it comes to using this method after training the model (after finding the hyperparameters relevant to the model), it's valid; only that there has to be some way of standardizing this to avoid loss of generality and for it to be applicable on test data.
68,797,509
I’m new here and to web development so forgive me if I’m asking such a simple question. When I use a CSS debugger chrome extension, they work on websites but do not work on my local HTML file in the browser. Can anyone explain why and/or provide a solution as to how to get this working?
2021/08/16
[ "https://Stackoverflow.com/questions/68797509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16675972/" ]
Well, let me teach you a trick to you do not need an extension to "see" the elements if is that you want. You can paste it in the console of the developer mode. It will create an mouse event that will capture the tag which you mouse over, then outline it with random color: ``` document.addEventListener("mouseover", function(e){ e.fromElement.style.outline = ""; e.toElement.style.outline = '1px solid rgb(' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ')'; }) ``` **This one is more interesting because it leaves a trail of edges:** ``` javascript:document.addEventListener("mouseover", function(e){ e.path.forEach(function(i){ i.style.outline= '1px solid rgb(' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ',' + Math.floor(Math.random()*256) + ')'; }) }); document.addEventListener("mouseout", function(e){ e.path.forEach(function(i){ i.style.outline=""; }) }); ``` A best trick is to create a false favorite, and then edit it adding `javascript:` before the code. --------------------------------------------------------------------------------------------------
Which debugger are you using? if you are debugging layout for elements you can simply add the below line in css of a webpage to show outlines, like this: ```css * { outline: 1px solid red; } ``` For example: ```css * { outline: 1px solid red; } div { width: 100vw; height: 100vh; } ``` ```html <div></div> ```
38,128,345
I have a vector of integers like this: ``` a <- c(2,3,4,1,2,1,3,5,6,3,2) values<-c(1,2,3,4,5,6) ``` I want to list, for every unique value in my vector (the unique values being ordered), the position of their occurences. My desired output: ``` rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9)) ```
2016/06/30
[ "https://Stackoverflow.com/questions/38128345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175156/" ]
You can do this, using `sapply`. The ordering that you need is ensured by the `sort` function. ``` sapply(sort(unique(a)), function(x) which(a %in% x)) #### [[1]] #### [1] 4 6 #### #### [[2]] #### [1] 1 5 11 #### ... ``` It will result in a list, giving the indices of your repetitions. It can't be a data.frame because a data.frame needs to have columns of same lengths. `sort(unique(a))` is exactly your `vector` variable. NOTE: you can also use `lapply` to force the output to be a list. With `sapply`, you get a list except if by chance the number of replicates is always the same, then the output will be a matrix... so, your choice!
You can use the `lapply` function to return a list with the indexes. `lapply(values, function (x) which(a == x))`
38,128,345
I have a vector of integers like this: ``` a <- c(2,3,4,1,2,1,3,5,6,3,2) values<-c(1,2,3,4,5,6) ``` I want to list, for every unique value in my vector (the unique values being ordered), the position of their occurences. My desired output: ``` rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9)) ```
2016/06/30
[ "https://Stackoverflow.com/questions/38128345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175156/" ]
`split` fits pretty well here, which returns a list of indexes for each unique value in `a`: ``` indList <- split(seq_along(a), a) indList # $`1` # [1] 4 6 # # $`2` # [1] 1 5 11 # # $`3` # [1] 2 7 10 # # $`4` # [1] 3 # # $`5` # [1] 8 # # $`6` # [1] 9 ``` And you can access the index by passing the value as a character, i.e.: ``` indList[["1"]] # [1] 4 6 ```
You can do this, using `sapply`. The ordering that you need is ensured by the `sort` function. ``` sapply(sort(unique(a)), function(x) which(a %in% x)) #### [[1]] #### [1] 4 6 #### #### [[2]] #### [1] 1 5 11 #### ... ``` It will result in a list, giving the indices of your repetitions. It can't be a data.frame because a data.frame needs to have columns of same lengths. `sort(unique(a))` is exactly your `vector` variable. NOTE: you can also use `lapply` to force the output to be a list. With `sapply`, you get a list except if by chance the number of replicates is always the same, then the output will be a matrix... so, your choice!
38,128,345
I have a vector of integers like this: ``` a <- c(2,3,4,1,2,1,3,5,6,3,2) values<-c(1,2,3,4,5,6) ``` I want to list, for every unique value in my vector (the unique values being ordered), the position of their occurences. My desired output: ``` rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9)) ```
2016/06/30
[ "https://Stackoverflow.com/questions/38128345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175156/" ]
`split` fits pretty well here, which returns a list of indexes for each unique value in `a`: ``` indList <- split(seq_along(a), a) indList # $`1` # [1] 4 6 # # $`2` # [1] 1 5 11 # # $`3` # [1] 2 7 10 # # $`4` # [1] 3 # # $`5` # [1] 8 # # $`6` # [1] 9 ``` And you can access the index by passing the value as a character, i.e.: ``` indList[["1"]] # [1] 4 6 ```
You can use the `lapply` function to return a list with the indexes. `lapply(values, function (x) which(a == x))`
38,128,345
I have a vector of integers like this: ``` a <- c(2,3,4,1,2,1,3,5,6,3,2) values<-c(1,2,3,4,5,6) ``` I want to list, for every unique value in my vector (the unique values being ordered), the position of their occurences. My desired output: ``` rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9)) ```
2016/06/30
[ "https://Stackoverflow.com/questions/38128345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175156/" ]
Perhaps this also works ``` order(match(a, values)) #[1] 4 6 1 5 11 2 7 10 3 8 9 ```
You can use the `lapply` function to return a list with the indexes. `lapply(values, function (x) which(a == x))`
38,128,345
I have a vector of integers like this: ``` a <- c(2,3,4,1,2,1,3,5,6,3,2) values<-c(1,2,3,4,5,6) ``` I want to list, for every unique value in my vector (the unique values being ordered), the position of their occurences. My desired output: ``` rep_indx<-data.frame(c(4,6),c(1,5,11),c(2,7,10),c(3),c(8),c(9)) ```
2016/06/30
[ "https://Stackoverflow.com/questions/38128345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175156/" ]
`split` fits pretty well here, which returns a list of indexes for each unique value in `a`: ``` indList <- split(seq_along(a), a) indList # $`1` # [1] 4 6 # # $`2` # [1] 1 5 11 # # $`3` # [1] 2 7 10 # # $`4` # [1] 3 # # $`5` # [1] 8 # # $`6` # [1] 9 ``` And you can access the index by passing the value as a character, i.e.: ``` indList[["1"]] # [1] 4 6 ```
Perhaps this also works ``` order(match(a, values)) #[1] 4 6 1 5 11 2 7 10 3 8 9 ```
15,460,039
I'm currently working on load balancing project. I need access to the file on another computer connected to mine over LAN so that I could balance the disk space of that computer. Is there any way possible to do this using java? like how i can display all the files stored in the other computer in something like a tree?? using java.
2013/03/17
[ "https://Stackoverflow.com/questions/15460039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2179089/" ]
Java doesn't provide a native method to achieve that. The easiest way might be to use NFS mount the other computers' disks to your computer, then your Java code could operate those remote disk just like local disk.
First, you have to share the file over the Network, and give the remote computer read/write permissions to all the files. Then you can use the java.nio classes to do it very easily: ``` import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class MoveRemoteFiles { public static void main(String[] args) throws IOException { String originalLocation = "\\\\NETWORK-LOCATION\\MyFile.txt"; String newLocation = "\\\\NETWORK-LOCATION\\MyFile_2.txt"; Path originalPath = Paths.get(originalLocation); Files.move(originalPath, Paths.get(newLocation)); } } ``` And regarding the listing of all files, I'd recommend using the [Apache Commons IO](http://commons.apache.org/proper/commons-io//) library with the `FileUtils.listFiles()` method to save time engineering your own solution, like so: ``` import java.io.File; import java.util.Collection; import org.apache.commons.io.FileUtils; public class ListRemoteFiles { public static void main(String[] args) { String originalLocation = "\\\\NETWORK-LOCATION\\Folder\\"; //List all files of all extensions (No Folders) Collection<File> files = FileUtils.listFiles(new File(originalLocation), null, true); //List all files and folders Collection<File> filesAndFolders = FileUtils.listFilesAndDirs ( new File(originalLocation), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); } } ``` And then you can use the method above to move them after.
58,212,508
I'm new to C++ I don't understand why I'm getting this error. Out of 5 statements that are similar 3 mark error but the other two are okay. The error is in the main function. ``` #include <iostream> using namespace std; // Function declaration void getGallons(int wall); void getHours(int gallons); void getCostpaint(int gallons, int pricePaint); void getLaborcharges(int hours); void getTotalcost(int costPaint, int laborCharges); // Function definition void getGallons(int wall) { int gallons; gallons = wall / 112; cout << "Number of gallons of paint required: " << gallons << endl; } // Function definition void getHours(int gallons) { int hours; hours = gallons * 8; cout << "Hours of labor required: " << hours << endl; } // Function definition void getCostpaint(int gallons, int pricePaint) { int costPaint; costPaint = gallons * pricePaint; cout << "The cost of paint: " << costPaint << endl; } // Function definition void getLaborcharges(int hours) { int laborCharges; laborCharges = hours * 35; cout << "The labor charge: " << laborCharges << endl; } // Funtion definition void getTotalcost(int costPaint, int laborCharges) { int totalCost; totalCost = costPaint + laborCharges; cout << "The total cost of the job: " << totalCost << endl; } // The main method int main() { int wall; int pricePaint; cout << "Enter square feet of wall: "; cin >> wall; cout << "Enter price of paint per gallon: "; cin >> pricePaint; getGallons(wall); getHours(gallons); // error here getCostpaint(gallons, pricePaint); getLaborcharges(hours); // error here getTotalcost(costPaint, laborCharges); //error here return 0; } ``` This lesson focused on using functions and passing parameters in the code. I'm not supposed to use global variables. If you have a better way to do this please share.
2019/10/03
[ "https://Stackoverflow.com/questions/58212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12156468/" ]
Reducing to three lines (the other errors are analogous): ``` int wall; getGallons(wall); getHours(gallons); // error here ``` While `wall` is defined, `gallons` is not. And where do you want to get `gallons` from anyway? The result is hidden deep inside another function. How do you want to get it out from there? Well, you need a return value: ``` int getGallons(int wall) //^^^ ! { int gallons = wall / 112; // ... return gallons; // ! } ``` This way, you can use your function like this: ``` int gallons = getGallons(wall); // now gallons is defined and you can use it: getHours(gallons); ``` Analogously for the other functions and variables. Usually, it is *not* a good idea to mix logic (calculations) and output in the same fucntion. So I'd rather move writing to console into `main` function: ``` int getGallons(int wall) { return wall / 112; } int getHours(int gallons) { return gallons * 8; } int wall; std::cin >> wall; int gallons = getGallons(int wall); std::cout << ...; int hours = getHours(gallons); std::cout << ...; ``` Notice? All input/output now is at the same level... Side note: It is not necessary to declare functions before defining them if you don't use them before definition: ``` //void f(); // CAN be ommitted void f() { }; void g() { f(); } ``` Counter-example: ``` void f(); void g() { f(); } // now using f before it is defined, thus you NEED do declare it void f() { }; ``` If you still want to keep the declarations is rather a matter of style (but will get important when managing code in different compilation units, as you'd then have the declarations in header files – you'll encounter soon in next lessons).
Reason is variables are not defined before they are used. Following changes added to the code. * since you have named functions as "getSomeValue()" better to use a return type instead of void. * its better to use double instead of int, because there are divisions in the calculation * also used nested function calls to reduce number of lines of code. Fixed Code: ``` #include <iostream> using namespace std; // Function declaration int getGallons(int wall); int getHours(int gallons); int getCostpaint(int gallons, int pricePaint); int getLaborcharges(int hours); int getTotalcost(int costPaint, int laborCharges); // Function definition int getGallons(int wall) { int gallons; gallons = wall / 112; cout << "Number of gallons of paint required: " << gallons << endl; return gallons; } // Function definition int getHours(int gallons) { int hours; hours = gallons * 8; cout << "Hours of labor required: " << hours << endl; return hours; } // Function definition int getCostpaint(int gallons, int pricePaint) { int costPaint; costPaint = gallons * pricePaint; cout << "The cost of paint: " << costPaint << endl; return costPaint; } // Function definition int getLaborcharges(int hours) { int laborCharges; laborCharges = hours * 35; cout << "The labor charge: " << laborCharges << endl; return laborCharges; } // Funtion definition int getTotalcost(int costPaint, int laborCharges) { int totalCost; totalCost = costPaint + laborCharges; cout << "The total cost of the job: " << totalCost << endl; return totalCost; } // The main method int main() { int wall; int pricePaint; cout << "Enter square feet of wall: "; cin >> wall; cout << "Enter price of paint per gallon: "; cin >> pricePaint; int costPaint = getCostpaint(getGallons(wall), pricePaint); int laborCharges = getLaborcharges(getHours(getGallons(wall))); getTotalcost(costPaint, laborCharges); return 0; } ```
58,212,508
I'm new to C++ I don't understand why I'm getting this error. Out of 5 statements that are similar 3 mark error but the other two are okay. The error is in the main function. ``` #include <iostream> using namespace std; // Function declaration void getGallons(int wall); void getHours(int gallons); void getCostpaint(int gallons, int pricePaint); void getLaborcharges(int hours); void getTotalcost(int costPaint, int laborCharges); // Function definition void getGallons(int wall) { int gallons; gallons = wall / 112; cout << "Number of gallons of paint required: " << gallons << endl; } // Function definition void getHours(int gallons) { int hours; hours = gallons * 8; cout << "Hours of labor required: " << hours << endl; } // Function definition void getCostpaint(int gallons, int pricePaint) { int costPaint; costPaint = gallons * pricePaint; cout << "The cost of paint: " << costPaint << endl; } // Function definition void getLaborcharges(int hours) { int laborCharges; laborCharges = hours * 35; cout << "The labor charge: " << laborCharges << endl; } // Funtion definition void getTotalcost(int costPaint, int laborCharges) { int totalCost; totalCost = costPaint + laborCharges; cout << "The total cost of the job: " << totalCost << endl; } // The main method int main() { int wall; int pricePaint; cout << "Enter square feet of wall: "; cin >> wall; cout << "Enter price of paint per gallon: "; cin >> pricePaint; getGallons(wall); getHours(gallons); // error here getCostpaint(gallons, pricePaint); getLaborcharges(hours); // error here getTotalcost(costPaint, laborCharges); //error here return 0; } ``` This lesson focused on using functions and passing parameters in the code. I'm not supposed to use global variables. If you have a better way to do this please share.
2019/10/03
[ "https://Stackoverflow.com/questions/58212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12156468/" ]
Reducing to three lines (the other errors are analogous): ``` int wall; getGallons(wall); getHours(gallons); // error here ``` While `wall` is defined, `gallons` is not. And where do you want to get `gallons` from anyway? The result is hidden deep inside another function. How do you want to get it out from there? Well, you need a return value: ``` int getGallons(int wall) //^^^ ! { int gallons = wall / 112; // ... return gallons; // ! } ``` This way, you can use your function like this: ``` int gallons = getGallons(wall); // now gallons is defined and you can use it: getHours(gallons); ``` Analogously for the other functions and variables. Usually, it is *not* a good idea to mix logic (calculations) and output in the same fucntion. So I'd rather move writing to console into `main` function: ``` int getGallons(int wall) { return wall / 112; } int getHours(int gallons) { return gallons * 8; } int wall; std::cin >> wall; int gallons = getGallons(int wall); std::cout << ...; int hours = getHours(gallons); std::cout << ...; ``` Notice? All input/output now is at the same level... Side note: It is not necessary to declare functions before defining them if you don't use them before definition: ``` //void f(); // CAN be ommitted void f() { }; void g() { f(); } ``` Counter-example: ``` void f(); void g() { f(); } // now using f before it is defined, thus you NEED do declare it void f() { }; ``` If you still want to keep the declarations is rather a matter of style (but will get important when managing code in different compilation units, as you'd then have the declarations in header files – you'll encounter soon in next lessons).
Here are a few errors/issues 1. You have function declarations which are redundant. You only need them if you plan on calling the function before the definition. 2. In your main method, you don't declare gallons 3. In your main method, you don't give values for wall and pricepaint. 4. In your functions, you operate via side effects, meaning you print to the console, rather than returning anything.
58,212,508
I'm new to C++ I don't understand why I'm getting this error. Out of 5 statements that are similar 3 mark error but the other two are okay. The error is in the main function. ``` #include <iostream> using namespace std; // Function declaration void getGallons(int wall); void getHours(int gallons); void getCostpaint(int gallons, int pricePaint); void getLaborcharges(int hours); void getTotalcost(int costPaint, int laborCharges); // Function definition void getGallons(int wall) { int gallons; gallons = wall / 112; cout << "Number of gallons of paint required: " << gallons << endl; } // Function definition void getHours(int gallons) { int hours; hours = gallons * 8; cout << "Hours of labor required: " << hours << endl; } // Function definition void getCostpaint(int gallons, int pricePaint) { int costPaint; costPaint = gallons * pricePaint; cout << "The cost of paint: " << costPaint << endl; } // Function definition void getLaborcharges(int hours) { int laborCharges; laborCharges = hours * 35; cout << "The labor charge: " << laborCharges << endl; } // Funtion definition void getTotalcost(int costPaint, int laborCharges) { int totalCost; totalCost = costPaint + laborCharges; cout << "The total cost of the job: " << totalCost << endl; } // The main method int main() { int wall; int pricePaint; cout << "Enter square feet of wall: "; cin >> wall; cout << "Enter price of paint per gallon: "; cin >> pricePaint; getGallons(wall); getHours(gallons); // error here getCostpaint(gallons, pricePaint); getLaborcharges(hours); // error here getTotalcost(costPaint, laborCharges); //error here return 0; } ``` This lesson focused on using functions and passing parameters in the code. I'm not supposed to use global variables. If you have a better way to do this please share.
2019/10/03
[ "https://Stackoverflow.com/questions/58212508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12156468/" ]
Reason is variables are not defined before they are used. Following changes added to the code. * since you have named functions as "getSomeValue()" better to use a return type instead of void. * its better to use double instead of int, because there are divisions in the calculation * also used nested function calls to reduce number of lines of code. Fixed Code: ``` #include <iostream> using namespace std; // Function declaration int getGallons(int wall); int getHours(int gallons); int getCostpaint(int gallons, int pricePaint); int getLaborcharges(int hours); int getTotalcost(int costPaint, int laborCharges); // Function definition int getGallons(int wall) { int gallons; gallons = wall / 112; cout << "Number of gallons of paint required: " << gallons << endl; return gallons; } // Function definition int getHours(int gallons) { int hours; hours = gallons * 8; cout << "Hours of labor required: " << hours << endl; return hours; } // Function definition int getCostpaint(int gallons, int pricePaint) { int costPaint; costPaint = gallons * pricePaint; cout << "The cost of paint: " << costPaint << endl; return costPaint; } // Function definition int getLaborcharges(int hours) { int laborCharges; laborCharges = hours * 35; cout << "The labor charge: " << laborCharges << endl; return laborCharges; } // Funtion definition int getTotalcost(int costPaint, int laborCharges) { int totalCost; totalCost = costPaint + laborCharges; cout << "The total cost of the job: " << totalCost << endl; return totalCost; } // The main method int main() { int wall; int pricePaint; cout << "Enter square feet of wall: "; cin >> wall; cout << "Enter price of paint per gallon: "; cin >> pricePaint; int costPaint = getCostpaint(getGallons(wall), pricePaint); int laborCharges = getLaborcharges(getHours(getGallons(wall))); getTotalcost(costPaint, laborCharges); return 0; } ```
Here are a few errors/issues 1. You have function declarations which are redundant. You only need them if you plan on calling the function before the definition. 2. In your main method, you don't declare gallons 3. In your main method, you don't give values for wall and pricepaint. 4. In your functions, you operate via side effects, meaning you print to the console, rather than returning anything.
51,983,019
Skip to EDIT2 which works There is: * Project (has\_many :group\_permissions) * GroupPermission (belongs\_to :project) I have a form where you can create a new project. A project has several attributes like name, status etc. and now important: iit. iit is selectable with radio buttons: yes or no. What I want: If someone selects **yes** on iit in the Project form, there should be a new record in GroupPermission. So in EVERY project where iit= 1 there should be a certain GroupPermisson. Can I make / check this in the GroupPermission model? Like if ``` class GroupPermission < ActiveRecord::Base if Project.where(iit: 1) make me a record for each project end ``` Can I even make database entries in the model like so? Is this the right way? **EDIT1:** In the Project controller I added: ``` if params[:iit] = 1 record = GroupPermission.new(cn: 'ccc-ml', project_id: params[:id]) record.save end ``` It then adds a new record in GroupPermissions. But I need the :id of the project. How can I access the id of the project which is about to be saved? **EDIT2** In the Project Controller ``` after_filter :iit_test, :only => [:create] ... private def iit_test if @trial.iit == 1 record = GroupPermission.new(cn: 'ccc-ml', project_id: @project.id, name: 'CATEGORY_3') record.save end ``` end EDIT2 works fine. I just have to check it with update etc. Thank you in advance.
2018/08/23
[ "https://Stackoverflow.com/questions/51983019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8609958/" ]
add your inputformatter as the first formatter `InputFormatters.Insert(0,new StringRawRequestBodyFormatter())` then in this formatter in CanRead method check if the parameter that is being bound has a custom attribute you specify alongside FromBody ``` public override Boolean CanRead(InputFormatterContext context) { if (context == null) throw new ArgumentNullException(nameof(context)); var contentType = context.HttpContext.Request.ContentType; if (supportedMimes.Contains(contentType) && context.Metadata is DefaultModelMetadata mt && mt.Attributes.ParameterAttributes.Any(a=>a.GetType().Equals(typeof(RawJsonAttribute)))) return true; else return false; } ``` Controller action:`public IActionResult BeginExportToFile([RawJson,FromBody] string expSvcConfigJsonStr)` So in simple terms this formatter will only be used for the supported mimes and for parameters that have a custom attribute. Hope it helps.
Yes this can be in the Startup.cs by adding a new route in the config method, you should have something like this by default you need to add a new one for the controller that you want: ``` app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); ``` Note: The order matters.
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
The reason it doesn't work is because *`T` is not known at compile time*. You are asking to take a list of a known type and use it as a list of an *unknown* type, which is not allowed (without dynamics or some other non-compile-time-type-safe mechanism). Since you're only supporting 4 types anyways, it sounds like you need four `search` methods that call a generic common method (if appropriate): ``` public IEnumerable<Doctor> searchDoctors(string field, string rangeStart, string rangeEnd = null) { List<Doctor> listToSearch = doctorList; // more code that isn't relevant to the question here } public IEnumerable<Patient> searchPatients(string field, string rangeStart, string rangeEnd = null) { List<Patient> listToSearch = patientList; // more code that isn't relevant to the question here } public IEnumerable<Visit> searchVisits(string field, string rangeStart, string rangeEnd = null) { List<Visit> listToSearch = visitList; // more code that isn't relevant to the question here } public IEnumerable<Treatment> searchTreatments(string field, string rangeStart, string rangeEnd = null) { List<Treatment> listToSearch = treatmentList; // more code that isn't relevant to the question here } ``` otherwise you're going to have a lot of code validating/casting/converting types that is susceptible to runtime errors. **Side note:** Since you are new to C# - I would recommend not trying to optimize/refactor too much using generics, etc. Write code that *works* (even if it's using copy-paste, not DRY, etc.), then make it *better*. Otherwise you spend a *lot* more time trying to shoehorn your program into some pattern that thinking about how the program *should* work.
The thing you are asking is not possible. I would recommend to type your `listToSearch` as `IList`. This will keep as much generic as you want. You can access all common list actions and you don't have to rely on generics. ``` IList listToSearch = null; ```
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
The reason it doesn't work is because *`T` is not known at compile time*. You are asking to take a list of a known type and use it as a list of an *unknown* type, which is not allowed (without dynamics or some other non-compile-time-type-safe mechanism). Since you're only supporting 4 types anyways, it sounds like you need four `search` methods that call a generic common method (if appropriate): ``` public IEnumerable<Doctor> searchDoctors(string field, string rangeStart, string rangeEnd = null) { List<Doctor> listToSearch = doctorList; // more code that isn't relevant to the question here } public IEnumerable<Patient> searchPatients(string field, string rangeStart, string rangeEnd = null) { List<Patient> listToSearch = patientList; // more code that isn't relevant to the question here } public IEnumerable<Visit> searchVisits(string field, string rangeStart, string rangeEnd = null) { List<Visit> listToSearch = visitList; // more code that isn't relevant to the question here } public IEnumerable<Treatment> searchTreatments(string field, string rangeStart, string rangeEnd = null) { List<Treatment> listToSearch = treatmentList; // more code that isn't relevant to the question here } ``` otherwise you're going to have a lot of code validating/casting/converting types that is susceptible to runtime errors. **Side note:** Since you are new to C# - I would recommend not trying to optimize/refactor too much using generics, etc. Write code that *works* (even if it's using copy-paste, not DRY, etc.), then make it *better*. Otherwise you spend a *lot* more time trying to shoehorn your program into some pattern that thinking about how the program *should* work.
I ran into something like this before I understood what generics are for. In my case I was trying to reduce the number of methods that were needed to add data to a handler before writing it as an `xml` file which isn't too far from what you are trying to accomplish. I was trying to reduce the number of exposed methods from 8 to 1. I ended up using an interface instead of a generic. In short, you probably can get your desired functionality by using an `interface` instead of a `generic`. D Stanley is correct. Write code that works, then improve. That way you can try something with the option of eliminating the changes to restore the functionality. Also, Eric Lippert wrote on the subject on Generics (the post is in stack overflow, I just can't find it right now) that if you write a method for using a generic and immediately throw in logic statements to sort out what the object type is, then you are using generics wrong.
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
The reason it doesn't work is because *`T` is not known at compile time*. You are asking to take a list of a known type and use it as a list of an *unknown* type, which is not allowed (without dynamics or some other non-compile-time-type-safe mechanism). Since you're only supporting 4 types anyways, it sounds like you need four `search` methods that call a generic common method (if appropriate): ``` public IEnumerable<Doctor> searchDoctors(string field, string rangeStart, string rangeEnd = null) { List<Doctor> listToSearch = doctorList; // more code that isn't relevant to the question here } public IEnumerable<Patient> searchPatients(string field, string rangeStart, string rangeEnd = null) { List<Patient> listToSearch = patientList; // more code that isn't relevant to the question here } public IEnumerable<Visit> searchVisits(string field, string rangeStart, string rangeEnd = null) { List<Visit> listToSearch = visitList; // more code that isn't relevant to the question here } public IEnumerable<Treatment> searchTreatments(string field, string rangeStart, string rangeEnd = null) { List<Treatment> listToSearch = treatmentList; // more code that isn't relevant to the question here } ``` otherwise you're going to have a lot of code validating/casting/converting types that is susceptible to runtime errors. **Side note:** Since you are new to C# - I would recommend not trying to optimize/refactor too much using generics, etc. Write code that *works* (even if it's using copy-paste, not DRY, etc.), then make it *better*. Otherwise you spend a *lot* more time trying to shoehorn your program into some pattern that thinking about how the program *should* work.
If you were, at least, returning `IEnumerable<T>` I could understand using the type parameter, but what you are doing here is reinventing method overloading. Try this: ``` public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart, string rangeEnd = null) { return Search(doctorList, field, rangeStart, rangeEnd); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart, string rangeEnd = null) { return Search(patientList, field, rangeStart, rangeEnd); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart, string rangeEnd = null) { return Search(visitList, field, rangeStart, rangeEnd); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart, string rangeEnd = null) { return Search(treatmentList, field, rangeStart, rangeEnd); } private IEnumerable<T> Search<T>(IEnumerable<T> list, string field, string rangeStart, string rangeEnd) { // more code that isn't relevant to the question here } ``` By the way, are you aware that default argument values are hardcode in the caller after compilation? Consider changing to this: ``` public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart) { return Search(doctorList, field, rangeStart); } public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart, string rangeEnd) { return Search(doctorList, field, rangeStart, rangeEnd); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart) { return Search(patientList, field, rangeStart); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart, string rangeEnd) { return Search(patientList, field, rangeStart, rangeEnd); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart) { return Search(visitList, field, rangeStart); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart, string rangeEnd) { return Search(visitList, field, rangeStart, rangeEnd); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart) { return Search(treatmentList, field, rangeStart); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart, string rangeEnd) { return Search(treatmentList, field, rangeStart, rangeEnd); } private IEnumerable<T> Search<T>(IEnumerable<T> list, string field, string rangeStart, string rangeEnd = null) { // more code that isn't relevant to the question here } ```
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
You can cast it to a `List<T>` by casting it to an object first: ``` if (typeof(T) == typeof(Doctor)) { listToSearch = (List<T>)(object)doctorList; } ```
The thing you are asking is not possible. I would recommend to type your `listToSearch` as `IList`. This will keep as much generic as you want. You can access all common list actions and you don't have to rely on generics. ``` IList listToSearch = null; ```
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
You can cast it to a `List<T>` by casting it to an object first: ``` if (typeof(T) == typeof(Doctor)) { listToSearch = (List<T>)(object)doctorList; } ```
I ran into something like this before I understood what generics are for. In my case I was trying to reduce the number of methods that were needed to add data to a handler before writing it as an `xml` file which isn't too far from what you are trying to accomplish. I was trying to reduce the number of exposed methods from 8 to 1. I ended up using an interface instead of a generic. In short, you probably can get your desired functionality by using an `interface` instead of a `generic`. D Stanley is correct. Write code that works, then improve. That way you can try something with the option of eliminating the changes to restore the functionality. Also, Eric Lippert wrote on the subject on Generics (the post is in stack overflow, I just can't find it right now) that if you write a method for using a generic and immediately throw in logic statements to sort out what the object type is, then you are using generics wrong.
22,636,332
I am using c# and have 4 existing lists, each of a different type (i.e. `List<Doctor>`, `List<Patient>` etc') I have a generic search method which receives type T and should search using LINQ the appropriate list based on the type T. I created a `var List<T> listToSearch` and wanted to set it to the appropriate list using if's, but I can't set `listToSearch` to any of them. Code: ``` // at class level: private List<Doctor> doctorList; private List<Patient> patientList; private List<Visit> visitList; private List<Treatment> treatmentList; public IEnumerable search<T>(string field, string rangeStart, string rangeEnd = null) { List<T> listToSearch = null; if (typeof(T) == typeof(Doctor)) { listToSearch = doctorList; } if (typeof(T) == typeof(Patient)) { listToSearch = patientList; } if (typeof(T) == typeof(Visit)) { listToSearch = visitList; } if (typeof(T) == typeof(Treatment)) { listToSearch = treatmentList; } // more code that isn't relevant to the question here } ``` Each `typeof(T)` line brings up an error: > > "Cannot implicitly convert type `'System.Collections.Generic.List<Doctor/Patient/Visit/Treatment>'` to `'System.Collections.Generic.List<T>'` > > > How do I change this code to allow for the use of Generic lists?
2014/03/25
[ "https://Stackoverflow.com/questions/22636332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1053122/" ]
You can cast it to a `List<T>` by casting it to an object first: ``` if (typeof(T) == typeof(Doctor)) { listToSearch = (List<T>)(object)doctorList; } ```
If you were, at least, returning `IEnumerable<T>` I could understand using the type parameter, but what you are doing here is reinventing method overloading. Try this: ``` public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart, string rangeEnd = null) { return Search(doctorList, field, rangeStart, rangeEnd); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart, string rangeEnd = null) { return Search(patientList, field, rangeStart, rangeEnd); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart, string rangeEnd = null) { return Search(visitList, field, rangeStart, rangeEnd); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart, string rangeEnd = null) { return Search(treatmentList, field, rangeStart, rangeEnd); } private IEnumerable<T> Search<T>(IEnumerable<T> list, string field, string rangeStart, string rangeEnd) { // more code that isn't relevant to the question here } ``` By the way, are you aware that default argument values are hardcode in the caller after compilation? Consider changing to this: ``` public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart) { return Search(doctorList, field, rangeStart); } public IEnumerable<Doctor> SearchDoctors(string field, string rangeStart, string rangeEnd) { return Search(doctorList, field, rangeStart, rangeEnd); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart) { return Search(patientList, field, rangeStart); } public IEnumerable<Patient> SearchPatients(string field, string rangeStart, string rangeEnd) { return Search(patientList, field, rangeStart, rangeEnd); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart) { return Search(visitList, field, rangeStart); } public IEnumerable<Visit> SearchVisits(string field, string rangeStart, string rangeEnd) { return Search(visitList, field, rangeStart, rangeEnd); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart) { return Search(treatmentList, field, rangeStart); } public IEnumerable<Treatment> SearchTreatments(string field, string rangeStart, string rangeEnd) { return Search(treatmentList, field, rangeStart, rangeEnd); } private IEnumerable<T> Search<T>(IEnumerable<T> list, string field, string rangeStart, string rangeEnd = null) { // more code that isn't relevant to the question here } ```
255,478
**Edit:** The original question before being re-edited too much: ``` \newcommand\divspace{\,} \[ \arraycolsep=0em \begin{array}{r@{\divspace}c@{\divspace}lllll} & & \multicolumn{4}{l}{7.24}& \\ \cline{2-6} 3427 &\big)&\multicolumn{6}{c}{24811.48}\\ & & 23989& \\ \cline{3-4} & & 8224&& \\ & & 6854&& \\ \cline{3-4} & & 13708&& \\ \cline{3-5} \end{array} \] ``` MWE say 300 div by 2 should give 150. ``` \documentclass{article} \begin{document} \newcommand\divspace{\,} \[ \arraycolsep=0em \begin{array}{r@{\divspace}c@{\divspace}lllll} & \multicolumn{3}{r}{150}\\ \cline{2-6} 2 &\big)&\multicolumn{3}{l}{300}&\\ & & 20&&&&\\ \cline{3-4} & & 10&0&&&\\ & & 10&0&&&\\ \cline{3-5} & & &0&0&& \end{array} \] \end{document} ```
2015/07/15
[ "https://tex.stackexchange.com/questions/255478", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10669/" ]
The mark up seems to complex; you want to align digits, so do it. ``` \documentclass{article} \begin{document} \[ \setlength{\arraycolsep}{0pt} \begin{array}{r@{\,}cccc} & & \multicolumn{3}{l}{150}\\ \cline{2-5} 2 &\big)& 3 & 0 & 0 \\ & & 2 & 0 & \\ \cline{3-5} & & 1 & 0 & 0 \\ & & 1 & 0 & 0 \\ \cline{3-5} & & & & 0 \end{array} \] \end{document} ``` ![enter image description here](https://i.stack.imgur.com/5MVzO.png)
Are you looking for a long division? How about something like this: ``` \documentclass{article} \input{longdiv} \begin{document} \longdiv{300}{2} \end{document} ``` > > ![enter image description here](https://i.stack.imgur.com/GkRHC.png) > > >
255,478
**Edit:** The original question before being re-edited too much: ``` \newcommand\divspace{\,} \[ \arraycolsep=0em \begin{array}{r@{\divspace}c@{\divspace}lllll} & & \multicolumn{4}{l}{7.24}& \\ \cline{2-6} 3427 &\big)&\multicolumn{6}{c}{24811.48}\\ & & 23989& \\ \cline{3-4} & & 8224&& \\ & & 6854&& \\ \cline{3-4} & & 13708&& \\ \cline{3-5} \end{array} \] ``` MWE say 300 div by 2 should give 150. ``` \documentclass{article} \begin{document} \newcommand\divspace{\,} \[ \arraycolsep=0em \begin{array}{r@{\divspace}c@{\divspace}lllll} & \multicolumn{3}{r}{150}\\ \cline{2-6} 2 &\big)&\multicolumn{3}{l}{300}&\\ & & 20&&&&\\ \cline{3-4} & & 10&0&&&\\ & & 10&0&&&\\ \cline{3-5} & & &0&0&& \end{array} \] \end{document} ```
2015/07/15
[ "https://tex.stackexchange.com/questions/255478", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/10669/" ]
I am sorry, but I witnessed the very first moment of posting the question and it was re-edited too much that it became another question. So, I re-posted the original question (which exactly conforms to the title). The incorrect placement of the dividend is shown by the code output: ![enter image description here](https://i.stack.imgur.com/AfrHn.png) To solve the problem correct the first row `\cline` to `\cline{2-7}` and second row as `\multicolumn{5}{c}{24811.48}` then make consistent number of `&`s in all rows: ``` \documentclass{article} \begin{document} \[ \setlength{\arraycolsep}{0pt} \begin{array}{rc*5{l}} & & \multicolumn{4}{l}{7.24}& \\ \cline{2-7} 3427\,&\big)\,&\multicolumn{5}{c}{24811.48} \\ & & 23989&&&& \\ \cline{3-4} & & 8224&& && \\ & & 6854&& && \\ \cline{3-4} & & 13708&&&& \\ \cline{3-5} \end{array} \] \end{document} ``` ![enter image description here](https://i.stack.imgur.com/IU9Ec.jpg) As pointed out by @egreg, however, the markup becomes too complex, especially if we also need align the digits (10 columns at least may be needed in this case). Yet a simple markup solution (three columns) with a typographically pleasing output plus aligned digits can be the following: ``` \documentclass{article} \begin{document} \[ \setlength{\arraycolsep}{0pt} \begin{array}{rcl} & & 7.24 \\ \cline{2-3} 3427\,&\big)\,& 24811.48 \\ & & \underline{23989_{}} \\ %\cline{3-3} & & \phantom{23}{8224} \\ & & \phantom{23}\underline{6854_{}} \\ %\cline{3-3} & & \phantom{23}{13708} \\ & & \phantom{23}\underline{13708_{}} \\ %\cline{3-3} & & \phantom{231370}0 \\ \end{array} \] \end{document} ``` ![enter image description here](https://i.stack.imgur.com/cyvi4.jpg) I used `\phantom{}` for alignment and replaced the `\cline`s with `\underline{}` to exactly fit the digits above. The extra `_{}` inside each `\underline{}` is to lower the line a bit for improving the visual appearance.
Are you looking for a long division? How about something like this: ``` \documentclass{article} \input{longdiv} \begin{document} \longdiv{300}{2} \end{document} ``` > > ![enter image description here](https://i.stack.imgur.com/GkRHC.png) > > >
53,917
I use worpress 3.3.2 and there several users in my multiblog. Only registered users can leave comments, but comments must be approved by post author or administrator. When some user makes a comment every author sees notification about new comment awaiting moderation. How can i hide notifications about comments that are awaiting moderation to other author's post? Maybe there is some plugin for this?
2012/06/01
[ "https://wordpress.stackexchange.com/questions/53917", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16650/" ]
No plug-in needed for this. Just open your theme files using the WordPress theme editor or via FTP. Look for the code that is being used to display the notice. It should be in the `index.php` file, maybe in a `content.php` file if your theme uses that, and in some cases it's in your `functions.php` file. It will use the exact text you're talking about so it should be easy to spot. You need to remove that or comment it out so it doesn't show. If you find it but can't remove it post it here and I'll help you out. If you are using a public theme post the name here and I'll have a look.
There is a plug in called Role Manager <http://www.im-web-gefunden.de/wordpress-plugins/role-manager/> that can help you with that.
61,563,466
I am using [craco](https://github.com/gsoft-inc/craco) with create react app and I would like to add a plugin only in DEV mode or by ENV Var my craco.config looks is: ``` const path = require('path'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); module.exports = () => { return { webpack: { alias: { environment: path.join( __dirname, 'src', 'environments', process.env.CLIENT_ENV || 'production' ) } // plugins: [new BundleAnalyzerPlugin()] }, jest: { configure: { testPathIgnorePatterns: ['<rootDir>/src/environments/'], moduleNameMapper: { environment: '<rootDir>/src/environments/test' } } } }; }; ``` so I would like this BundleAnalyzerPlugin. only if the ENV param x =true or if NODE\_ENV=test while I trying to push to plugin array I got that plugin I undefined ``` module.exports.webpack.plugins.push(plugin) ```
2020/05/02
[ "https://Stackoverflow.com/questions/61563466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9050897/" ]
You can set an environment variable right before any script command. For example, in your package.json, add a new line in the `scripts` paragraph that sets some variables: ``` "scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "analyzer": "env NODE_ENV=production ANALYZER=test yarn start" } ``` In `craco.config.js` you can simply use: ``` plugins: process.env.ANALYZER === 'test' ? [new BundleAnalyzerPlugin()] : [] ``` Now, running `npm run analyzer` will both, set node env to `production`, set a variable `ANALYZER` to `test` (used later on) and load the craco config, that will start both the webpack server and the analyser.
you can use conditions from craco like `when`, `whenDev`, `whenProd`, `whenTest` ``` webpack: { plugins: [...whenDev(() => [new BundleAnalyzerPlugin()], [])] }, ```
12,799,264
I'm trying to link a foreignKey on provider and a M2Mfield on bestbuy\_type - however each time I try saving anything to either of these fields I get the error: ``` (1452, 'Cannot add or update a child row: a foreign key constraint fails (`savingschampion`.`products_masterproduct`, CONSTRAINT `provider_id_refs_id_2ea9c584` FOREIGN KEY (`provider_id`) REFERENCES `products_provider` (`id`))') ``` The fields are specified in my model as: ``` class MasterProduct(BaseModel): provider = models.ForeignKey('products.Provider', related_name = 'master_products', blank=True, null=True) bestbuy_type = models.ManyToManyField('products.BestBuy',blank=True, null=True) ...other (no relationship) fields which work fine ``` Using this does actually populate the correct values in django admin for the fields however the error is produced on the save. Using MySQL and the engine specified is: ``` 'ENGINE': 'django.db.backends.mysql' ``` Does anyone have any idea why this would be happening?
2012/10/09
[ "https://Stackoverflow.com/questions/12799264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991277/" ]
Turns out that the new tables being created were using InnoDB rather than MyISAM like the existing tables. Adding this line to my Database config solved this for me by forcing the new tables created by South to use MyISAM: ``` 'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, ```
**'OPTIONS' : { 'init\_command' : 'SET storage\_engine=MyISAM', },** <<-- This did not work for me but after cleaning the data in my database tables I want to modify it worked, though it's not a good approach to follow.
12,799,264
I'm trying to link a foreignKey on provider and a M2Mfield on bestbuy\_type - however each time I try saving anything to either of these fields I get the error: ``` (1452, 'Cannot add or update a child row: a foreign key constraint fails (`savingschampion`.`products_masterproduct`, CONSTRAINT `provider_id_refs_id_2ea9c584` FOREIGN KEY (`provider_id`) REFERENCES `products_provider` (`id`))') ``` The fields are specified in my model as: ``` class MasterProduct(BaseModel): provider = models.ForeignKey('products.Provider', related_name = 'master_products', blank=True, null=True) bestbuy_type = models.ManyToManyField('products.BestBuy',blank=True, null=True) ...other (no relationship) fields which work fine ``` Using this does actually populate the correct values in django admin for the fields however the error is produced on the save. Using MySQL and the engine specified is: ``` 'ENGINE': 'django.db.backends.mysql' ``` Does anyone have any idea why this would be happening?
2012/10/09
[ "https://Stackoverflow.com/questions/12799264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991277/" ]
Turns out that the new tables being created were using InnoDB rather than MyISAM like the existing tables. Adding this line to my Database config solved this for me by forcing the new tables created by South to use MyISAM: ``` 'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, ```
I have resolved the same problem converting all the MyISAM type tables to InnoDB applying the SQL commands produced by this script: ``` SET @DATABASE_NAME = 'name_of_your_db'; SELECT CONCAT('ALTER TABLE `', table_name, '` ENGINE=InnoDB;') AS sql_statements FROM information_schema.tables AS tb WHERE table_schema = @DATABASE_NAME AND `ENGINE` = 'MyISAM' AND `TABLE_TYPE` = 'BASE TABLE' ORDER BY table_name DESC; ``` and then use this option in the django settings : ``` 'OPTIONS' : { 'init_command' : 'SET storage_engine=InnoDB', }, ```
12,799,264
I'm trying to link a foreignKey on provider and a M2Mfield on bestbuy\_type - however each time I try saving anything to either of these fields I get the error: ``` (1452, 'Cannot add or update a child row: a foreign key constraint fails (`savingschampion`.`products_masterproduct`, CONSTRAINT `provider_id_refs_id_2ea9c584` FOREIGN KEY (`provider_id`) REFERENCES `products_provider` (`id`))') ``` The fields are specified in my model as: ``` class MasterProduct(BaseModel): provider = models.ForeignKey('products.Provider', related_name = 'master_products', blank=True, null=True) bestbuy_type = models.ManyToManyField('products.BestBuy',blank=True, null=True) ...other (no relationship) fields which work fine ``` Using this does actually populate the correct values in django admin for the fields however the error is produced on the save. Using MySQL and the engine specified is: ``` 'ENGINE': 'django.db.backends.mysql' ``` Does anyone have any idea why this would be happening?
2012/10/09
[ "https://Stackoverflow.com/questions/12799264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991277/" ]
Turns out that the new tables being created were using InnoDB rather than MyISAM like the existing tables. Adding this line to my Database config solved this for me by forcing the new tables created by South to use MyISAM: ``` 'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, ```
backup the data in the table then delete the data from the table. Run migrations again it will work fine.
12,799,264
I'm trying to link a foreignKey on provider and a M2Mfield on bestbuy\_type - however each time I try saving anything to either of these fields I get the error: ``` (1452, 'Cannot add or update a child row: a foreign key constraint fails (`savingschampion`.`products_masterproduct`, CONSTRAINT `provider_id_refs_id_2ea9c584` FOREIGN KEY (`provider_id`) REFERENCES `products_provider` (`id`))') ``` The fields are specified in my model as: ``` class MasterProduct(BaseModel): provider = models.ForeignKey('products.Provider', related_name = 'master_products', blank=True, null=True) bestbuy_type = models.ManyToManyField('products.BestBuy',blank=True, null=True) ...other (no relationship) fields which work fine ``` Using this does actually populate the correct values in django admin for the fields however the error is produced on the save. Using MySQL and the engine specified is: ``` 'ENGINE': 'django.db.backends.mysql' ``` Does anyone have any idea why this would be happening?
2012/10/09
[ "https://Stackoverflow.com/questions/12799264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/991277/" ]
Turns out that the new tables being created were using InnoDB rather than MyISAM like the existing tables. Adding this line to my Database config solved this for me by forcing the new tables created by South to use MyISAM: ``` 'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, ```
This usually happens when you have a foreign key that reference a default that does not exist. l recommend you check if the object exist in the table that is adding the foreign key. If it does not exist change your default value that you are adding during migration to the one that exists, this can be done in migration files.
20,405,595
So I want to write ten digits to a .txt file and when I run it, I want to place myself at the last digit so I can manually change the final digit. This is what I got so far: ``` public static void main(String[] args) throws IOException { int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; File file = new File("text.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(" " + Arrays.toString(a)); bw.close(); System.out.println("Done!"); ``` What this basically does is write ten digits in the form of an int array to a .txt file. Now how would I go about allowing myself to change the last digit, in this case: 10 through user input?
2013/12/05
[ "https://Stackoverflow.com/questions/20405595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071133/" ]
**Step 1** Read everything into memory from the file. ``` StringBuilder contents = new StringBuilder(); File file = new File("test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { contents.append(line); } ``` **Step 2** Adjust the data in memory. ``` // Let's assume each day is split by a space String[] numbers = contents.toString().split(" "); numbers[numbers.length - 1] = String.valueOf(Integer.parseInt(numbers[numbers.length - 1]) - 1); ``` **Step 3** Write everything back. ``` FileOutputStream fos = new FileOutputStream(file); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos)); for(String number : numbers) { out.write(number); } out.close(); ```
You have two separate problems. The first is how to get your "input". The data you want the user to add. To do that the simplest way would be to take a command line paramater in the arguments and use that as the final character. so after doing the bw.write but before bw.close do ``` for (String str: args) { bw.write(str); } ``` If you need to really wait for input but stay on the command line (rather than through a GUI) then you need to read from System.in() The second problem is how to actually write to the correct point in the file. That can be done as per Chris' answer by reading the whole existing file and then writing back appending or it could be done by opening the file, seeking to the correct point, and then making the change. There is a Random Access Files system in Java that would help with this: <http://docs.oracle.com/javase/tutorial/essential/io/rafs.html>
20,405,595
So I want to write ten digits to a .txt file and when I run it, I want to place myself at the last digit so I can manually change the final digit. This is what I got so far: ``` public static void main(String[] args) throws IOException { int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; File file = new File("text.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(" " + Arrays.toString(a)); bw.close(); System.out.println("Done!"); ``` What this basically does is write ten digits in the form of an int array to a .txt file. Now how would I go about allowing myself to change the last digit, in this case: 10 through user input?
2013/12/05
[ "https://Stackoverflow.com/questions/20405595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3071133/" ]
Chris's answer is probably the most straight forward. However another possible way is using a `RandomAccessFile`. This would be a good option if the file you are maintaining is very large. ``` public class RAFExample { public static void main(String[] args){ int[] values = {1,2,3,4,5,6,123}; File file = new File("text.txt"); System.out.println("File located at: " + file.getAbsolutePath()); RAFExample re = new RAFExample(); try { re.saveArray(file,values); System.out.println("Current File Contents: " + re.getFileContents(file)); re.updateFile(file,9); System.out.println("Current File Contents: " + re.getFileContents(file)); re.updateFile(file,2342352); System.out.println("Current File Contents: " + re.getFileContents(file)); re.updateFile(file,-1); System.out.println("Current File Contents: " + re.getFileContents(file)); } catch (IOException e) { e.printStackTrace(); } } public void saveArray(File file, int[] values) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile())); try{ String toFile = Arrays.toString(values); System.out.println("Writing the following string to the file: " + toFile); bw.write(toFile); }finally{ bw.close(); } } public void updateFile(File f, int value) throws IOException{ RandomAccessFile raf = new RandomAccessFile(f,"rw"); // Find the last space in the file final byte space = ' '; try{ String s; if(raf.length() == 0){ s = "[" + value + "]"; raf.write(s.getBytes()); }else{ raf.seek(raf.length()); int b = raf.read(); while(raf.getFilePointer() - 2 > 0 && b != space){ raf.seek(raf.getFilePointer() - 2); b = raf.read(); } // now we are at the position to write the new value if(raf.getFilePointer() == 0){ // We got to the beginning of the file, // which means there is 1 or 0 values s = "[" + value + "]"; }else{ s = String.valueOf(value); } raf.write(s.getBytes()); raf.write(']'); // This follows the format of Arrays.toString(array) raf.setLength(raf.getFilePointer()); } }finally{ raf.close(); } } private String getFileContents(File f){ BufferedReader reader = null; StringBuilder sb = new StringBuilder(100); try{ reader = new BufferedReader(new FileReader(f)); while(reader.ready()){ sb.append(reader.readLine()); } }catch(IOException e){ e.printStackTrace(System.err); }finally{ if(reader != null){ try{reader.close();}catch (IOException ignore){} } } return sb.toString(); } } ```
You have two separate problems. The first is how to get your "input". The data you want the user to add. To do that the simplest way would be to take a command line paramater in the arguments and use that as the final character. so after doing the bw.write but before bw.close do ``` for (String str: args) { bw.write(str); } ``` If you need to really wait for input but stay on the command line (rather than through a GUI) then you need to read from System.in() The second problem is how to actually write to the correct point in the file. That can be done as per Chris' answer by reading the whole existing file and then writing back appending or it could be done by opening the file, seeking to the correct point, and then making the change. There is a Random Access Files system in Java that would help with this: <http://docs.oracle.com/javase/tutorial/essential/io/rafs.html>
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
In dimens.xml. Use this: ``` <dimen name="design_snackbar_padding_horizontal">0dp</dimen> ``` But remember that this will get applied to all the snackbars in your application.
Before showing the Snackbar you can remove the parent layout padding in the following way: ``` //... _firmwareSnackbar.getView().setPadding(0,0,0,0); _firmwareSnackbar.show(); ```
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
Before showing the Snackbar you can remove the parent layout padding in the following way: ``` //... _firmwareSnackbar.getView().setPadding(0,0,0,0); _firmwareSnackbar.show(); ```
Add to theme of App or Activity `<item name="snackbarStyle">@style/Widget.Design.Snackbar</item>`
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
Before showing the Snackbar you can remove the parent layout padding in the following way: ``` //... _firmwareSnackbar.getView().setPadding(0,0,0,0); _firmwareSnackbar.show(); ```
You shoud remove paddings from a parent view: ```java View snackBarLayout = findViewById(R.id.mainLayout); Snackbar globalSnackbar = Snackbar.make(snackBarLayout, "", Snackbar.LENGTH_INDEFINITE); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) globalSnackbar.getView(); layout.setPadding(0,0,0,0); ```
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
If you are using material components, then add this code to your style.xml file under values ``` <style name="Widget.SnackBar" parent="Widget.MaterialComponents.Snackbar"> <item name="android:layout_margin">0dp</item> </style> ``` then ``` <style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar"> <!-- Customize your theme here. --> <item name="snackbarStyle">@style/Widget.SnackBar</item> </style> ``` This will change margin for all existing snackBar in the app. So if you want to show a gap around SnackBar you can use padding. ``` val snackBar = Snackbar.make(homeLayout, "", Snackbar.LENGTH_INDEFINITE) val snackBarLayout = snackBar.view as Snackbar.SnackbarLayout snackBarLayout.setPadding(8, 0, 8, 0) ```
Before showing the Snackbar you can remove the parent layout padding in the following way: ``` //... _firmwareSnackbar.getView().setPadding(0,0,0,0); _firmwareSnackbar.show(); ```
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
In dimens.xml. Use this: ``` <dimen name="design_snackbar_padding_horizontal">0dp</dimen> ``` But remember that this will get applied to all the snackbars in your application.
Add to theme of App or Activity `<item name="snackbarStyle">@style/Widget.Design.Snackbar</item>`
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
In dimens.xml. Use this: ``` <dimen name="design_snackbar_padding_horizontal">0dp</dimen> ``` But remember that this will get applied to all the snackbars in your application.
You shoud remove paddings from a parent view: ```java View snackBarLayout = findViewById(R.id.mainLayout); Snackbar globalSnackbar = Snackbar.make(snackBarLayout, "", Snackbar.LENGTH_INDEFINITE); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) globalSnackbar.getView(); layout.setPadding(0,0,0,0); ```
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
If you are using material components, then add this code to your style.xml file under values ``` <style name="Widget.SnackBar" parent="Widget.MaterialComponents.Snackbar"> <item name="android:layout_margin">0dp</item> </style> ``` then ``` <style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar"> <!-- Customize your theme here. --> <item name="snackbarStyle">@style/Widget.SnackBar</item> </style> ``` This will change margin for all existing snackBar in the app. So if you want to show a gap around SnackBar you can use padding. ``` val snackBar = Snackbar.make(homeLayout, "", Snackbar.LENGTH_INDEFINITE) val snackBarLayout = snackBar.view as Snackbar.SnackbarLayout snackBarLayout.setPadding(8, 0, 8, 0) ```
Add to theme of App or Activity `<item name="snackbarStyle">@style/Widget.Design.Snackbar</item>`
43,598,901
The following is the record of 10 devices for every few minutes. I need to return unique set of the record for each id and each should be only the latest. How can I do that with elastic search or any other solution would be good. ``` { {id: 1, time: 12345}, {id: 2, time: 12346}, {id: 1, time: 12347}, {id: 2, time: 12348}, {id: 1, time: 12349}, {id: 3, time: 12350}, ... // 10 different ids and 10000 records } ```
2017/04/24
[ "https://Stackoverflow.com/questions/43598901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3705055/" ]
If you are using material components, then add this code to your style.xml file under values ``` <style name="Widget.SnackBar" parent="Widget.MaterialComponents.Snackbar"> <item name="android:layout_margin">0dp</item> </style> ``` then ``` <style name="AppTheme" parent="Theme.MaterialComponents.NoActionBar"> <!-- Customize your theme here. --> <item name="snackbarStyle">@style/Widget.SnackBar</item> </style> ``` This will change margin for all existing snackBar in the app. So if you want to show a gap around SnackBar you can use padding. ``` val snackBar = Snackbar.make(homeLayout, "", Snackbar.LENGTH_INDEFINITE) val snackBarLayout = snackBar.view as Snackbar.SnackbarLayout snackBarLayout.setPadding(8, 0, 8, 0) ```
You shoud remove paddings from a parent view: ```java View snackBarLayout = findViewById(R.id.mainLayout); Snackbar globalSnackbar = Snackbar.make(snackBarLayout, "", Snackbar.LENGTH_INDEFINITE); Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) globalSnackbar.getView(); layout.setPadding(0,0,0,0); ```
57,531
I updated to OS X 10.8 and my process count went from about 75 under Mac OS X 10.7.4(?) to 96. What can I do to fix this? I use my Mac (MacBook Pro, Mid 2010, 2.8 Ghz Core i7, 8GB RAM, 256 GB SSD) for iOS development and the occasional gaming and it bugs me how the process count keeps jumping with each OS upgrade. Since, I feel more comfortable with Windows I already have my PCs optimized down to ~30 processes when idle thanks to the handy dandy MSCONFIG. Is there an equivalent utility for Mac OS X?
2012/07/26
[ "https://apple.stackexchange.com/questions/57531", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1258/" ]
The number of processes is completely unimportant. Your machine can run tens of thousands if it needed to. Ask yourself the question: What are those processes doing? Is any one eating up ram nonestop? Tons of memory? Lots of those may be os-related. Use "Activity Monitor" installed with OSX to figure this stuff out. [TinkerTool](http://www.bresink.com/osx/TinkerTool.html) does a good job allowing you to see every program you configured to start on startup. There are daemon processes too, I've had some software my daughter used start a daemon that kept doing an infinite loop because software was uninstalled... You can check "Console" for what is printing into your kernel logs. Its not the number of processes, but what they do.
And I have 142… who cares? Is there any impact on performance caused? You can probably turn off every convenience and feature such as time machine, automatic software update checks, iCloud syncing, push e-mail, cal-dav, spot light indexing, menu bar try icons, dock, finder, etc. and end up with "~30" processes… but why? Note: I have 142 processes on a 4 year old MacBook (2.4Ghz core 2 duo, 4GB ram, 250 GN HARD DRIVE (not even ssd), 256 MB vram) and still run smoothly...
57,531
I updated to OS X 10.8 and my process count went from about 75 under Mac OS X 10.7.4(?) to 96. What can I do to fix this? I use my Mac (MacBook Pro, Mid 2010, 2.8 Ghz Core i7, 8GB RAM, 256 GB SSD) for iOS development and the occasional gaming and it bugs me how the process count keeps jumping with each OS upgrade. Since, I feel more comfortable with Windows I already have my PCs optimized down to ~30 processes when idle thanks to the handy dandy MSCONFIG. Is there an equivalent utility for Mac OS X?
2012/07/26
[ "https://apple.stackexchange.com/questions/57531", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1258/" ]
And I have 142… who cares? Is there any impact on performance caused? You can probably turn off every convenience and feature such as time machine, automatic software update checks, iCloud syncing, push e-mail, cal-dav, spot light indexing, menu bar try icons, dock, finder, etc. and end up with "~30" processes… but why? Note: I have 142 processes on a 4 year old MacBook (2.4Ghz core 2 duo, 4GB ram, 250 GN HARD DRIVE (not even ssd), 256 MB vram) and still run smoothly...
toAlex: While all the answers you have been given thus far are absolutely correct, what they are failing to understand is what is the underling question: How to I, as a 'total geek with a need to control all aspects of my techno-life" (<- tongue and cheek), gain total control over MY machine?! I get this... I hate when apps and processes are run on my machine and I don't understand what they are doing. Let me first point you too a really great site that will give you a clear list of each process that is running :http://triviaware.com/macprocess/all. This site will let you upload a text file (that you collect threw your terminal app by running: "ps -A > process.txt". You will then upload it and get the definitions of each thing you are running. Once you have that info you will be able to determine what you might be able to kill off and if you really want to. Next spend a little time in your ~/Library folder and look into "LaunchDaemons" & "LaunchAgents". This is where all the process that start up with your account live. You should also look into your "StartupItems" while your there. Now if your really want to go crazy look into your /System/Library folder and look at the same folders in there. This is where all the process are that Apple wants you to run. You can go nutz! All that said I give you this fair warning!!!! Mess around in these folders all you want but know you can TOTALY SCREW UP your machine to the point of needing to do a total rebuild. So before you start make a complete and total backup of everything!!! So from one control freak to another... Good luck in your chase to become a master of your environment! It's taken me 28 years and I'm only 3/4 of the way there. :-)
57,531
I updated to OS X 10.8 and my process count went from about 75 under Mac OS X 10.7.4(?) to 96. What can I do to fix this? I use my Mac (MacBook Pro, Mid 2010, 2.8 Ghz Core i7, 8GB RAM, 256 GB SSD) for iOS development and the occasional gaming and it bugs me how the process count keeps jumping with each OS upgrade. Since, I feel more comfortable with Windows I already have my PCs optimized down to ~30 processes when idle thanks to the handy dandy MSCONFIG. Is there an equivalent utility for Mac OS X?
2012/07/26
[ "https://apple.stackexchange.com/questions/57531", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1258/" ]
The number of processes is completely unimportant. Your machine can run tens of thousands if it needed to. Ask yourself the question: What are those processes doing? Is any one eating up ram nonestop? Tons of memory? Lots of those may be os-related. Use "Activity Monitor" installed with OSX to figure this stuff out. [TinkerTool](http://www.bresink.com/osx/TinkerTool.html) does a good job allowing you to see every program you configured to start on startup. There are daemon processes too, I've had some software my daughter used start a daemon that kept doing an infinite loop because software was uninstalled... You can check "Console" for what is printing into your kernel logs. Its not the number of processes, but what they do.
toAlex: While all the answers you have been given thus far are absolutely correct, what they are failing to understand is what is the underling question: How to I, as a 'total geek with a need to control all aspects of my techno-life" (<- tongue and cheek), gain total control over MY machine?! I get this... I hate when apps and processes are run on my machine and I don't understand what they are doing. Let me first point you too a really great site that will give you a clear list of each process that is running :http://triviaware.com/macprocess/all. This site will let you upload a text file (that you collect threw your terminal app by running: "ps -A > process.txt". You will then upload it and get the definitions of each thing you are running. Once you have that info you will be able to determine what you might be able to kill off and if you really want to. Next spend a little time in your ~/Library folder and look into "LaunchDaemons" & "LaunchAgents". This is where all the process that start up with your account live. You should also look into your "StartupItems" while your there. Now if your really want to go crazy look into your /System/Library folder and look at the same folders in there. This is where all the process are that Apple wants you to run. You can go nutz! All that said I give you this fair warning!!!! Mess around in these folders all you want but know you can TOTALY SCREW UP your machine to the point of needing to do a total rebuild. So before you start make a complete and total backup of everything!!! So from one control freak to another... Good luck in your chase to become a master of your environment! It's taken me 28 years and I'm only 3/4 of the way there. :-)
4,107
I am trying to add this script (Marc Anderson's blog) to AllItems.aspx. Please guide me where it needs to go and what needs to be done to make it work. Thank you. ``` <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery-1.4.2.min.js"></script> <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery.SPServices-0.5.4.min.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function() { var userDepartment = $().SPServices.SPGetCurrentUser({ fieldName: "Department" }); $("input[Title='Department']").val(userDepartment); var userPhone = $().SPServices.SPGetCurrentUser({ fieldName: "WorkPhone" }); $("input[Title='Phone']").val(userPhone); }); </script> ```
2010/07/17
[ "https://sharepoint.stackexchange.com/questions/4107", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
I was able to solve my problem. I copied the files from a temp folder and using JavaScript I was able to print the files using Microsoft OneNote 2010.
I would try to make a print css file. Add a link to the page (masterpage) and open the current page in a new window, loading the print CSS. Off-course you could always add a dropdown button using code, but you still need to make the print css.
4,107
I am trying to add this script (Marc Anderson's blog) to AllItems.aspx. Please guide me where it needs to go and what needs to be done to make it work. Thank you. ``` <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery-1.4.2.min.js"></script> <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery.SPServices-0.5.4.min.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function() { var userDepartment = $().SPServices.SPGetCurrentUser({ fieldName: "Department" }); $("input[Title='Department']").val(userDepartment); var userPhone = $().SPServices.SPGetCurrentUser({ fieldName: "WorkPhone" }); $("input[Title='Phone']").val(userPhone); }); </script> ```
2010/07/17
[ "https://sharepoint.stackexchange.com/questions/4107", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
I basically map a network drive to the location (i.e. turn <http://it-etp.xyzcorp.com/sites/abcdept/> to \it-etp.xyzcorp.com\sites\abcdept\, browse to it, and map a drive to the location (mapping a drive is optional, but helpful in SharePoint management in the long run). There are many ways to perform the next steps, but basically I open my "Printers and Faxes" and open the destination printer I want. I then open the browser that I mapped the SharePoint site in, select the files, and then drag / drop them onto the printer. You will likely get a message letting you know that you will be printing multiple documents, but I disregard those and let the system work away (it may take quite a while depending on the number of docs you wish to print).
I would try to make a print css file. Add a link to the page (masterpage) and open the current page in a new window, loading the print CSS. Off-course you could always add a dropdown button using code, but you still need to make the print css.
4,107
I am trying to add this script (Marc Anderson's blog) to AllItems.aspx. Please guide me where it needs to go and what needs to be done to make it work. Thank you. ``` <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery-1.4.2.min.js"></script> <script language="javascript" type="text/javascript" src="../../jQuery%20Libraries/jquery.SPServices-0.5.4.min.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function() { var userDepartment = $().SPServices.SPGetCurrentUser({ fieldName: "Department" }); $("input[Title='Department']").val(userDepartment); var userPhone = $().SPServices.SPGetCurrentUser({ fieldName: "WorkPhone" }); $("input[Title='Phone']").val(userPhone); }); </script> ```
2010/07/17
[ "https://sharepoint.stackexchange.com/questions/4107", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
I was able to solve my problem. I copied the files from a temp folder and using JavaScript I was able to print the files using Microsoft OneNote 2010.
I basically map a network drive to the location (i.e. turn <http://it-etp.xyzcorp.com/sites/abcdept/> to \it-etp.xyzcorp.com\sites\abcdept\, browse to it, and map a drive to the location (mapping a drive is optional, but helpful in SharePoint management in the long run). There are many ways to perform the next steps, but basically I open my "Printers and Faxes" and open the destination printer I want. I then open the browser that I mapped the SharePoint site in, select the files, and then drag / drop them onto the printer. You will likely get a message letting you know that you will be printing multiple documents, but I disregard those and let the system work away (it may take quite a while depending on the number of docs you wish to print).
13,784,995
I am having a problem with a while loop in c++. The while loop is always being executed the first time around but when the program reaches the cin of the while loop the while loop works perfectly I was wondering what I was doing wrong. Thanks in advance. Also I am sorry if the problem is noobish. I am still a beginner. ``` cout<<"Would you like some ketchup? y/n"<<endl<<endl<<endl; //Ketchup selection screen cin>>optketchup; while (optketchup != "yes" && optketchup != "no" && optketchup != "YES" && optketchup != "Yes" && optketchup != "YEs" && optketchup != "yEs" && optketchup != "YeS" && optketchup != "yeS" && optketchup != "YeS" && optketchup != "yES" && optketchup != "y" && optketchup != "Y" && optketchup != "No" && optketchup != "nO" && optketchup != "NO" && optketchup != "n" && optketchup != "No"); { cout<<"You have entered an entered "<<optketchup<<" which is an invalid option. Please try again."<<endl; cin>>optketchup; } if (optketchup == "yes" || optketchup == "YES" || optketchup == "Yes" || optketchup == "YEs" || optketchup == "yEs" || optketchup == "YeS" || optketchup == "yeS" || optketchup == "YeS" || optketchup == "yES" || optketchup == "y" || optketchup == "Y") { slcketchup == "with"; } else { slcketchup == "without"; } cout<<"Your sandwich shall be "<<slcketchup<<" ketchup."<<endl; system ("pause"); ``` Again thanks in advance.
2012/12/09
[ "https://Stackoverflow.com/questions/13784995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1888952/" ]
You have a semicolon(';') in the `while`. That's causing the problem. Don't write ``` while(.... lots of conditions ...); { //stuff } ``` Write ``` while(.... lots of conditions ...) { //stuff } ``` Notice the lack of the `;` in the 2nd one. Other than that, what if you had to check for the word `Pneumonoultramicroscopicsilicovolcanoconiosis`. How many combinations of upper & lower cases would you end up checking? Instead, convert the input into upper case & compare against upper case `YES` or `NO` or `PNEUMONOULTRAMICROSCOPICSILICOVOLCANOCONIOSIS`.
A control statement executing a single line of code can be written in two different way. ``` if (optketchup == "yes") { slcketchup = "with"; } ``` ``` if (optketchup == "yes") slcketchup = "with"; ``` Also the following code is valid; the difference is that there isn't any instruction to execute when `optketchup` is equal to `"yes"`. ``` if (optketchup == "yes"); ``` This is true for other control statements, such as your `while`. Also, `=` is the assignment operator, while `==` is the comparison operator. You are using the latter when you wanted to use the first. Then, as others already pointed out, just convert `optketchup` to lowercase: You will just need to compare the lowercase value with `"yes"`, instead of checking any possible variant of "yes" written using a mix of lowercase/uppercase characters.
31,037,749
Is there any way to disable selection of multiple columns for a Swing JTable? I've disabled selection all together in the "Tid" column by overriding the selection intervals of the selection model: ``` myTable.getColumnModel().setSelectionModel(new DefaultListSelectionModel() { private boolean isSelectable(int index0, int index1) { return index1 != 0; } @Override public void setSelectionInterval(int index0, int index1) { if(isSelectable(index0, index1)) { super.setSelectionInterval(index0, index1); } } @Override public void addSelectionInterval(int index0, int index1) { if(isSelectable(index0, index1)) { super.addSelectionInterval(index0, index1); } } }); ``` And my guess is that one can also disallow the selection of multiple columns by overriding methods in the selection model. But I can't really figure out how to accomplish that. **Allowed selection** ![Allowed Selection - the selection spans only one column but multiple rows](https://i.stack.imgur.com/Jf9HX.png "Allowed selection") **Disallowed selection** ![Disallowed Selection - the selection spans multiple columns and multiple rows](https://i.stack.imgur.com/OH9Jy.png "Disallowed selection")
2015/06/24
[ "https://Stackoverflow.com/questions/31037749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3075917/" ]
First get the `TableColumnModel` from the `JTable` ``` TableColumnModel columnModel = table.getColumnModel(); ``` Next, get the `LstSeletionModel` for the `TableColumnModel` ``` ListSelectionModel selectionModel = columnModel.getSelectionModel(); ``` With this, you could set the `selectionMode` that the model will use, for example ``` selectionModel.setSelectionModel(ListSelectionModel.SINGLE_SELECTION) ``` See the JavaDocs for [ListSelectionModel](http://docs.oracle.com/javase/7/docs/api/javax/swing/ListSelectionModel.html) and [TableColumnModel](http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableColumnModel.html) for more details Runnable example.... ==================== ![TableSelection](https://i.stack.imgur.com/xysTB.gif) ``` import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.table.DefaultTableModel; public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { public TestPane() { setLayout(new BorderLayout()); DefaultTableModel model = new DefaultTableModel(0, 10); for (int row = 0; row < 10; row++) { String[] data = new String[10]; for (int col = 0; col < 10; col++) { data[col] = row + "x" + col; } model.addRow(data); } JTable table = new JTable(model); table.setColumnSelectionAllowed(true); table.setRowSelectionAllowed(true); table.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add(new JScrollPane(table)); } } } ```
Actually, it was a simple enough addition to my already existing overrides that was needed. ``` @Override public void setSelectionInterval(int index0, int index1) { if (isSelectable(index0, index1)) { if (index0==index1) { //The if condition needed. super.setSelectionInterval(index0, index1); } } } ``` I realised upon reviewing the JavaDoc and the `DefaultListSelectionModel` that the `index0` and `index1` were just what I was looking for - the column span. So by doing the call to the superclass if and only if the two column indices are equal, selection of multiple columns is not possible.
46,882,380
``` import numpy as np with open("/Users/myname/Downloads/names/yob1880.txt","r") as f: text = f.readlines() for line in text: print (line) def mapper(): for lines in line: data = line.strip().split("\t") name, sex, number = data print ("{0}\t{1}".format(name, number)) ``` dataset has comma separated values of name, sex and number. dataset is taken from here: <https://www.ssa.gov/oact/babynames/names.zip> [enter image description here](https://i.stack.imgur.com/xMghV.png)
2017/10/23
[ "https://Stackoverflow.com/questions/46882380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8817356/" ]
Try this: ``` import numpy as np import csv with open("/Users/myname/Downloads/names/yob1880.txt","r") as f: csv_file = csv.reader(f) def mapper(): for line in csv_file: name, sex, number = line print ("{0}\t{1}".format(name, number)) mapper() ``` The csv module helps out quite a bit.
I think, instead of ``` for lines in line: data = line.strip().split("\t") name, sex, number = data print ("{0}\t{1}".format(name, number)) ``` You should actually use the single line (which in your case is called `lines` or rephrase your variables). Thus, think about this here: ``` for line in text: data = line.strip().split(',') ``` Do you see the difference? `lines` and `line`? --- Also, reading the comments and the provided files, you should `split(',')`. Or even better, use the [csv](https://docs.python.org/2/library/csv.html) module, that comes with a csv reader.
34,903,203
Is it possible to change edit the css of only 4th tab of this li menu. If so, how? All help appreciated. Thank you! ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ```
2016/01/20
[ "https://Stackoverflow.com/questions/34903203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5816510/" ]
You can use `:nth-child(4)`, in the case you want the **4th child** of anything: ```css .rt_tabs li:nth-child(4) { background: #99c; } ``` ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ``` Other ways to do (in this particular example): 1. Use the id: `#tab-4-title {}`. 2. Use the attribute selector: `[data-tab-number="4"] {}`.
Your element already has an id, so its easy ```css #tab-4-title{ /*Whatever change you want*/ } ```
34,903,203
Is it possible to change edit the css of only 4th tab of this li menu. If so, how? All help appreciated. Thank you! ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ```
2016/01/20
[ "https://Stackoverflow.com/questions/34903203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5816510/" ]
You can use `:nth-child(4)`, in the case you want the **4th child** of anything: ```css .rt_tabs li:nth-child(4) { background: #99c; } ``` ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ``` Other ways to do (in this particular example): 1. Use the id: `#tab-4-title {}`. 2. Use the attribute selector: `[data-tab-number="4"] {}`.
`.tab_nav li:nth-child(4)` targets the 4th `li` child of `.tab_nav`. Or in this case `.tab_nav li:last-child` should also work. More information on nth-child: <https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child>
34,903,203
Is it possible to change edit the css of only 4th tab of this li menu. If so, how? All help appreciated. Thank you! ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ```
2016/01/20
[ "https://Stackoverflow.com/questions/34903203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5816510/" ]
You can use `:nth-child(4)`, in the case you want the **4th child** of anything: ```css .rt_tabs li:nth-child(4) { background: #99c; } ``` ```html <div class="rt_tabs clearfix left tab-style-2" id="single-product-details" data-tab-style="tab-style-2"> <ul class="tab_nav hidden-xs"> <li class="tab_title active" id="tab-1-title" data-tab-number="1"><span class="icon-lightbulb"></span>TAB 1</li> <li class="tab_title " id="tab-2-title" data-tab-number="2"><span class="icon-home"></span>TAB 2</li> <li class="tab_title " id="tab-3-title" data-tab-number="3"><span class="icon-plus-circled"></span>TAB 3</li> <li class="tab_title " id="tab-4-title" data-tab-number="4"><span class="icon-mail-1"></span>TAB 4</li> </ul> ``` Other ways to do (in this particular example): 1. Use the id: `#tab-4-title {}`. 2. Use the attribute selector: `[data-tab-number="4"] {}`.
Use the id: ``` #tab-4-title {...} ``` Use a attribute selector: ``` [data-tab-number="4"] {...} ``` Use a pseudo-selector: ``` li:nth-child(4) {...} li:last-child {...} li:nth-last-child(1) {...} li:last-of-type {...} ``` There are several other possibilities.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
For BW projects, I cooked my own Unit Test framework based on BW Processes itself. So the automated tests and validations are coded in the TIBCO project itself. For AMX projects I recommend SOAPUI for automated testing of your services. However, I coded all the unit tests in the underlying language, in my case Java, using JUnit. The Implementation classes under the components reference each other directly in the unit tests, bypassing the AMX code doing the messaging.
With BW-TEST you can practice TDD and add your projects to your CI Check it out on <http://nicosommi.com/?p=209> It's open source
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
With BW-TEST you can practice TDD and add your projects to your CI Check it out on <http://nicosommi.com/?p=209> It's open source
[IBM RIT](http://pic.dhe.ibm.com/infocenter/rithelp/v8r5m0/topic/com.ibm.rational.rit.accessibility.doc/helpindex_rit.html) is very good tool to work on this kind of scenarios, it can help you to assert different scenarios and also to evaluate code coverage.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
For BW projects, I cooked my own Unit Test framework based on BW Processes itself. So the automated tests and validations are coded in the TIBCO project itself. For AMX projects I recommend SOAPUI for automated testing of your services. However, I coded all the unit tests in the underlying language, in my case Java, using JUnit. The Implementation classes under the components reference each other directly in the unit tests, bypassing the AMX code doing the messaging.
[IBM RIT](http://pic.dhe.ibm.com/infocenter/rithelp/v8r5m0/topic/com.ibm.rational.rit.accessibility.doc/helpindex_rit.html) is very good tool to work on this kind of scenarios, it can help you to assert different scenarios and also to evaluate code coverage.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
[IBM RIT](http://pic.dhe.ibm.com/infocenter/rithelp/v8r5m0/topic/com.ibm.rational.rit.accessibility.doc/helpindex_rit.html) is very good tool to work on this kind of scenarios, it can help you to assert different scenarios and also to evaluate code coverage.
I recommend IBM RIT. it is part of IBM RTW stack. You can use it in TDD and CI/CD models of delivery easily.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
Trying to do a methodology like TDD using soap UI would not be very effective. I have used This for BW and you do not get the same level of granularity and comfort from a full unit test suite. BWUnit is a good tool, and if you have a good relationship with your TIbco PSG guys you may be able to get TibUnit which is a PSG Ware like CLE. We've also come up with a plan to use an external Unit test framework like .net and then use a controller pattern to swap out processes using Dynamic Process override flag. So esentaially we'd have a control channel that would say something like Control - Process 1 Override -/Processes/SomeProcess.process - Process 2 Override {Blank} so in your unit test you would be able in your setup to call BW using your control channel (EMS or HTTP) and tell it to load a different process. While this works its still a hack because of the limited functionality of Designer. We've also looked at Service Grid and BWSE and that didn't appear to give us anything more. Actually a little more limiting.
I recommend IBM RIT. it is part of IBM RTW stack. You can use it in TDD and CI/CD models of delivery easily.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
I've had great success creating a soap interface layer for each of my processes (taking in the same arguments) and leveraging [SoapUI](http://soapui.org) to do all the testing driven from a few database tables. Edit: What I described is pretty much how BWUnit is working: it creates a web service interface around each of your processes (maybe with a little less manual work, but same concept.) > > Test Input (SoapUI) -> Testable Interface (soap/ems/etc) -> Existing process -> Exit Interface -> Assertions (SoapUI) > > > You could do the testing within tibco itself, with files, RV, JMS, or any input for that matter, except you're writing all the test assertion code yourself rather than using an existing tool that has it all built in. You can then rely on SoapUI to generate all your JUnit reports etc. If you want to get really fancy, you can add a soapui target to your build script to include the unit tests and/or functional tests for each build once it's deployed.
I recommend IBM RIT. it is part of IBM RTW stack. You can use it in TDD and CI/CD models of delivery easily.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
For BW projects, I cooked my own Unit Test framework based on BW Processes itself. So the automated tests and validations are coded in the TIBCO project itself. For AMX projects I recommend SOAPUI for automated testing of your services. However, I coded all the unit tests in the underlying language, in my case Java, using JUnit. The Implementation classes under the components reference each other directly in the unit tests, bypassing the AMX code doing the messaging.
I've had great success creating a soap interface layer for each of my processes (taking in the same arguments) and leveraging [SoapUI](http://soapui.org) to do all the testing driven from a few database tables. Edit: What I described is pretty much how BWUnit is working: it creates a web service interface around each of your processes (maybe with a little less manual work, but same concept.) > > Test Input (SoapUI) -> Testable Interface (soap/ems/etc) -> Existing process -> Exit Interface -> Assertions (SoapUI) > > > You could do the testing within tibco itself, with files, RV, JMS, or any input for that matter, except you're writing all the test assertion code yourself rather than using an existing tool that has it all built in. You can then rely on SoapUI to generate all your JUnit reports etc. If you want to get really fancy, you can add a soapui target to your build script to include the unit tests and/or functional tests for each build once it's deployed.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
Deopends on the protocol used (what is used). Racoon and SoapUI has been mentioned. With them you can test on a "per module" level. That is Component or System tests. Especially usful for performance tests. However this is the most common way to test tibco components. I will have a look at the BWUnit, looks interesting and integrated with CI Servers (I have built a similar tool in a project). A flaw of this approch may be that TIBCO systems usually are composed of different tools and not only BW, this means that Java components, C++ servers and so fort is used to for the total system. There is also a Commercial tool called GHTester (<http://www.greenhatconsulting.com/ghtester/>) If you are using RV you might have a look at <http://www.rvsnoop.org/> to capture the messages in a replayable format for free (OSS tool that I started)
[IBM RIT](http://pic.dhe.ibm.com/infocenter/rithelp/v8r5m0/topic/com.ibm.rational.rit.accessibility.doc/helpindex_rit.html) is very good tool to work on this kind of scenarios, it can help you to assert different scenarios and also to evaluate code coverage.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
There's an old framework called [Raccoon](http://raccoonfwk.sourceforge.net/) built above Tibco ActiveEnterprise. It has a component for unit testing called [UiTest](http://raccoonfwk.sourceforge.net/tibco/uiTest.html) focused on RendezVous messaging. It doesn't seem to have too much activity lately, though.
I recommend IBM RIT. it is part of IBM RTW stack. You can use it in TDD and CI/CD models of delivery easily.
2,635,830
Does anyone know what unit testing tools are available when developing Tibco processes? In the next few months I'll be working on a Tibco project and I'm trying to find any existing unit testing frameworks that might make the job easier to build with a TDD approach. Thus far, the only one I've been able to locate is called [BWUnit](http://windyroad.org/software/bwunit/). It seems ok but its currently in beta and its commercial software. If possible I'd like to use an open source tool but as long as it is able to do a good job I'd be happy. So does anyone know of any other unit testing tools for Tibco development? Also, does anyone have any experience with BWUnit? How useful is/was it?
2010/04/14
[ "https://Stackoverflow.com/questions/2635830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39532/" ]
Trying to do a methodology like TDD using soap UI would not be very effective. I have used This for BW and you do not get the same level of granularity and comfort from a full unit test suite. BWUnit is a good tool, and if you have a good relationship with your TIbco PSG guys you may be able to get TibUnit which is a PSG Ware like CLE. We've also come up with a plan to use an external Unit test framework like .net and then use a controller pattern to swap out processes using Dynamic Process override flag. So esentaially we'd have a control channel that would say something like Control - Process 1 Override -/Processes/SomeProcess.process - Process 2 Override {Blank} so in your unit test you would be able in your setup to call BW using your control channel (EMS or HTTP) and tell it to load a different process. While this works its still a hack because of the limited functionality of Designer. We've also looked at Service Grid and BWSE and that didn't appear to give us anything more. Actually a little more limiting.
[IBM RIT](http://pic.dhe.ibm.com/infocenter/rithelp/v8r5m0/topic/com.ibm.rational.rit.accessibility.doc/helpindex_rit.html) is very good tool to work on this kind of scenarios, it can help you to assert different scenarios and also to evaluate code coverage.
13,992,683
When running a spec I am getting all the output of the database transaction as well: ``` lee$ rspec spec/mailers/ Connecting to database specified by database.yml (0.1ms) BEGIN User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'user@example.name' LIMIT 1 User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."auth_token" = '8bF72xsaxsSsidLvA1uD9Q' LIMIT 1 SQL (2.3ms) INSERT INTO "users" ("auth_token", "created_at", "email", "first_name", "last_name", "password_digest", "password_reset_token", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING "id" [["auth_token", "8bF70xsaEsSsidLvA1uD9Q"], ["created_at", Fri, 21 Dec 2012 14:55:40 UTC +00:00], ["email", "michale@swift.name"], ["first_name", nil], ["last_name", nil], ["password_digest", "$2a$10$KXKLprkU/Irp30LoB8M.DuSwLV9bq9P3C7hIAO4yNShPrDE.NmHU."], ["password_reset_token", nil], ["updated_at", Fri, 21 Dec 2012 14:55:40 UTC +00:00]] (1.6ms) COMMIT Rendered user_mailer/customer_sigup_confirmation.html.erb (0.8ms) Rendered user_mailer/customer_sigup_confirmation.text.erb (0.4ms) . Finished in 0.41419 seconds 1 example, 0 failures Randomized with seed 6071 ``` This is far too much noise! **How can I disable/reduce it?** Below is my spec\_helper if it helps. ``` require 'rubygems' require 'spork' #uncomment the following line to use spork with the debugger # require 'spork/ext/ruby-debug' Spork.prefork do # Loading more in this block will cause your tests to run faster. However, # if you change any configuration or code from libraries loaded here, you'll # need to restart spork for it take effect. # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'capybara/rspec' require 'capybara/poltergeist' Capybara.javascript_driver = :poltergeist # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = "random" # Include Factory Girl syntax to simplify calls to factories config.include FactoryGirl::Syntax::Methods # Add Support Modules # config.include LoginMacros config.include MailerMacros config.before(:each) { reset_email } config.treat_symbols_as_metadata_keys_with_true_values = true config.filter_run :focus => true config.run_all_when_everything_filtered = true end end Spork.each_run do # This code will be run each time you run your specs. FactoryGirl.reload class ActiveRecord::Base mattr_accessor :shared_connection @@shared_connection = nil def self.connection @@shared_connection || retrieve_connection end end # Forces all threads to share the same connection. This works on # Capybara because it starts the web server in a thread. ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection end ```
2012/12/21
[ "https://Stackoverflow.com/questions/13992683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/99877/" ]
In you environment initializer for test (config/environments/test.rb), [configure](http://guides.rubyonrails.org/configuring.html) proper logger level: `config.logger.level = Logger::FATAL`
Part of the problem probably stems from `Poltergeist` being used as the `Capybara` javascript driver. I had a similar issue when using `capybara-webkit`. Try using this syntax: ``` Capybara.register_driver :poltergeist_silent do |app| Capybara::Poltergeist::Driver.new(app, :logger => nil) end Capybara.javascript_driver = :poltergeist_silent ``` This would go in your `spec_helper`, replacing this line: `Capybara.javascript_driver = :poltergeist`. This may prevent the log messages referring to rendering. I have a feeling the messages about the database may be coming from `Spork`, as I have used `Rspec` extensively without `Spork` and I don't see those messages. Can you try checking to see if there is an option for `Spork` to disable log/stdout messages?
1,061,588
I created and enabled a service: ``` $ sudo systemctl enable /path/to/imaservice.service Created symlink /etc/systemd/system/multi-user.target.wants/imaservice.service → /path/to/imaservice.service. Created symlink /etc/systemd/system/imaservice.service → /path/to/imaservice.service. ``` It exists and persists in both: ``` /etc/systemd/system/imaservice.service /etc/systemd/system/multi-user.target.wants/imaservice.service ``` I can now start/stop/status it happily. When I reboot, I can't start it. I get the following: ``` $sudo systemctl is-enabled imaservice enabled ``` However: ``` $sudo systemctl start imaservice Failed to start imaservice.service: Unit imaservice.service not found. ``` Every time I reboot, I have to re-enable with: ``` $sudo systemctl enable imaservice $sudo systemctl daemon-reload ``` And after this it's back to normal. What am I doing wrong?
2018/08/02
[ "https://askubuntu.com/questions/1061588", "https://askubuntu.com", "https://askubuntu.com/users/855870/" ]
After submitting the bug report, I got the following reply from one of the developers: > > This issue has been fixed and pushed to GNOME Extensions. It’s pending a manual review (these reviews are done by volunteers and they can take forever) but the update should be available soon. > > > If you’re impatient, you can find and apply the patch on GitHub: > <https://github.com/stuartlangridge/gnome-shell-clock-override/issues/13> > > > So, it is now only a matter of time for us to get a fix. **UPDATE** : Release has now been reviewed and available for download. Problem solved.
Fixed version is pending review, until you can use that: ``` %H:%M %;@ ``` "%; @" generates a number, I do not know what this number is but it works
23,396,053
I'm calculating the determinant of a matrix, the calculations and therefore a method is called depending on the dimensionality of the data, for example: ``` template<int X, int Y> float determinant(X, Y, std::vector<Vector> &data) { // Determine the dimensionality of matrix data (x and y) } ``` The problem that I am having is that in the class that calculates the PCA, which calls this function, only accepts an iterator: ``` class PCA { public: template<typename T> PCA(T begin, T end) { // Determine the X and Y here float det = determinant(X, Y, ....); } }; ``` Now I am wondering whether or not it is possible to deduce the `X` and `Y` from the iterator that has been passed through PCA, rather than passing in two integer values. Any advice would be greatly appreciated EDIT: Apologises, my question was not clear. Basically, `typedef std::vector<double> Vector;` is used so therefore `std::vector<Vector> data;` would therefore be a vector of vectors. I sample this doing the following: `std::vector<Vector> data1 = { {1, 2}, {3, 4}, {5, 6}, {8, 9} }; // 2x2` whereas when I want to add the following: `std::vector<Vector> data2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; // 3x3` so obviously, when calculating the determinant there is a different calculation for this. I want to deduce that data1 is a 2x2 and data2 3x3 from the function without having to specifically pass these values in.
2014/04/30
[ "https://Stackoverflow.com/questions/23396053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326876/" ]
Since vectors aren't fixed-size, they could be jagged. (Constrast this with, e.g. `std::array<>` or `T [N][M][L]`; you could deduce their ranks at compiletime). Let's assume they're not: see it **[Live On Coliru](http://coliru.stacked-crooked.com/a/dbe4121ef644a3a0)** ``` #include <vector> #include <cstdint> #include <deque> template <typename V> std::deque<std::size_t> dims_of(V const& v) { return {}; } template <typename T> std::deque<std::size_t> dims_of(std::vector<T> const& v) { if (v.empty()) return { 0 }; else { auto dims = dims_of(v.front()); dims.push_front(v.size()); return dims; } } #include <iostream> int main() { std::vector<std::vector<std::vector<int> > > const v(7, std::vector<std::vector<int> >( 10, std::vector<int>(3, 0) ) ); for (auto dim : dims_of(v)) std::cout << dim << " "; } ``` Prints ``` 7 10 3 ```
What about deriving from PCA into class that holds X and Y ``` template<int X,int Y> PCA_size : public PCA { enum { Xv=X}; enum { Yv=Y}; } ``` Then you can just recast existing PCA object into yours ``` static_cast<PCA_size<3,5> >(PCA_instance); ```
117,993
I will be moving to a new city to take up a job in 20 days. How soon I can apply for the renewal of my passport from the new place, after moving in there? Can I use my rental agreement and HR letter as address proof?
2018/07/06
[ "https://travel.stackexchange.com/questions/117993", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/80110/" ]
Your own government's instructions indicate you can apply as soon as you have the required proof: [Change of Address](https://portal1.passportindia.gov.in/AppOnlineProject/online/faqServicesAvailable) > > Q61: How do I change the address on my passport? > > A: To change the address in the passport, you have to apply for a "Re-issue" of passport and get the specified change done in the personal particulars. > > > [Table 3, found on page 11](https://portal1.passportindia.gov.in/AppOnlineProject/pdf/ApplicationformInstructionBooklet-V3.0.pdf) > > **Proof of Present Address.** > > For Proof of Address attach one of the following documents: > > > > > ``` > a. Water Bill > b. Telephone (landline or postpaid mobile bill) > c. Electricity bill > d. Income Tax Assessment Order > e. Election Commission Photo ID card > f. Gas connection bill > g. Certificate from Employer of reputed and widely known companies on letter > head (Only public limited companies can give address proof on company > letter head along with seal. Computerised print-outs shall not be > entertained) > h. Spouse’s passport copy (First and last page including family details > mentioning applicant's name as spouse of the passport holder), (provided > the applicant’s present address matches the address mentioned in the > spouse’s passport) > i. Parent’s passport copy, in case of minors (First and last page) > j. Aadhaar Letter/ Card (Aadhaar letter/card or the e-Aadhaar (an > electronically generated letter from the website of UIDAI), as the case > may be, will be accepted as Proof of Address (POA) and Proof of Photo- > Identity (POI) for availing passport related services. Acceptance of > Aadhaar as PoA and PoI would be subject to successful validation with > Aadhaar database.) > k. Rent Agreement > > ``` > >
You have to give details of all places you have stayed during past one year and the police verification would be done at all those places. It will be better if you can get the passport reissued and police verification done at current address itself.
32,674,843
Say I have a master branch and a branch for developing a feature: ``` -- s -- x -- x -- x -- HEAD [master] \ \ bs -- x -- x -- x [feature] ``` and the feature branch for some reason (laziness) is a bit old. Now when I'm on `master` and do `git diff feature`, I got all the diff from `s` to `HEAD` as well. I'd like to get a diff diff that actually happened on `feature` branch **alone**. But I don't know how to find out what `s` is. Is there a way to find out?
2015/09/20
[ "https://Stackoverflow.com/questions/32674843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172265/" ]
As [Jonathon Reinhart noted](https://stackoverflow.com/a/32674865/1256452) you just need to diff commit `s` against the tip of `feature`. As you noted, you forgot to mention that you want to have git find commit `s` for you. The general way to ask git to find `s` is to find the "merge base" between `HEAD` (`master`) and `feature`. The `git merge-base` command does this, so in a shell, you could do: ``` $ s=$(git merge-base HEAD feature) ``` and then ``` $ git diff $s feature ``` Conveniently, though, `git diff` takes over the three-dot syntax: `git diff X...Y` (note the three dots) means "find the merge-base of `X` and `Y` and then diff that merge-base against `Y`". So: ``` $ git diff master...feature ``` Or, since `HEAD` is currently a symbolic name for `master`, you can write: ``` $ git diff HEAD...feature ``` and this then means that you can simply write: ``` $ git diff ...feature ``` as omitting one of the names means "use `HEAD`". (Or, if you prefer and your git is not too ancient, you can use `@` to spell `HEAD`.)
If you want to see the changes from `s` to `feature`, then: ``` git diff s feature ``` From the man page: > > > ``` > git diff [--options] <commit> <commit> [--] [<path>…​] > This is to view the changes between two arbitrary <commit>. > > ``` > > For all of your diffing needs, consult <http://git-scm.com/docs/git-diff>
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*Debris* is broken-apart pieces of stuff arising from some sort of violent event that pulls things apart. (*Rubble* is a close synonym, although it carries more of a static feeling; we wouldn't usually say "rubble flying in the air," for example.) *Wreckage* is what's left of something identifiable that has been damaged beyond repair. *Remains* is also used in this context, but it is also used to refer to what's left of someone or something that has died, or a corpse. (We would not use *wreckage* to refer to such.) A few pictures of tornado damage should clarify the differences. This is a picture of flying debris from a tornado: ![](https://i.stack.imgur.com/daBKf.jpg) Here is a picture of a large piece of debris sticking through the wreckage of a car: [![enter image description here](https://i.stack.imgur.com/7EqNw.jpg)](https://i.stack.imgur.com/7EqNw.jpg) Here is the wreckage of a house and a truck after a tornado blew the truck into the house. As you can see, there is a fair amount of debris scattered about: [![](https://i.stack.imgur.com/S3xT9.jpg)](https://i.stack.imgur.com/S3xT9.jpg) (source: [dailymail.co.uk](https://i.dailymail.co.uk/i/pix/2012/04/04/article-2124648-1274D8CC000005DC-341_470x295.jpg)) And here are the remains of a neighborhood after a huge tornado demolished it. As you can see, there is nothing left of it but piles of debris (or rubble) where houses used to be: [![](https://i.stack.imgur.com/0a8LA.jpg)](https://i.stack.imgur.com/0a8LA.jpg) (source: [wxug.com](https://icons.wxug.com/hurricane/2013/moore_wide_destruction.jpg))
*debris* or *remains* would be acceptable: * The debris from the crash of Flight XYZ * The remains of the aeroplane However, *debris* and *remains* aren't completely interchangeable. You would *not* use *debris* to describe parts of deceased/maimed living being. * The remains of the man were discovered... * **not** The debris of the man was discovered... Also, I'd consider uses of *remains* as implying that the some kind of destruction or damage, whereas remains usually means more natural processes - what's just "left".
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*debris* or *remains* would be acceptable: * The debris from the crash of Flight XYZ * The remains of the aeroplane However, *debris* and *remains* aren't completely interchangeable. You would *not* use *debris* to describe parts of deceased/maimed living being. * The remains of the man were discovered... * **not** The debris of the man was discovered... Also, I'd consider uses of *remains* as implying that the some kind of destruction or damage, whereas remains usually means more natural processes - what's just "left".
Debris is broken-apart pieces of stuff left over after some sort of violent event that pulls things apart. (Rubble is a close synonym.) Wreckage is what's left of something identifiable that has been damaged beyond repair, but as jimsug has mentioned, it would not be used to refer to living things that have died. In that case we would always use remains. Remains are what is left after something or someone has been wrecked or killed. So often wreckage and remains can refer to the same thing.
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*debris* or *remains* would be acceptable: * The debris from the crash of Flight XYZ * The remains of the aeroplane However, *debris* and *remains* aren't completely interchangeable. You would *not* use *debris* to describe parts of deceased/maimed living being. * The remains of the man were discovered... * **not** The debris of the man was discovered... Also, I'd consider uses of *remains* as implying that the some kind of destruction or damage, whereas remains usually means more natural processes - what's just "left".
**Wreckage** refers to one or more large pieces of something that has been *wrecked*, severely damaged by something other than time. (e.g. the wreckage of a bus that has fallen over a small cliff). **Debris** is from the French word *débris*, originally meaning to *break down*, and refers to many small pieces of wreckage or remains. (e.g. the debris from a bus that had contained a terrorist bomb.) **Remains** are what *remain* of something that has decayed, rotted, rusted, scavenged, etc. over a long time period (e.g. the remains of an abandoned bus).
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*Debris* is broken-apart pieces of stuff arising from some sort of violent event that pulls things apart. (*Rubble* is a close synonym, although it carries more of a static feeling; we wouldn't usually say "rubble flying in the air," for example.) *Wreckage* is what's left of something identifiable that has been damaged beyond repair. *Remains* is also used in this context, but it is also used to refer to what's left of someone or something that has died, or a corpse. (We would not use *wreckage* to refer to such.) A few pictures of tornado damage should clarify the differences. This is a picture of flying debris from a tornado: ![](https://i.stack.imgur.com/daBKf.jpg) Here is a picture of a large piece of debris sticking through the wreckage of a car: [![enter image description here](https://i.stack.imgur.com/7EqNw.jpg)](https://i.stack.imgur.com/7EqNw.jpg) Here is the wreckage of a house and a truck after a tornado blew the truck into the house. As you can see, there is a fair amount of debris scattered about: [![](https://i.stack.imgur.com/S3xT9.jpg)](https://i.stack.imgur.com/S3xT9.jpg) (source: [dailymail.co.uk](https://i.dailymail.co.uk/i/pix/2012/04/04/article-2124648-1274D8CC000005DC-341_470x295.jpg)) And here are the remains of a neighborhood after a huge tornado demolished it. As you can see, there is nothing left of it but piles of debris (or rubble) where houses used to be: [![](https://i.stack.imgur.com/0a8LA.jpg)](https://i.stack.imgur.com/0a8LA.jpg) (source: [wxug.com](https://icons.wxug.com/hurricane/2013/moore_wide_destruction.jpg))
For the item in this photo (an airplane) I would call this **wreckage**. This generally applies to things that are destroyed by some force, such as means of transportation (cars, trains, etc.) *debris* in a very general sense could be used. *remains* (as I use it) usually refers to living things that aren't living anymore, though by definition that is not the only usage.
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
For the item in this photo (an airplane) I would call this **wreckage**. This generally applies to things that are destroyed by some force, such as means of transportation (cars, trains, etc.) *debris* in a very general sense could be used. *remains* (as I use it) usually refers to living things that aren't living anymore, though by definition that is not the only usage.
Debris is broken-apart pieces of stuff left over after some sort of violent event that pulls things apart. (Rubble is a close synonym.) Wreckage is what's left of something identifiable that has been damaged beyond repair, but as jimsug has mentioned, it would not be used to refer to living things that have died. In that case we would always use remains. Remains are what is left after something or someone has been wrecked or killed. So often wreckage and remains can refer to the same thing.
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
For the item in this photo (an airplane) I would call this **wreckage**. This generally applies to things that are destroyed by some force, such as means of transportation (cars, trains, etc.) *debris* in a very general sense could be used. *remains* (as I use it) usually refers to living things that aren't living anymore, though by definition that is not the only usage.
**Wreckage** refers to one or more large pieces of something that has been *wrecked*, severely damaged by something other than time. (e.g. the wreckage of a bus that has fallen over a small cliff). **Debris** is from the French word *débris*, originally meaning to *break down*, and refers to many small pieces of wreckage or remains. (e.g. the debris from a bus that had contained a terrorist bomb.) **Remains** are what *remain* of something that has decayed, rotted, rusted, scavenged, etc. over a long time period (e.g. the remains of an abandoned bus).
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*Debris* is broken-apart pieces of stuff arising from some sort of violent event that pulls things apart. (*Rubble* is a close synonym, although it carries more of a static feeling; we wouldn't usually say "rubble flying in the air," for example.) *Wreckage* is what's left of something identifiable that has been damaged beyond repair. *Remains* is also used in this context, but it is also used to refer to what's left of someone or something that has died, or a corpse. (We would not use *wreckage* to refer to such.) A few pictures of tornado damage should clarify the differences. This is a picture of flying debris from a tornado: ![](https://i.stack.imgur.com/daBKf.jpg) Here is a picture of a large piece of debris sticking through the wreckage of a car: [![enter image description here](https://i.stack.imgur.com/7EqNw.jpg)](https://i.stack.imgur.com/7EqNw.jpg) Here is the wreckage of a house and a truck after a tornado blew the truck into the house. As you can see, there is a fair amount of debris scattered about: [![](https://i.stack.imgur.com/S3xT9.jpg)](https://i.stack.imgur.com/S3xT9.jpg) (source: [dailymail.co.uk](https://i.dailymail.co.uk/i/pix/2012/04/04/article-2124648-1274D8CC000005DC-341_470x295.jpg)) And here are the remains of a neighborhood after a huge tornado demolished it. As you can see, there is nothing left of it but piles of debris (or rubble) where houses used to be: [![](https://i.stack.imgur.com/0a8LA.jpg)](https://i.stack.imgur.com/0a8LA.jpg) (source: [wxug.com](https://icons.wxug.com/hurricane/2013/moore_wide_destruction.jpg))
Debris is broken-apart pieces of stuff left over after some sort of violent event that pulls things apart. (Rubble is a close synonym.) Wreckage is what's left of something identifiable that has been damaged beyond repair, but as jimsug has mentioned, it would not be used to refer to living things that have died. In that case we would always use remains. Remains are what is left after something or someone has been wrecked or killed. So often wreckage and remains can refer to the same thing.
26,366
Please suggest the most proper word to describe the picture below. ![enter image description here](https://i.stack.imgur.com/zvjWx.jpg) Can I use "debris" to describe it? Are they completely interchangeable?
2014/06/14
[ "https://ell.stackexchange.com/questions/26366", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/-1/" ]
*Debris* is broken-apart pieces of stuff arising from some sort of violent event that pulls things apart. (*Rubble* is a close synonym, although it carries more of a static feeling; we wouldn't usually say "rubble flying in the air," for example.) *Wreckage* is what's left of something identifiable that has been damaged beyond repair. *Remains* is also used in this context, but it is also used to refer to what's left of someone or something that has died, or a corpse. (We would not use *wreckage* to refer to such.) A few pictures of tornado damage should clarify the differences. This is a picture of flying debris from a tornado: ![](https://i.stack.imgur.com/daBKf.jpg) Here is a picture of a large piece of debris sticking through the wreckage of a car: [![enter image description here](https://i.stack.imgur.com/7EqNw.jpg)](https://i.stack.imgur.com/7EqNw.jpg) Here is the wreckage of a house and a truck after a tornado blew the truck into the house. As you can see, there is a fair amount of debris scattered about: [![](https://i.stack.imgur.com/S3xT9.jpg)](https://i.stack.imgur.com/S3xT9.jpg) (source: [dailymail.co.uk](https://i.dailymail.co.uk/i/pix/2012/04/04/article-2124648-1274D8CC000005DC-341_470x295.jpg)) And here are the remains of a neighborhood after a huge tornado demolished it. As you can see, there is nothing left of it but piles of debris (or rubble) where houses used to be: [![](https://i.stack.imgur.com/0a8LA.jpg)](https://i.stack.imgur.com/0a8LA.jpg) (source: [wxug.com](https://icons.wxug.com/hurricane/2013/moore_wide_destruction.jpg))
**Wreckage** refers to one or more large pieces of something that has been *wrecked*, severely damaged by something other than time. (e.g. the wreckage of a bus that has fallen over a small cliff). **Debris** is from the French word *débris*, originally meaning to *break down*, and refers to many small pieces of wreckage or remains. (e.g. the debris from a bus that had contained a terrorist bomb.) **Remains** are what *remain* of something that has decayed, rotted, rusted, scavenged, etc. over a long time period (e.g. the remains of an abandoned bus).
61,366,909
Consider below code: ```js let myData = { a: 1 } const app = new Vue({ data: myData }); ``` As Vue docs says when we try to add a property like below, the new property isn't reactive: ```js myData.b = 12; console.log(app.b); // undefined ``` Vue docs suggests using `Vue.set`: ```js Vue.set(myData, 'b', 12); console.log(app.b); // still undefined ``` Vue docs says `Vue.set` adds a property to a reactive object! But I want to add `b` to the data's root level. I don't know how to make `b` reactive.
2020/04/22
[ "https://Stackoverflow.com/questions/61366909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3578287/" ]
> > The question is simple: How to create a root level property and make it reactive? > > > The properties in `data` are only reactive if they existed when the instance was created. That means if you add a new property, like: ``` myData.b = 12; ``` Then changes to `b` will not trigger any view updates. If you know you'll need a property later, but it starts out empty or non-existent, you'll need to set some initial value. For example: ``` let myData = { a: 1, b: 0 } // or, let myData = { a: 1, b: null } ``` Now you can see changes to `b` are showing in the UI also: ```js let myData = { a: 1, b: 0 } const app = new Vue({ el: "#myApp", data: myData }) myData.b = 12; console.log(app.$data); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <div id="myApp"> <pre>{{ b }} </pre> </div> ```
I can't find in documentation if you can add property to the root level and make it also reactive, but there is alternative solution. ```js let myData = { obj: { a: 1 } } const app = new Vue({ data: myData, watch: { obj: { handler(val) { console.log('watching !', val) }, deep: true } } }); Vue.set(app.obj, 'b', 12) console.log(app.$data) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> ```
61,366,909
Consider below code: ```js let myData = { a: 1 } const app = new Vue({ data: myData }); ``` As Vue docs says when we try to add a property like below, the new property isn't reactive: ```js myData.b = 12; console.log(app.b); // undefined ``` Vue docs suggests using `Vue.set`: ```js Vue.set(myData, 'b', 12); console.log(app.b); // still undefined ``` Vue docs says `Vue.set` adds a property to a reactive object! But I want to add `b` to the data's root level. I don't know how to make `b` reactive.
2020/04/22
[ "https://Stackoverflow.com/questions/61366909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3578287/" ]
The docs clearly say you **cannot add** top [level keys](https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects). > > Vue does not allow dynamically adding new root-level reactive properties to an already created instance. > > > You **must** add a key to the root level object so you can update it later. You can either: * create a key with a default value that you'll update. This means that you know the key before hand * create an empty object with a generic key (for instance `dynamicProps`) and use `Vue.set` to add dynamic keys at runtime to it.
> > The question is simple: How to create a root level property and make it reactive? > > > The properties in `data` are only reactive if they existed when the instance was created. That means if you add a new property, like: ``` myData.b = 12; ``` Then changes to `b` will not trigger any view updates. If you know you'll need a property later, but it starts out empty or non-existent, you'll need to set some initial value. For example: ``` let myData = { a: 1, b: 0 } // or, let myData = { a: 1, b: null } ``` Now you can see changes to `b` are showing in the UI also: ```js let myData = { a: 1, b: 0 } const app = new Vue({ el: "#myApp", data: myData }) myData.b = 12; console.log(app.$data); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script> <div id="myApp"> <pre>{{ b }} </pre> </div> ```
61,366,909
Consider below code: ```js let myData = { a: 1 } const app = new Vue({ data: myData }); ``` As Vue docs says when we try to add a property like below, the new property isn't reactive: ```js myData.b = 12; console.log(app.b); // undefined ``` Vue docs suggests using `Vue.set`: ```js Vue.set(myData, 'b', 12); console.log(app.b); // still undefined ``` Vue docs says `Vue.set` adds a property to a reactive object! But I want to add `b` to the data's root level. I don't know how to make `b` reactive.
2020/04/22
[ "https://Stackoverflow.com/questions/61366909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3578287/" ]
The docs clearly say you **cannot add** top [level keys](https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects). > > Vue does not allow dynamically adding new root-level reactive properties to an already created instance. > > > You **must** add a key to the root level object so you can update it later. You can either: * create a key with a default value that you'll update. This means that you know the key before hand * create an empty object with a generic key (for instance `dynamicProps`) and use `Vue.set` to add dynamic keys at runtime to it.
I can't find in documentation if you can add property to the root level and make it also reactive, but there is alternative solution. ```js let myData = { obj: { a: 1 } } const app = new Vue({ data: myData, watch: { obj: { handler(val) { console.log('watching !', val) }, deep: true } } }); Vue.set(app.obj, 'b', 12) console.log(app.$data) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> ```
249,394
I have 2 files containing a list of songs. hdsongs.txt and sdsongs.txt I wrote a simple script to list all songs and output to text files, to then run a diff against. It works fine for the most part, but the actual diff command in the script is showing the same line as being different. This is actually happening for multiple lines, but not all. Here is an example of a song in both files: ``` $ grep Apologize \*songs\* hdsongs.txt:Timbaland/Apologize.mp3 sdsongs.txt:Timbaland/Apologize.mp3 ``` There is no trailing special character that I can see: ``` $ cat -A hdsongs.txt sdsongs.txt | grep Apologize Timbaland/Apologize.mp3$ Timbaland/Apologize.mp3$ ``` When I run diff, it shows the same line being in each file; but aren't the lines the same? ``` $ diff hdsongs.txt sdsongs.txt | grep Apologize > Timbaland/Apologize.mp3 < Timbaland/Apologize.mp3 ``` This is similar to the thread here: [diff reports two files differ, although they are the same!](https://unix.stackexchange.com/questions/45711/diff-reports-two-files-differ-although-they-are-the-same) but this is for lines within the file, not the whole file, and the resolution there doesn't seem to fit in this case. ``` $ diff <(cat -A phonesongsonly.txt) <(cat -A passportsongsonly.txt) | grep Apologize < Timbaland/Apologize.mp3$ > Timbaland/Apologize.mp3$ $ wdiff -w "$(tput bold;tput setaf 1)" -x "$(tput sgr0)" -y "$(tput bold;tput setaf 2)" -z "$(tput sgr0)" hdsongs.txt sdsongs.txt | grep Apologize >Timbaland/Apologize.mp3 >Timbaland/Apologize.mp3 ``` Does anyone know why diff would report the same line twice like this?
2015/12/14
[ "https://unix.stackexchange.com/questions/249394", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/147481/" ]
My guess is you simply haven't sorted the files. That's one of the behaviors you can get on unsorted input: ``` $ cat file1 foo bar $ cat file2 bar foo $ $ diff file1 file2 1d0 < foo 2a2 > foo ``` But, if you sort: ``` $ diff <(sort file1) <(sort file2) $ ``` The `diff` program's job is to tell you whether two files are identical and, if not, where they differ. It is not designed to find similarities between different lines. If line X of the one file is not the same as line X of the other, then the files are not the same. It doesn't matter if they contain exactly the same information, if that information is organized in a different way, the files are reported as different.
I would suggest trying to use something like the hexdiff program to get a binary/hexadecimal output, as the human eye can't always tell the difference between the characters a computer displays, and some characters may not be displayed.
249,394
I have 2 files containing a list of songs. hdsongs.txt and sdsongs.txt I wrote a simple script to list all songs and output to text files, to then run a diff against. It works fine for the most part, but the actual diff command in the script is showing the same line as being different. This is actually happening for multiple lines, but not all. Here is an example of a song in both files: ``` $ grep Apologize \*songs\* hdsongs.txt:Timbaland/Apologize.mp3 sdsongs.txt:Timbaland/Apologize.mp3 ``` There is no trailing special character that I can see: ``` $ cat -A hdsongs.txt sdsongs.txt | grep Apologize Timbaland/Apologize.mp3$ Timbaland/Apologize.mp3$ ``` When I run diff, it shows the same line being in each file; but aren't the lines the same? ``` $ diff hdsongs.txt sdsongs.txt | grep Apologize > Timbaland/Apologize.mp3 < Timbaland/Apologize.mp3 ``` This is similar to the thread here: [diff reports two files differ, although they are the same!](https://unix.stackexchange.com/questions/45711/diff-reports-two-files-differ-although-they-are-the-same) but this is for lines within the file, not the whole file, and the resolution there doesn't seem to fit in this case. ``` $ diff <(cat -A phonesongsonly.txt) <(cat -A passportsongsonly.txt) | grep Apologize < Timbaland/Apologize.mp3$ > Timbaland/Apologize.mp3$ $ wdiff -w "$(tput bold;tput setaf 1)" -x "$(tput sgr0)" -y "$(tput bold;tput setaf 2)" -z "$(tput sgr0)" hdsongs.txt sdsongs.txt | grep Apologize >Timbaland/Apologize.mp3 >Timbaland/Apologize.mp3 ``` Does anyone know why diff would report the same line twice like this?
2015/12/14
[ "https://unix.stackexchange.com/questions/249394", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/147481/" ]
My guess is you simply haven't sorted the files. That's one of the behaviors you can get on unsorted input: ``` $ cat file1 foo bar $ cat file2 bar foo $ $ diff file1 file2 1d0 < foo 2a2 > foo ``` But, if you sort: ``` $ diff <(sort file1) <(sort file2) $ ``` The `diff` program's job is to tell you whether two files are identical and, if not, where they differ. It is not designed to find similarities between different lines. If line X of the one file is not the same as line X of the other, then the files are not the same. It doesn't matter if they contain exactly the same information, if that information is organized in a different way, the files are reported as different.
Since you have not stated that the files are sorted, I'll assume that they aren't.  This is the expected output from `diff` when a line appears in both files, but in different locations.  This would be clear if you looked at the entire `diff` output, rather than piping it through `grep`.
52,453,330
Here I need to convert my nested JSON into a custom JSON without having nested objects. ```js function transform(){ let items = [ { "carId":328288, "firstName":"yathindra", "lastName":"rawya", "list":[ { "id":182396, "isAvail":false, "stateId":288, "state":"Awesome" }, { "id":182396, "isAvail":false, "stateId":678, "state":"Cool1" } ], }, { "carId":3282488, "firstName":"yathindraR", "lastName":"K", "list":[ { "id":18232396, "isAvail":false, "stateId":22388, "state":"Awesome" }, { "id":182356796, "isAvail":false, "stateId":45678, "state":"Cool" } ], } ] let customList = []; for(let i=0;i<items.length;i++){ let temp = new Array() for(let j=0;j<items[i].list.length;j++){ temp.push( items[i].list[j].state ) } customList.push({ fname: items[i].firstName, lname: items[i].lastName, ...temp }) } console.log(JSON.stringify(customList)) } transform(); ``` Below is the output I am getting. ``` [{"0":"Awesome","1":"Cool1","fname":"yathindra","lname":"rawya"},{"0":"Awesome","1":"Cool","fname":"yathindraR","lname":"K"}] ``` But I don't want to place items in the temp array in the beginning. I want them to place at last. Something like this. ``` [{"fname":"yathindra","lname":"rawya","0":"Awesome","1":"Cool1"},{"fname":"yathindraR","lname":"K","0":"Awesome","1":"Cool"}] ``` Here there is no need of using numbers as keys in the temp array. Because I want only values of each. **So its ok if the keys of all are strings and order of values matters**. How to make this done?
2018/09/22
[ "https://Stackoverflow.com/questions/52453330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8353827/" ]
Please replace your code with below one, it will work straight away. Key will be "state-1", "state-2" instead of "0", "1" ``` function transform(){ let items = [ { "carId":328288, "firstName":"yathindra", "lastName":"rawya", "list":[ { "id":182396, "isAvail":false, "stateId":288, "state":"Awesome" }, { "id":182396, "isAvail":false, "stateId":678, "state":"Cool1" } ], }, { "carId":3282488, "firstName":"yathindraR", "lastName":"K", "list":[ { "id":18232396, "isAvail":false, "stateId":22388, "state":"Awesome" }, { "id":182356796, "isAvail":false, "stateId":45678, "state":"Cool" } ], } ] let customList = []; for(let i=0;i<items.length;i++){ let temp = {}; for(let j=0;j<items[i].list.length;j++){ temp["state-"+(j+1)] = items[i].list[j].state; } customList.push({ fname: items[i].firstName, lname: items[i].lastName, ...temp }) } console.log(JSON.stringify(customList)) } transform(); ```
Prepend your key with a zero, and then insertion order is maintained. In a CSV, that seems a good option. If you want to use the spread operator, use an object instead of an array. ```js function transform() { let items = [{ "carId": 328288, "firstName": "yathindra", "lastName": "rawya", "list": [{ "id": 182396, "isAvail": false, "stateId": 288, "state": "Awesome" }, { "id": 182396, "isAvail": false, "stateId": 678, "state": "Cool1" } ], }, { "carId": 3282488, "firstName": "yathindraR", "lastName": "K", "list": [{ "id": 18232396, "isAvail": false, "stateId": 22388, "state": "Awesome" }, { "id": 182356796, "isAvail": false, "stateId": 45678, "state": "Cool" } ], } ] let customList = []; for (let i = 0; i < items.length; i++) { let temp = {} for (let j = 0; j < items[i].list.length; j++) { temp['0' + j] = items[i].list[j].state } const o = { fname: items[i].firstName, lname: items[i].lastName, ...temp } customList.push(o) } console.log(JSON.stringify(customList)) } transform(); ``` That said, there are other ways you can map your items... ```js function transform() { let items = [{ "carId": 328288, "firstName": "yathindra", "lastName": "rawya", "list": [{ "id": 182396, "isAvail": false, "stateId": 288, "state": "Awesome" }, { "id": 182396, "isAvail": false, "stateId": 678, "state": "Cool1" } ], }, { "carId": 3282488, "firstName": "yathindraR", "lastName": "K", "list": [{ "id": 18232396, "isAvail": false, "stateId": 22388, "state": "Awesome" }, { "id": 182356796, "isAvail": false, "stateId": 45678, "state": "Cool" } ], } ] let customList = items.map(item => { let j = 0; let list = item.list.reduce((acc, it) => { acc['0' + j++] = it.state; return acc }, {}) return { fname: item.firstName, lname: item.lastName, ...list } }) console.log(JSON.stringify(customList)) } transform(); ```
52,453,330
Here I need to convert my nested JSON into a custom JSON without having nested objects. ```js function transform(){ let items = [ { "carId":328288, "firstName":"yathindra", "lastName":"rawya", "list":[ { "id":182396, "isAvail":false, "stateId":288, "state":"Awesome" }, { "id":182396, "isAvail":false, "stateId":678, "state":"Cool1" } ], }, { "carId":3282488, "firstName":"yathindraR", "lastName":"K", "list":[ { "id":18232396, "isAvail":false, "stateId":22388, "state":"Awesome" }, { "id":182356796, "isAvail":false, "stateId":45678, "state":"Cool" } ], } ] let customList = []; for(let i=0;i<items.length;i++){ let temp = new Array() for(let j=0;j<items[i].list.length;j++){ temp.push( items[i].list[j].state ) } customList.push({ fname: items[i].firstName, lname: items[i].lastName, ...temp }) } console.log(JSON.stringify(customList)) } transform(); ``` Below is the output I am getting. ``` [{"0":"Awesome","1":"Cool1","fname":"yathindra","lname":"rawya"},{"0":"Awesome","1":"Cool","fname":"yathindraR","lname":"K"}] ``` But I don't want to place items in the temp array in the beginning. I want them to place at last. Something like this. ``` [{"fname":"yathindra","lname":"rawya","0":"Awesome","1":"Cool1"},{"fname":"yathindraR","lname":"K","0":"Awesome","1":"Cool"}] ``` Here there is no need of using numbers as keys in the temp array. Because I want only values of each. **So its ok if the keys of all are strings and order of values matters**. How to make this done?
2018/09/22
[ "https://Stackoverflow.com/questions/52453330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8353827/" ]
Please replace your code with below one, it will work straight away. Key will be "state-1", "state-2" instead of "0", "1" ``` function transform(){ let items = [ { "carId":328288, "firstName":"yathindra", "lastName":"rawya", "list":[ { "id":182396, "isAvail":false, "stateId":288, "state":"Awesome" }, { "id":182396, "isAvail":false, "stateId":678, "state":"Cool1" } ], }, { "carId":3282488, "firstName":"yathindraR", "lastName":"K", "list":[ { "id":18232396, "isAvail":false, "stateId":22388, "state":"Awesome" }, { "id":182356796, "isAvail":false, "stateId":45678, "state":"Cool" } ], } ] let customList = []; for(let i=0;i<items.length;i++){ let temp = {}; for(let j=0;j<items[i].list.length;j++){ temp["state-"+(j+1)] = items[i].list[j].state; } customList.push({ fname: items[i].firstName, lname: items[i].lastName, ...temp }) } console.log(JSON.stringify(customList)) } transform(); ```
Javascript `Object` first shows the sorted number list and then, the rest of the object's content as it is! run the following code and see what happens:D ```js console.log(JSON.stringify({1:true, b:false, 3:false})) ``` So if you want to keep your order, don't use numbers as keys!
36,948,316
I am just wondering if there is a way to simulate a "no connection" event in a mocha unit test. I have a method that return a promise that should wait for an internet connection with a polling strategy and I want to test it out with mocha. There is a method to achieve such a result. Some code: ``` it('should wait for connection', function(done) { this.timeout(2500); //simulate an internet connection drop here wait.connection().then(done); setTimeout(//activate connection, 2000); }); ``` Thank you for any response. [EDIT]: Here there is the code I want to test: ``` var wait = { connection: function() { 'use strict'; var settings = {retry: 1000}; return new Promise(function(resolve) { (function poll() { needle.get('https://api.ipify.org', function(error, response) { if(!error && response.statusCode === 200 && /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(response.body)) resolve(); else wait.for(settings.retry).then(poll); }); })(); }); } }; ``` In this case the Promise will remain pending since a new connection is available. How can I simulate an error on the `needle` get request?
2016/04/29
[ "https://Stackoverflow.com/questions/36948316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803678/" ]
You can use [sinon](http://sinonjs.org/) to stub `needle.get` ``` var needle = require("needle"); var sinon = require("sinon");; before(() => { sinon.stub(needle, "get", (url, calback) => { var dummyError = {}; callback(dummyError); }) }); // Run your 'it' here after(() => { needle.get.restore(); }); ```
If you have no connection or any problems of connection, use the `reject()` of your promise and catch them. `done` is a function, and if you call the function with a non-null parameter, it means that your test is not good. Maybe you have to try: ``` my_object.wait.connection() .then(() => done(1)) .catch(() => done()); ```