apt-get install ca-certificates
The s
makes the difference ;)
return JsonConvert.SerializeObject(images.ToList(), Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
using Newtonsoft.Json;
I've been using this in an Xcode JNI project to recursively build my test classes:
find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}
Here is what I would do.
In your base class (can be rootVC BaseVc etc),
A. Write a Protocol to send the "DidFinishReloading" callback.
@protocol ReloadComplition <NSObject>
@required
- (void)didEndReloading:(UITableView *)tableView;
@end
B. Write a generic method to reload the table view.
-(void)reloadTableView:(UITableView *)tableView withOwner:(UIViewController *)aViewController;
In the base class method implementation, call reloadData followed by delegateMethod with delay.
-(void)reloadTableView:(UITableView *)tableView withOwner:(UIViewController *)aViewController{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[tableView reloadData];
if(aViewController && [aViewController respondsToSelector:@selector(didEndReloading:)]){
[aViewController performSelector:@selector(didEndReloading:) withObject:tableView afterDelay:0];
}
}];
}
Confirm to the reload completion protocol in all the view controllers where you need the callback.
-(void)didEndReloading:(UITableView *)tableView{
//do your stuff.
}
Reference: https://discussions.apple.com/thread/2598339?start=0&tstart=0
The browser discloses it in navigator.userAgent
. If you're using jQuery, you're better off using jQuery.browser
as @Rab Nawaz said. However, as the API documentation says, it's better to check for feature support if possible. Quoting the documentation:
We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.
Here is a code example:
function isIE() {
if (window.jQuery) {
return jQuery.browser.msie || false;
} else {
// adapted from jQuery's source:
return navigator.userAgent.toLowerCase().indexOf('msie') >= 0;
}
}
In C++ (or in C with C-style casts), you could create the function:
/* Function to control # of decimal places to be output for x */
double showDecimals(const double& x, const int& numDecimals) {
int y=x;
double z=x-y;
double m=pow(10,numDecimals);
double q=z*m;
double r=round(q);
return static_cast<double>(y)+(1.0/m)*r;
}
Then std::cout << showDecimals(37.777779,2);
would produce: 37.78.
Obviously you don't really need to create all 5 variables in that function, but I leave them there so you can see the logic. There are probably simpler solutions, but this works well for me--especially since it allows me to adjust the number of digits after the decimal place as I need.
Swift 5.0, 4.0, 3.0 Updated Solution
Insert at Bottom
self.yourArray.append(msg)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()
Insert at Top of TableView
self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()
In C/C++ sizeof
. always gives the number of bytes in the entire object, and arrays are treated as one object. Note: sizeof
a pointer--to the first element of an array or to a single object--gives the size of the pointer, not the object(s) pointed to. Either way, sizeof
does not give the number of elements in the array (its length). To get the length, you need to divide by the size of each element. eg.,
for( unsigned int a = 0; a < sizeof(texts)/sizeof(texts[0]); a = a + 1 )
As for doing it the C++11 way, the best way to do it is probably
for(const string &text : texts)
cout << "value of text: " << text << endl;
This lets the compiler figure out how many iterations you need.
EDIT: as others have pointed out, std::array
is preferred in C++11 over raw arrays; however, none of the other answers addressed why sizeof
is failing the way it is, so I still think this is the better answer.
You need to set up SSH keys.
This GitHub page explains how to generate keys.
If you have an existing key, you copy $HOME/.ssh/id_rsa.pub
and paste it into the GitHub SSH settings page.
You can repeat it by fetching again the data
while($row = mysql_fetch_assoc($result)){
//another html element
<div>$row['name']</div>
<div>$row['title']</div>
//and so on
}
or you need to put it on the variable and call display it again on other html element
$name = $row['name'];
$title = $row['title']
//and so on
then put it on the other element, but if you want to call all the data of each id, you need to do the first code
Why not write a little method yourself
public Character[] toCharacterArray( String s ) {
if ( s == null ) {
return null;
}
int len = s.length();
Character[] array = new Character[len];
for (int i = 0; i < len ; i++) {
/*
Character(char) is deprecated since Java SE 9 & JDK 9
Link: https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html
array[i] = new Character(s.charAt(i));
*/
array[i] = s.charAt(i);
}
return array;
}
In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.
Also read Protect from sql injection it will guide how you can protect your database.
Hope it help you to understand also any question comment me.
Your code should be something like
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
How To Read XML Data into a DataSet by Using Visual C# .NET contains some details. Basically, you can use the overloaded DataSet method ReadXml to get the data into a DataSet. Your XML data will be in the first DataTable there.
There is also a DataTable.ReadXml method.
To go from SCRATCH with SQLite DB to importing the CSV into a table:
sqlite3 <your_db_file_name>
*It will be created as an empty file.CREATE TABLE <table_Name> (<field_name1> <Type>, <field_name2> <type>);
Once you have the table created and the columns match your data from the file then you can do the above...
.mode csv <table_name>
.import <filename> <table_name>
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
On top of @kp's answer:
I'm dealing with this and in my case, I have to show a child element and correct the height of the parent object accordingly (auto-sizing is not working in a bootstrap header for some reason I don't have time to debug).
But instead of using javascript to modify the parent, I think I'll dynamically add a CSS class to the parent and CSS-selectively show the children accordingly. This will maintain the decisions in the logic and not based on a CSS state.
tl;dr; apply the a
and b
styles to the parent <div>
, not the child (of course, not everyone will be able to do this. i.e. Angular components making decisions of their own).
<style>
.parent { height: 50px; }
.parent div { display: none; }
.with-children { height: 100px; }
.with-children div { display: block; }
</style>
<div class="parent">
<div>child</div>
</div>
<script>
// to show the children
$('.parent').addClass('with-children');
</script>
I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.
<table>
<tr><td>Name:</td><td><input type="text"/></td></tr>
<tr><td>Age:</td><td><input type="text"/></td></tr>
</table>
<!--You can add the fields as you want-->
td{
text-align:right;
}
If you find any security issue then follow steps as well
Thats DONE!
Although I don't know what RDBMS you are using, you probably need to give the whole column specification, not just say that you now want it to be nullable. For example, if it's currently INT NOT NULL
, you should issue ALTER TABLE Merchant_Pending_Functions Modify NumberOfLocations INT
.
There are 3 ways to pass data from Parent to Children
Through Children Router Resolver if you have to receive different data
this.data = this.route.snaphsot.data['dataFromResolver'];
Through Parent Router Resolver if your have to receive the same data from parent
this.data = this.route.parent.snaphsot.data['dataFromResolver'];
Note1: You can read about resolver here. There is also an example of resolver and how to register the resolver into the module and then retrieve data from resolver into the component. The resolver registration is the same on the parent and child.
Note2: You can read about ActivatedRoute here to be able to get data from router
Hope you are having app.module.ts
.
In your app.module.ts
add below line-
exports: [myComponentComponent],
Like this:
import { NgModule, Renderer } from '@angular/core';
import { HeaderComponent } from './headerComponent/header.component';
import { HeaderMainComponent } from './component';
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [
HeaderMainComponent,
HeaderComponent
],
imports: [
RouterModule,
],
providers: [],
bootstrap: [HeaderMainComponent],
exports: [HeaderComponent],
})
export class HeaderModule { }
You can initialize the values as empty strings and fill them in later as they are found.
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
I did like this..
Right click on the project--> configure-->convert to maven project. Right click on the project-->maven-->add dependencies.
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
To fully understand this, you must grasp the following concepts:
First of all (And it's been preached enough), arrays are not pointers. Instead, in most uses, they 'decay' to the address to their first element, which can be assigned to a pointer:
int a[] = {1, 2, 3};
int *p = a; // p now points to a[0]
I assume it works this way so that the array's contents can be accessed without copying all of them. That's just a behavior of array types and is not meant to imply that they are same thing.
Multidimensional arrays are just a way to 'partition' memory in a way that the compiler/machine can understand and operate on.
For instance, int a[4][3][5]
= an array containing 4*3*5 (60) 'chunks' of integer-sized memory.
The advantage over using int a[4][3][5]
vs plain int b[60]
is that they're now 'partitioned' (Easier to work with their 'chunks', if needed), and the program can now perform bound checking.
In fact, int a[4][3][5]
is stored exactly like int b[60]
in memory - The only difference is that the program now manages it as if they're separate entities of certain sizes (Specifically, four groups of three groups of five).
Keep in mind: Both int a[4][3][5]
and int b[60]
are the same in memory, and the only difference is how they're handled by the application/compiler
{
{1, 2, 3, 4, 5}
{6, 7, 8, 9, 10}
{11, 12, 13, 14, 15}
}
{
{16, 17, 18, 19, 20}
{21, 22, 23, 24, 25}
{26, 27, 28, 29, 30}
}
{
{31, 32, 33, 34, 35}
{36, 37, 38, 39, 40}
{41, 42, 43, 44, 45}
}
{
{46, 47, 48, 49, 50}
{51, 52, 53, 54, 55}
{56, 57, 58, 59, 60}
}
From this, you can clearly see that each "partition" is just an array that the program keeps track of.
Now, arrays are syntactically different from pointers. Specifically, this means the compiler/machine will treat them differently. This may seem like a no brainer, but take a look at this:
int a[3][3];
printf("%p %p", a, a[0]);
The above example prints the same memory address twice, like this:
0x7eb5a3b4 0x7eb5a3b4
However, only one can be assigned to a pointer so directly:
int *p1 = a[0]; // RIGHT !
int *p2 = a; // WRONG !
Why can't a
be assigned to a pointer but a[0]
can?
This, simply, is a consequence of multidimensional arrays, and I'll explain why:
At the level of 'a
', we still see that we have another 'dimension' to look forward to. At the level of 'a[0]
', however, we're already in the top dimension, so as far as the program is concerned we're just looking at a normal array.
You may be asking:
Why does it matter if the array is multidimensional in regards to making a pointer for it?
It's best to think this way:
A 'decay' from a multidimensional array is not just an address, but an address with partition data (AKA it still understands that its underlying data is made of other arrays), which consists of boundaries set by the array beyond the first dimension.
This 'partition' logic cannot exist within a pointer unless we specify it:
int a[4][5][95][8];
int (*p)[5][95][8];
p = a; // p = *a[0] // p = a+0
Otherwise, the meaning of the array's sorting properties are lost.
Also note the use of parenthesis around *p
: int (*p)[5][95][8]
- That's to specify that we're making a pointer with these bounds, not an array of pointers with these bounds: int *p[5][95][8]
Let's review:
In brief: multidimensional arrays decay to addresses that carry the ability to understand their contents.
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
git config --global fetch.prune true
To always --prune
for git fetch
and git pull
in all your Git repositories:
git config --global fetch.prune true
This above command appends in your global Git configuration (typically ~/.gitconfig
) the following lines. Use git config -e --global
to view your global configuration.
[fetch]
prune = true
git config remote.origin.prune true
To always --prune
but from one single repository:
git config remote.origin.prune true
#^^^^^^
#replace with your repo name
This above command adds in your local Git configuration (typically .git/config
) the below last line. Use git config -e
to view your local configuration.
[remote "origin"]
url = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
fetch = +refs/heads/*:refs/remotes/origin/*
prune = true
You can also use --global
within the second command or use instead --local
within the first command.
git config --global gui.pruneDuringFetch true
If you use git gui
you may also be interested by:
git config --global gui.pruneDuringFetch true
that appends:
[gui]
pruneDuringFetch = true
The corresponding documentations from git help config
:
--global
For writing options: write to global
~/.gitconfig
file rather than the repository.git/config
, write to$XDG_CONFIG_HOME/git/config
file if this file exists and the~/.gitconfig
file doesn’t.
--local
For writing options: write to the repository
.git/config
file. This is the default behavior.
fetch.prune
If true, fetch will automatically behave as if the
--prune
option was given on the command line. See alsoremote.<name>.prune
.
gui.pruneDuringFetch
"true" if git-gui should prune remote-tracking branches when performing a fetch. The default value is "false".
remote.<name>.prune
When set to true, fetching from this remote by default will also remove any remote-tracking references that no longer exist on the remote (as if the
--prune
option was given on the command line). Overridesfetch.prune
settings, if any.
It's an HtmlGenericControl so not sure what the recommended way to do this is, so you could also do:
testSpace.Attributes.Add("style", "text-align: center;");
or
testSpace.Attributes.Add("class", "centerIt");
or
testSpace.Attributes["style"] = "text-align: center;";
or
testSpace.Attributes["class"] = "centerIt";
You can also use this (based on a few of the above answers):
file = open('filename.txt', 'w')
file.close()
of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.
happy coding!
You can use:
Bulk collect along with FOR ALL that is called Bulk binding
.
Because PL/SQL forall
operator speeds 30x faster for simple table inserts.
BULK_COLLECT
and Oracle FORALL
together these two features are known as Bulk Binding
. Bulk Binds are a PL/SQL technique where, instead of multiple individual SELECT
, INSERT
, UPDATE
or DELETE
statements are executed to retrieve from, or store data in, at table, all of the operations are carried out at once, in bulk. This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a time. To do bulk binds with INSERT
, UPDATE
, and DELETE
statements, you enclose the SQL statement within a PL/SQL FORALL
statement. To do bulk binds with SELECT
statements, you include the BULK COLLECT
clause in the SELECT
statement instead of using INTO
.
It improves performance.
In Gson 2.7.2 it's as easy as
Gson gson = new Gson();
String serialized = gson.toJson(map);
From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.
The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:
string s = Properties.Settings.Default.MyConnectionString;
There's nothing wrong with include file in head. It seems you forgot to add;
. Please try this one:
<body onload="imageRefreshBig();">
But as per my knowledge semicolons are optional. You can try with ;
but better debug code and see if chrome console gives any error.
I hope this helps.
If you want to make sure that last row does not wrap and thus size the way you want it, have a look at
td {
white-space: nowrap;
}
In win7, if you want to set the correct timezone as a parameter in JRE, you have to edit the file deployment.properties
stored in path c:\users\%username%\appdata\locallow\sun\java\deployment
adding the string deployment.javaws.jre.1.args=-Duser.timezone\=
my_time_zone
Another option if you're using Flavors in Android Studio:
Click Build -> Select Build Variant.
In the list click the variant you're working in and it will turn green and the others will have the red J.
The following code does what is required
function doTest() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hello');
}
When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder
add "my-resource.txt" file inside the new folder. Then in your code:
InputStream res =
Main.class.getResourceAsStream("/my-resource.txt");
BufferedReader reader =
new BufferedReader(new InputStreamReader(res));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split()
or separate it into two parts using indices:
a = "abc"
a, result = a[:-1], a[-1]
This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):
for result in reversed(a):
...
I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split
:
ans = "foo,blah,etc."
for a in ans.split(","):
...
You can extract the different parts out quite neatly using a regex pattern:
In [11]: df.row.str.extract('(?P<fips>\d{5})((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))')
Out[11]:
fips 1 state county state_code
0 00000 UNITED STATES UNITED STATES NaN NaN
1 01000 ALABAMA ALABAMA NaN NaN
2 01001 Autauga County, AL NaN Autauga County AL
3 01003 Baldwin County, AL NaN Baldwin County AL
4 01005 Barbour County, AL NaN Barbour County AL
[5 rows x 5 columns]
To explain the somewhat long regex:
(?P<fips>\d{5})
\d
) and names them "fips"
.The next part:
((?P<state>[A-Z ]*$)|(?P<county>.*?), (?P<state_code>[A-Z]{2}$))
Does either (|
) one of two things:
(?P<state>[A-Z ]*$)
*
) of capital letters or spaces ([A-Z ]
) and names this "state"
before the end of the string ($
),or
(?P<county>.*?), (?P<state_code>[A-Z]{2}$))
.*
) thenstate_code
before the end of the string ($
).In the example:
Note that the first two rows hit the "state" (leaving NaN in the county and state_code columns), whilst the last three hit the county, state_code (leaving NaN in the state column).
That's not possible with CSS, you will have to use the Javascript for that. Although you can set the width of the p to as much as 30 characters and next letters will automatically come down but again this won't be that accurate and will vary if the characters are in capital.
Since hiding the badge is not really legit as per the TOU, and existing placement options were breaking my UI and/or UX, I've come up with the following customization that mimics fixed positioning, but is instead rendered inline:
You just need to apply some CSS on your badge container:
.badge-container {
display: flex;
justify-content: flex-end;
overflow: hidden;
width: 70px;
height: 60px;
margin: 0 auto;
box-shadow: 0 0 4px #ddd;
transition: linear 100ms width;
}
.badge-container:hover {
width: 256px;
}
I think that's as far as you can legally push it.
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
Would this solution work?:
add following line to SceneDelegate: window.rootViewController?.view.backgroundColor = .black
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let windowScene = scene as? UIWindowScene {
window.rootViewController?.view.backgroundColor = .black
}
And if you'd like to extract the differences between the two strings, you can use String::Diff.
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
In XML, this what I use for achieving the same result. May be this is more intuitive.
scale_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:pivotX="50%"
android:pivotY="100%"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
scale_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:pivotX="50%"
android:pivotY="100%"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>
See the animation on the X axis is from 1.0 -> 1.0
which means you don't have any scaling up in that direction and stays at the full width while, on the Y axis you get 0.0 -> 1.0
scaling, as shown in the graphic in the question. Hope this helps someone.
Some might want to know the java code as we see one requested.
Place the animation files in anim
folder and then load and set animation files something like.
Animation scaleDown = AnimationUtils.loadAnimation(youContext, R.anim.scale_down);
ImagView v = findViewById(R.id.your_image_view);
v.startAnimation(scaleDown);
EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.
Unfortunately, np.polynomial.polynomial.polyfit
returns the coefficients in the opposite order of that for np.polyfit
and np.polyval
(or, as you used np.poly1d
). To illustrate:
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
0.65459882])
In [41]: np.polyfit(x, y, 4)
Out[41]:
array([ 0.65459882, -8.859311 , 44.83281407, -100.53595375,
84.29340846])
In general: np.polynomial.polynomial.polyfit
returns coefficients [A, B, C]
to A + Bx + Cx^2 + ...
, while np.polyfit
returns: ... + Ax^2 + Bx + C
.
So if you want to use this combination of functions, you must reverse the order of coefficients, as in:
ffit = np.polyval(coefs[::-1], x_new)
However, the documentation states clearly to avoid np.polyfit
, np.polyval
, and np.poly1d
, and instead to use only the new(er) package.
You're safest to use only the polynomial package:
import numpy.polynomial.polynomial as poly
coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)
Or, to create the polynomial function:
ffit = poly.Polynomial(coefs) # instead of np.poly1d
plt.plot(x_new, ffit(x_new))
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
One way to do this is by changing the parent of the overlapping picture box to the PictureBox over which it is lapping. Since the Visual Studio designer doesn't allow you to add a PictureBox to a PictureBox, this will have to be done in your code (Form1.cs) and within the Intializing function:
public Form1()
{
InitializeComponent();
pictureBox7.Controls.Add(pictureBox8);
pictureBox8.Location = new Point(0, 0);
pictureBox8.BackColor = Color.Transparent;
}
Just change the picture box names to what ever you need. This should return:
I found another way may be it will help you
=INDEX( SORT( A5:D ; 1 ; FALSE) ; 1 )
-will return last row
More info from anab here: https://groups.google.com/forum/?fromgroups=#!topic/How-to-Documents/if0_fGVINmI
A variation on @gauss256's answer, deleting .svn
, worked for me:
rm -rf troublesome_folder/.svn
svn add troublesome_folder
svn commit
Before Gauss's solution I tried @jwir3's approach and got no joy:
svn cleanup
svn cleanup *
svn cleanup troublesome_folder
svn add --force troublesome_folder
svn commit
Here is another way to do it, if you need something flexible where you want to display help if specific params are passed, none at all or more than 1 conflicting arg:
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--days', required=False, help="Check mapped inventory that is x days old", default=None)
parser.add_argument('-e', '--event', required=False, action="store", dest="event_id",
help="Check mapped inventory for a specific event", default=None)
parser.add_argument('-b', '--broker', required=False, action="store", dest="broker_id",
help="Check mapped inventory for a broker", default=None)
parser.add_argument('-k', '--keyword', required=False, action="store", dest="event_keyword",
help="Check mapped inventory for a specific event keyword", default=None)
parser.add_argument('-p', '--product', required=False, action="store", dest="product_id",
help="Check mapped inventory for a specific product", default=None)
parser.add_argument('-m', '--metadata', required=False, action="store", dest="metadata",
help="Check mapped inventory for specific metadata, good for debugging past tix", default=None)
parser.add_argument('-u', '--update', required=False, action="store_true", dest="make_updates",
help="Update the event for a product if there is a difference, default No", default=False)
args = parser.parse_args()
days = args.days
event_id = args.event_id
broker_id = args.broker_id
event_keyword = args.event_keyword
product_id = args.product_id
metadata = args.metadata
make_updates = args.make_updates
no_change_counter = 0
change_counter = 0
req_arg = bool(days) + bool(event_id) + bool(broker_id) + bool(product_id) + bool(event_keyword) + bool(metadata)
if not req_arg:
print("Need to specify days, broker id, event id, event keyword or past tickets full metadata")
parser.print_help()
sys.exit()
elif req_arg != 1:
print("More than one option specified. Need to specify only one required option")
parser.print_help()
sys.exit()
# Processing logic here ...
Cheers!
Just write:
<script>
var my_variable_name = "<?php echo $php_string; ?>";
</script>
Now it's available as a JavaScript variable by the name of my_variable_name
at any point below the above code.
You can have it on github using the command
git clone https://github.com/coreutils/coreutils.git
You can find all the source codes in the src folder.
You need to have git installed.
Things have changed since 2012, ls
source code has now 5309 lines
In my case, when I tried to start MySQL, I received the same error: The server quit without updating PID file
. This is what I did to fix it (using Terminal):
goto /usr/local/var/mysql
sudo rm -rf hostname.err # Delete .err file
cd /usr/local/mysql/support-files
sudo mysql.server start # Success!
for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done
No rename
or sed
needed. Just bash parameter expansion.
In SQL Server 2008 there are two new Dynamic Management Functions introduced to keep track of object dependencies: sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities:
1/ Returning the entities that refer to a given entity:
SELECT
referencing_schema_name, referencing_entity_name,
referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('<TableName>', 'OBJECT')
2/ Returning entities that are referenced by an object:
SELECT
referenced_schema_name, referenced_entity_name, referenced_minor_name,
referenced_class_desc, is_caller_dependent, is_ambiguous
FROM sys.dm_sql_referenced_entities ('<StoredProcedureName>', 'OBJECT');
Alternatively, you can use sp_depends:
EXEC sp_depends '<TableName>'
Another option is to use a pretty useful tool called SQL Dependency Tracker from Red Gate.
No, but since C++11 there is [u]int8_t.
from p in PriceLog
group p by p.LogDateTime.ToString("MMM") into g
select new
{
LogDate = g.Key.ToString("MMM yyyy"),
GoldPrice = (int)dateGroup.Average(p => p.GoldPrice),
SilverPrice = (int)dateGroup.Average(p => p.SilverPrice)
}
You can invoke a PHP script manually from the command line
hello.php
<?php
echo 'hello world!';
?>
Command line:
php hello.php
Output:
hello world!
See the documentation: http://php.net/manual/en/features.commandline.php
EDIT OP edited the question to add a critical detail: the script is to be executed by another script.
There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include
(docs) and/or require
(docs) (note: include_once
and require_once
are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:
include('hello.php');
/* output
hello world!
*/
Second and slightly more complex is to use shell_exec
(docs). With shell_exec
, you will call the php binary and pass the desired script as the argument. Your code would look like this:
$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/
Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)
$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/
Documentation for functions used
include
: http://us2.php.net/manual/en/function.include.phprequire
: http://us2.php.net/manual/en/function.require.phpshell_exec
: http://us2.php.net/manual/en/function.shell-exec.phpcurl_init
: http://us2.php.net/manual/en/function.curl-init.phpcurl_setopt
: http://us2.php.net/manual/en/function.curl-setopt.phpcurl_exec
: http://us2.php.net/manual/en/function.curl-exec.phpcurl_close
: http://us2.php.net/manual/en/function.curl-close.phpWith the following you can insert multiple values and also have default values but you're creating a new dictionary.
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
$ mail -s "test message from centos" [email protected]
hello from centos linux command line
Ctrl+D to finish
here a is an Object
but b(null)
is not an Object it is a null reference
System.out.println(a instanceof Object); // true
System.out.println(b instanceof Object); // false
here is my similar answer
problem is that the collapse item (div) is nested in the table elements. The div is hidden, the tr and td of the table are still visible and some css-styles are applied to them (border and padding).
Why are you using tables? Is there a reason for? When you dont´t have to use them, dont´use them :-)
Step 1: Add following content to the file .gitignore.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
_x000D_
Step 2: Make sure take effect
If the issue still exists, that's because settings in .gitignore can only ignore files that were originally not tracked. If some files have already been included in the version control system, then modifying .gitignore is invalid. To solve this issue completely, you need to open Git Bash or Package Manager Console (see screenshot below) to run following commands in the repository root folder.
git rm -r --cached .
git add .
git commit -m "Update .gitignore"
_x000D_
You've not shown how you're creating the string 2016-01-12T23:00:00.000Z
, but I assume via .format()
.
Anyway, .set()
is using your local time zone, but the Z
in the time string indicates zero time, otherwise known as UTC.
https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators
So I assume your local timezone is 23 hours from UTC?
saikumar's answer showed how to load the time in as UTC, but the other option is to use a .format()
call that outputs using your local timezone, rather than UTC.
http://momentjs.com/docs/#/get-set/
http://momentjs.com/docs/#/displaying/format/
PostgreSQL does not define round(double precision, integer)
. For reasons @Mike Sherrill 'Cat Recall' explains in the comments, the version of round that takes a precision is only available for numeric
.
regress=> SELECT round( float8 '3.1415927', 2 );
ERROR: function round(double precision, integer) does not exist
regress=> \df *round*
List of functions
Schema | Name | Result data type | Argument data types | Type
------------+--------+------------------+---------------------+--------
pg_catalog | dround | double precision | double precision | normal
pg_catalog | round | double precision | double precision | normal
pg_catalog | round | numeric | numeric | normal
pg_catalog | round | numeric | numeric, integer | normal
(4 rows)
regress=> SELECT round( CAST(float8 '3.1415927' as numeric), 2);
round
-------
3.14
(1 row)
(In the above, note that float8
is just a shorthand alias for double precision
. You can see that PostgreSQL is expanding it in the output).
You must cast the value to be rounded to numeric
to use the two-argument form of round
. Just append ::numeric
for the shorthand cast, like round(val::numeric,2)
.
If you're formatting for display to the user, don't use round
. Use to_char
(see: data type formatting functions in the manual), which lets you specify a format and gives you a text
result that isn't affected by whatever weirdness your client language might do with numeric
values. For example:
regress=> SELECT to_char(float8 '3.1415927', 'FM999999999.00');
to_char
---------------
3.14
(1 row)
to_char
will round numbers for you as part of formatting. The FM
prefix tells to_char
that you don't want any padding with leading spaces.
concat
also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe
df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column
review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame
# Gets rows in df where IDs match in the userID column and combines them
dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])
Simply use this for the so far latest version 4.1.0.
pip install opencv-contrib-python==4.1.0.25
For default version use this:
pip install opencv-contrib-python
The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.
Try this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})
FYI, [ChildActionOnly] is not available in ASP.NET MVC Core. see some info here
let plainString = "foo"
let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v
if let decodedData = Data(base64Encoded: base64String!),
let decodedString = String(data: decodedData, encoding: .utf8) {
print(decodedString) // foo
}
let plainString = "foo"
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v
let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo
NSString *plainString = @"foo";
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo
You Just Simply have to Follow these steps for making it easy...
You don't have to write new onClickListener
for Every Button
... Just Implement View.OnClickLister
to your Activity
/Fragment
.. it will implement new Method called onClick()
for handling onClick Events for Button
,TextView` etc.
- Implement
OnClickListener()
in yourActivity
/Fragment
public class MainActivity extends Activity implements View.OnClickListener {
}
- Implement onClick() method in your Activity/Fragment
public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onClick(View v) {
// default method for handling onClick Events..
}
}
- Implement
OnClickListener()
For Buttons
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Button one = (Button) findViewById(R.id.oneButton);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.twoButton);
two.setOnClickListener(this);
Button three = (Button) findViewById(R.id.threeButton);
three.setOnClickListener(this);
}
- Find Buttons By Id and Implement Your Code..
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;
default:
break;
}
}
Please refer to this link for more information :
https://androidacademic.blogspot.com/2016/12/multiple-buttons-onclicklistener-android.html (updated)
This will make easier to handle many buttons click events and makes it looks simple to manage it...
This should work.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: green;
}
#container {
width: inherit;
height: inherit;
margin: 0;
padding: 0;
background-color: pink;
}
h1 {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="container">
<h1>Hello World</h1>
</div>
</body>
</html>
The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.
The width: inherit; height: inherit;
pulls the width and height from the parent element. This should be the default and is not truly necessary.
Try removing the h1 { ... }
CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the h1
element is influencing the layout of its container. You could prevent this by declaring overflow: hidden;
on the container or the body.
I'd also suggest you do some reading on the CSS Box Model.
...\Program Files\Microsoft SQL Server\MSSQL 1.0\MSSQL\Backup
Found a solution. This problem happens, when you import a project.
The solution is simple
Now you should see the web app libraries showing your jars added.
The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as
pip3 install hide_code
Visit https://github.com/kirbs-/hide_code/ for more info about this extension.
If you are building a class and you want there to be a base value for the property, then use the virtual
keyword in the base class. This allows you to optionally override the property.
Using your example above:
//you may want to also use interfaces.
interface IFather
{
int MyInt { get; set; }
}
public class Father : IFather
{
//defaulting the value of this property to 1
private int myInt = 1;
public virtual int MyInt
{
get { return myInt; }
set { myInt = value; }
}
}
public class Son : Father
{
public override int MyInt
{
get {
//demonstrating that you can access base.properties
//this will return 1 from the base class
int baseInt = base.MyInt;
//add 1 and return new value
return baseInt + 1;
}
set
{
//sets the value of the property
base.MyInt = value;
}
}
}
In a program:
Son son = new Son();
//son.MyInt will equal 2
GIT uses colored output by default but on some system like as CentOS it is not enabled . You can enable it like this
git config --global color.ui true
git config --global color.ui false
git config --global color.ui auto
You can choose your required command from here .
Here --global is optional to apply action for every repository in your system . If you want to apply coloring for current repository only then you can do something like this -
git config color.ui true
If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:
adapter.Fill(ds);
ds.Tables(0).Rows.Add();
Put this in an initializer
class Hash
def filter(*args)
return nil if args.try(:empty?)
if args.size == 1
args[0] = args[0].to_s if args[0].is_a?(Symbol)
self.select {|key| key.to_s.match(args.first) }
else
self.select {|key| args.include?(key)}
end
end
end
Then you can do
{a: "1", b: "b", c: "c", d: "d"}.filter(:a, :b) # => {a: "1", b: "b"}
or
{a: "1", b: "b", c: "c", d: "d"}.filter(/^a/) # => {a: "1"}
Yes you can - first capture the event using onmouseover
, then set the class name using
Element.className
.
If you like to add or remove classes - use the more convenient Element.classList
method.
.active {
background: red;
}
_x000D_
<div onmouseover=className="active">
Hover this!
</div>
_x000D_
just use -
if(!a) // if a is negative,undefined,null,empty value then...
{
// do whatever
}
else {
// do whatever
}
this works because of the == difference from === in javascript, which converts some values to "equal" values in other types to check for equality, as opposed for === which simply checks if the values equal. so basically the == operator know to convert the "", null, undefined to a false value. which is exactly what you need.
There are two related error messages that may tell you something is wrong with declarations and/or imports.
The first is the one you are referring to, which can be generated by NOT putting an #import in your .m (or .pch file) while declaring an @class in your .h.
The second you might see, if you had a method in your States class like:
- (void)logout:(NSTimer *)timer
after adding the #import is this:
No visible @interface for "States" declares the selector 'logout:'
If you see this, you need to check and see if you declared your "logout" method (in this instance) in the .h file of the class you're importing or forwarding.
So in your case, you would need a:
- (void)logout:(NSTimer *)timer;
in your States class's .h to make one or both of these related errors disappear.
When doing recursive replacement, the path and filename need to be included:
Get-ChildItem -Recurse | ForEach { (Get-Content $_.PSPath |
ForEach {$ -creplace "old", "new"}) | Set-Content $_.PSPath }
This wil replace all "old" with "new" case-sensitive in all the files of your folders of your current directory.
It is working you have to check attr after assigning value
$('#amount').attr( 'datamin','1000');
alert($('#amount').attr( 'datamin'));?
There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:
$errors = array_filter($errors);
if (!empty($errors)) {
}
array_filter()
function's default behavior will remove all values from array which are equal to null
, 0
, ''
or false
.
Otherwise in your particular case empty()
construct will always return true
if there is at least one element even with "empty" value.
It wasn't working for me either. vbcrlf and Environment.Newline() both had no effect. My problem was that the Placeholder Properties had a Markup type of HTML. When I changed it to None, it worked like a champ!
I have same problem. I solved install this setup. (I use vs 2015 (4.6))
Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:
Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
Const DateCol = "A" 'column where dates are store
Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
Const FirstRow = 2 'first row where date data is stored
'Copy range of values to Dates array
Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
Dim i As Integer
For i = LBound(Dates) To UBound(Dates)
If IsDate(Dates(i, 1)) Then
If Month(CDate(Dates(i, 1))) = MonthNum Then
Dim CurrRow As Long
'get the current row number in the worksheet
CurrRow = FirstRow + i - 1
Dim DestRow As Long
'get the destination row
DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
'copy row CurrRow in FromSheet to row DestRow in ToSheet
FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
End If
End If
Next i
End Sub
Personally I don't like to use TempData, but I prefer to pass a strongly typed object as explained in Passing Information Between Controllers in ASP.Net-MVC.
You should always find a way to make it explicit and expected.
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
More of a comment than an answer...
I'm using Lombok and I was developing a (very) skeleton API and my response DTO didn't have any fields (yet) and I got the HttpMediaTypeNotAcceptableException
error while running my integration tests.
Adding a field to the response DTO fixed the issue.
I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
Now you should be able to sort by this column either Oldest to Newest or Newest to Oldest
I am not sure, what is the official documentation for markdown.
Cross-Reference can be written just in brackets [Heading]
, or with empty brackets [Heading][]
.
Both works using pandoc.
So I created a quick bash script, that will replace $__TOC__
in md file with its TOC. (You will need envsubst, that might not be part of your distro)
#!/bin/bash
filename=$1
__TOC__=$(grep "^##" $filename | sed -e 's/ /1. /;s/^##//;s/#/ /g;s/\. \(.*\)$/. [\1][]/')
export __TOC__
envsubst '$__TOC__' < $filename
If there is any single privilege that stands for ALL READ operations on database.
It depends on how you define "all read."
"Reading" from tables and views is the SELECT
privilege. If that's what you mean by "all read" then yes:
GRANT SELECT ON *.* TO 'username'@'host_or_wildcard' IDENTIFIED BY 'password';
However, it sounds like you mean an ability to "see" everything, to "look but not touch." So, here are the other kinds of reading that come to mind:
"Reading" the definition of views is the SHOW VIEW
privilege.
"Reading" the list of currently-executing queries by other users is the PROCESS
privilege.
"Reading" the current replication state is the REPLICATION CLIENT
privilege.
Note that any or all of these might expose more information than you intend to expose, depending on the nature of the user in question.
If that's the reading you want to do, you can combine any of those (or any other of the available privileges) in a single GRANT
statement.
GRANT SELECT, SHOW VIEW, PROCESS, REPLICATION CLIENT ON *.* TO ...
However, there is no single privilege that grants some subset of other privileges, which is what it sounds like you are asking.
If you are doing things manually and looking for an easier way to go about this without needing to remember the exact grant you typically make for a certain class of user, you can look up the statement to regenerate a comparable user's grants, and change it around to create a new user with similar privileges:
mysql> SHOW GRANTS FOR 'not_leet'@'localhost';
+------------------------------------------------------------------------------------------------------------------------------------+
| Grants for not_leet@localhost |
+------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, REPLICATION CLIENT ON *.* TO 'not_leet'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' |
+------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Changing 'not_leet' and 'localhost' to match the new user you want to add, along with the password, will result in a reusable GRANT
statement to create a new user.
Of, if you want a single operation to set up and grant the limited set of privileges to users, and perhaps remove any unmerited privileges, that can be done by creating a stored procedure that encapsulates everything that you want to do. Within the body of the procedure, you'd build the GRANT
statement with dynamic SQL and/or directly manipulate the grant tables themselves.
In this recent question on Database Administrators, the poster wanted the ability for an unprivileged user to modify other users, which of course is not something that can normally be done -- a user that can modify other users is, pretty much by definition, not an unprivileged user -- however -- stored procedures provided a good solution in that case, because they run with the security context of their DEFINER
user, allowing anybody with EXECUTE
privilege on the procedure to temporarily assume escalated privileges to allow them to do the specific things the procedure accomplishes.
If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:
SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)
I haven't executed it, so there may be a syntax error or two there.
For DevOps/build engineers, you can probably fix this running nuget restore
against the affected SLN, or project if you lack a SLN. I have to do this for our CI/CD builds for all our UWP projects.
call "%VS140COMNTOOLS%VsDevCmd.bat"
call "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\VsDevCmd.bat"
call nuget restore MyStuff.SLN
or call nuget restore MyStuff.csproj
if there's no SLN.Similar to other answers, the problem for me was declaring a many-to-one column to do lazy fetching. Switching to eager fetching fixed the problem. Before:
@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.LAZY)
After:
@ManyToOne(targetEntity = StatusCode.class, fetch = FetchType.EAGER)
The browsers have changed their privacy to autoplay video or audio due to Ads which is annoying. So you can just trick with below code.
You can put any silent audio in the iframe.
<iframe src="youraudiofile.mp3" type="audio/mp3" allow="autoplay" id="audio" style="display:none"></iframe>
<audio autoplay>
<source src="youraudiofile.mp3" type="audio/mp3">
</audio>
Just add an invisible iframe with an .mp3 as its source and allow="autoplay" before the audio element. As a result, the browser is tricked into starting any subsequent audio file. Or autoplay a video that isn’t muted.
For Windows 8 User : Open Command Prompt, type netstat -an | find "your port number" , enter .
If reply comes like LISTENING then the port is in use, else it is free .
Had the exact same problem and just could not find the right solution. Hope this helps somebody.
I have an .NET Core 3.1 WebApi with EF Core. Upon receiving multiple calls at the same time, the applications was trying to add and save changes to the database at the same time.
In my case the problem was that the table that the data would be saved in did not have a primary key set.
Somehow EF Core missed when the migration was ran from the application that the ID in the model was supposed to be a primary key.
I found the problem by opening the SQL Profiler and seeing that all transactions was successfully submitted to the database (from the application) but only one new row was created. The profiler also showed that some type of deadlock was happening but I couldn't see much more in the trace logs of the profiler. On further inspection I noticed that the primary key identifier was missing on the column "Id".
The exceptions I got from my application was:
This SqlTransaction has completed; it is no longer usable.
and/or
An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseSqlServer' call.
This builds on ntc2 and Chris Johnsen's answer. I am using this whenever I want to create a new session with a custom history-limit. I wanted a way to create sessions with limited scrollback without permanently changing my history-limit for future sessions.
tmux set-option -g history-limit 100 \; new-session -s mysessionname \; set-option -g history-limit 2000
This works whether or not there are existing sessions. After setting history-limit for the new session it resets it back to the default which for me is 2000.
I created an executable bash script that makes this a little more useful. The 1st parameter passed to the script sets the history-limit for the new session and the 2nd parameter sets its session name:
#!/bin/bash
tmux set-option -g history-limit "${1}" \; new-session -s "${2}" \; set-option -g history-limit 2000
Just simple modification of @silgon answer:
while true; do
inotifywait -r -e modify,create,delete /directory
rsync -avz /directory /target
done
(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)
Try the library SimpleDraweeView
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/badge_image"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
and now you can simply do:
final Uri uri = Uri.parse(post.getImageUrl());
To truncate a string provided by the maximum limit without breaking a word use this:
/**
* truncate a string provided by the maximum limit without breaking a word
* @param string $str
* @param integer $maxlen
* @return string
*/
public static function truncateStringWords($str, $maxlen): string
{
if (strlen($str) <= $maxlen) return $str;
$newstr = substr($str, 0, $maxlen);
if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));
return $newstr;
}
filenames = '000'.upto('100').map { |index| "file_#{index}" }
Outputs
[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]
Depending on how it will be used, you can either do this with two maps Map<K1, V>
and Map<K2, V>
or with two maps Map<K1, V>
and Map<K2, K1>
. If one of the keys is more permanent than the other, the second option may make more sense.
Currently it only works for the .dropdown-menu
:
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
If you want it for other use, in your own css, following the bootstrap.css create another one:
.divider {
height: 1px;
width:100%;
display:block; /* for use on default inline elements like span */
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :
{
"brand": "bwm",
"price": 30000
}
{
"brand": "benz",
"price": 50000
}
example array:
[
{
"brand": "bwm",
"price": 30000
},
{
"brand": "benz",
"price": 50000
}
]
In order to use JSON more beautifully, you can go here JSON Viewer do format
The rule is that the first week of a year is the week that contains the first Thursday of the year.
I personally use Zend_Date for this kind of calculation and to get the week for today is this simple. They have a lot of other useful functions if you work with dates.
$now = Zend_Date::now();
$week = $now->get(Zend_Date::WEEK);
// 10
If you are using storyboards you could set the navigation bar tint colour.
The currently added directory is already committed in the repository. So delete the directory in the repository and commit the same directory again.
For me put variable before calling did the trick:
OPENSSL_CONF=/usr/ssl/openssl.cnf openssl req -new -x509 -key privatekey.pem -out publickey.cer -days 365
fromDic.ToList().ForEach(x =>
{
if (toDic.ContainsKey(x.Key))
toDic.Remove(x.Key);
toDic.Add(x);
});
I whipped up a quick (Jquery only) plugin, that saves the value in a data field while an input is disabled. This just means as long as the field is being disabled programmaticly through jquery using .prop() or .attr()... then accessing the value by .val(), .serialize() or .serializeArra() will always return the value even if disabled :)
Shameless plug: https://github.com/Jezternz/jq-disabled-inputs
Here Style.xml is like
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="actionBarTheme">@style/MyTheme</item>
</style>
<style name="MyTheme" parent="@android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/AppTheme.ActionBarStyle</item>
</style>
<style name="AppTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:titleTextStyle">@style/AppTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="AppTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
<item name="android:textColor">@color/colorBlack</item>
</style>
You should add
<item name="actionBarTheme">@style/MyTheme</item>
in AppTheme
Changing git clone protocol to try.
for example, this error happened when "git clone https://xxxxxxxxxxxxxxx"
you can try with "git clone git://xxxxxxxxxxxxxx", maybe ok then.
If you want to delete lines 5 through 10 and 12:
sed -e '5,10d;12d' file
This will print the results to the screen. If you want to save the results to the same file:
sed -i.bak -e '5,10d;12d' file
This will back the file up to file.bak
, and delete the given lines.
Note: Line numbers start at 1. The first line of the file is 1, not 0.
The trick is to have an algorithm that only you know (such that it could be decoded at the other end).
There are simple things like, "Pick a prime number and add a magic number to it"
More convoluted options such as using asymmetric encryption of a set of binary data (that could include a unique identifier, version numbers, etc) and distribute the encrypted data as the key.
Might also be worth reading the responses to this question as well
from IPython.display import display
display(df) # OR
print df.to_html()
Use poll to get the first element, and add to add a new last element. That's it, no synchronization or anything else.
Try adding
html {
overflow-x: hidden;
}
as well as
body {
overflow-x: hidden;
}
Use the Figure.savefig()
method, like so:
ax = s.hist() # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')
It doesn't have to end in pdf
, there are many options. Check out the documentation.
Alternatively, you can use the pyplot
interface and just call the savefig
as a function to save the most recently created figure:
import matplotlib.pyplot as plt
s.hist()
plt.savefig('path/to/figure.pdf') # saves the current figure
If you want remove all local changes - including files that are untracked by git - from your working copy, simply stash them:
git stash push --include-untracked
If you don't need them anymore, you now can drop that stash:
git stash drop
If you don't want to stash changes that you already staged - e.g. with git add
- then add the option --keep-index
. Note however, that this will still prevent merging if those staged changes collide with the ones from upstream.
If you want to overwrite only specific parts of your local changes, there are two possibilities:
Commit everything you don't want to overwrite and use the method above for the rest.
Use git checkout path/to/file/to/revert
for the changes you wish to overwrite. Make sure that file is not staged via git reset HEAD path/to/file/to/revert
.
There are three obvious ways to communicate with services:
In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():
void onCreate(Intent i) {
sInstance = this;
}
Make a static function MyService getInstance()
, which returns the static sInstance
.
Then in Activity.onCreate()
you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread()
.
The last thing you need to do is to remove the reference to you listener object in Activity.onPause()
, otherwise an instance of your activity context will leak, not good.
NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.
<script>
function checkForPally() {
var input = document.getElementById("inputTable").value;
var input = input.replace(/\s/g, '');
var arrayInput = input.split();
var inputReversed = arrayInput.reverse();
var stringInputReversed = inputReversed.join("");
if (input == stringInputReversed) {
check.value = "The word you enter is a palindrome"
}
if (input != stringInputReversed) {
check.value = "The word you entered is not a palindrome"
}
}
</script>
You first use the getElement tag to set the initial variable of the palindrome. Seeing as a palindrome can be multiple words you use the regex entry to remove the whitespaces. You then use the split function to convert the string into an array.
Next up, you use the reverse method to reverse the array when this is done you join the reversed array back into a string. Lastly, you just use a very basic if statement to check for equality, if the reversed value is equall to the initial variable you have yourself a palindrome.
Default argument values are evaluated at function define-time, but self
is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.
It's a common pattern to default an argument to None
and add a test for that in code:
def p(self, b=None):
if b is None:
b = self.a
print b
With Eclipse Oxygen you can do the below things:
Maven will take them when installing the project.
Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it
There is no such thing as the "last" row in a table, as an Oracle table has no concept of order.
However, assuming that you wanted to find the last inserted primary key and that this primary key is an incrementing number, you could do something like this:
select *
from ( select a.*, max(pk) over () as max_pk
from my_table a
)
where pk = max_pk
If you have the date that each row was created this would become, if the column is named created
:
select *
from ( select a.*, max(created) over () as max_created
from my_table a
)
where created = max_created
Alternatively, you can use an aggregate query, for example:
select *
from my_table
where pk = ( select max(pk) from my_table )
Here's a little SQL Fiddle to demonstrate.
Singleton pattern
public class MyClass() {
private static MyClass instance = null;
/**
* Get instance of my class, Singleton
**/
public static MyClass getInstance() {
if(instance == null) {
instance = new MyClass();
}
return instance;
}
/**
* Private constructor
*/
private MyClass() {
//This will only be called once, by calling getInstanse() method.
}
}
In Python 3, here's a solution, which takes a command off the command line and delivers real-time nicely decoded strings as they are received.
Receiver (receiver.py
):
import subprocess
import sys
cmd = sys.argv[1:]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
print("received: {}".format(line.rstrip().decode("utf-8")))
Example simple program that could generate real-time output (dummy_out.py
):
import time
import sys
for i in range(5):
print("hello {}".format(i))
sys.stdout.flush()
time.sleep(1)
Output:
$python receiver.py python dummy_out.py
received: hello 0
received: hello 1
received: hello 2
received: hello 3
received: hello 4
You are running the [
(aka test
) command with the argument "false", not running the command false
. Since "false" is a non-empty string, the test
command always succeeds. To actually run the command, drop the [
command.
if false; then
echo "True"
else
echo "False"
fi
In Python 2.7 with iPython:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
As of 2018, from google help center (tested on Chrome 63) :
As mentioned in another answer, incognito tabs are also of great use for development.
It depends on your application and its use as to the level of security you need.
In terms of security, you should be validating all values you get from the querystring or post parameters, to ensure they're valid.
You may also wish to add logging for others, including analysis of weblogs so you can determine if an attempt to hack your system is occuring.
I don't believe it's possible to inject javascript into a URL and have this run, unless your application is using parameters without validating them first.
Query:
select ord_num, agent_code, ord_date, ord_amount
from orders
where (agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders
GROUP BY agent_code);
above query worked for me in mysql. refer following link -->
https://www.w3resource.com/sql/subqueries/multiplee-row-column-subqueries.php
As others have suggested, AirPlay mirroring is the way to go. To mirror directly to your computer use an AirPlay server like http://www.airserverapp.com/. Then, since it's showing up directly on your computer you can capture it using the built-in Quicktime app (File > New Screen Recording). Works great!
Simple but yet fast:
>>> def is_odd(a):
... return bool(a - ((a>>1)<<1))
...
>>> print(is_odd(13))
True
>>> print(is_odd(12))
False
>>>
Or even simpler:
>>> def is_odd(a):
... return bool(a & 1)
As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:
and
, or
and not
have much lower precedence than &&
, ||
and !
and
and or
have the same precedence, while &&
has higher precedence than ||
In general, it is good style to avoid the use of and
, or
and not
and use &&
, ||
and !
instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)
The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that
idiom, where do_this
returns false
or nil
if there is an error and only then is do_that
executed instead. (Analogous, there is also the do_this and then_do_that
idiom.)
Examples:
download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache
Sometimes, this can make control flow a little bit more fluent than using if
or unless
.
It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.
There is nothing to change. Pass only in the connect function {useNewUrlParser: true }
.
This will work:
MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
if(err) {
console.log(err);
}
else {
console.log('connected to ' + url);
db.close();
}
})
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
Object.entries do it in better way.
var dataObject = {"a":{"title":"shop"}, "b":{"title":"home"}}_x000D_
_x000D_
Object.entries(dataObject).map(itemArray => { _x000D_
console.log("key=", itemArray[0], "value=", itemArray[1])_x000D_
})
_x000D_
This is an old question, but its one I found while searching as well.
If you installed with brew
then the solution would actually be the this:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
The actual answer is "use mutation observers" (as outlined in this question: Determining if a HTML element has been added to the DOM dynamically), however support (specifically on IE) is limited (http://caniuse.com/mutationobserver).
So the actual ACTUAL answer is "Use mutation observers.... eventually. But go with Jose Faeti's answer for now" :)
It means you need to do either 1 of the below:
A solution to #2 when you are not able to get the certificate & .p12 file from the creator would be to just check the 'Automatically manage signing' option.
Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5
jQuery.parseXML( data )
Returns: XMLDocument
There are two ways to get variable from URL in PHP:
When your URL is: http://www.example.com/index.php?id=7
you can get this id
via $_GET['id']
or $_REQUEST['id']
command and store in $id
variable.
Lest's take a look:
// url is www.example.com?id=7
//get id from url via $_GET['id'] command:
$id = $_GET['id']
same will be:
//get id from url via $_REQUEST['id'] command:
$id = $_REQUEST['id']
the difference is that variables can be passed to file via URL or via POST method.
if variable is passed through url, then you can get it with $_GET['variable_name']
or $_REQUEST['variable_name']
but if variable is posted, then you need to you $_POST['variable_name']
or $_REQUEST['variable_name']
So as you see $_REQUEST['variable_name']
can be used in both ways.
P.S: Also remember - never do like this: $results = mysql_query("SELECT * FROM next WHERE id=$id");
it may cause MySQL Injection and your database can be hacked.
Try to use:
$results = mysql_query("SELECT * FROM next WHERE id='".mysql_real_escape_string($id)."'");
// check for the app if it exist in the phone it will lunch it otherwise, it will search for the app in google play app in the phone and to avoid any crash, if no google play app installed in the phone, it will search for the app in the google play store using the browser :
public void onLunchAnotherApp() {
final String appPackageName = getApplicationContext().getPackageName();
Intent intent = getPackageManager().getLaunchIntentForPackage(appPackageName);
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
onGoToAnotherInAppStore(intent, appPackageName);
}
}
public void onGoToAnotherInAppStore(Intent intent, String appPackageName) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + appPackageName));
startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName));
startActivity(intent);
}
}
If you are a GUI guy and just want to find it in PhpMyAdmin, than pick the table of your choice and head over the Operations
tab >> Table options
>> Storage Engine
.
You can even change it from there using the drop-down options list.
PS: This guide is based on version 4.8 of PhpMyAdmin. Can't guarantee the same path for very older versions.
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:
ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];
If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.
A CASE
statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND -- Added the "AND" here
CASE WHEN @day = 'Monday' THEN (Monday = 1) -- Removed "AND"
WHEN @day = 'Tuesday' THEN (Tuesday = 1) -- Removed "AND"
ELSE AND (Wednesday = 1)
END
I think the easiest way to do this is to use the Regular Expressions. This way you can get the same split count as you could using myVar.Split('x') but in a multiple character setting.
string myVar = "do this to count the number of words in my wording so that I can word it up!";
int count = Regex.Split(myVar, "word").Length;
What is the exact error you get? Is it like the following?
>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format: data=2008-08-12T12:20:30.656234Z fmt=%Y-%m-%dT%H:%M:%S.Z
If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.
Try this:
>>> def gt(dt_str):
dt, _, us= dt_str.partition(".")
dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
us= int(us.rstrip("Z"), 10)
return dt + datetime.timedelta(microseconds=us)
>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
All you need to do is to change the PATH variable to include the bin
directory of your PostgreSQL installation.
An explanation on how to change environment variables is here:
http://support.microsoft.com/kb/310519
http://www.computerhope.com/issues/ch000549.htm
To verify that the path is set correctly, you can use:
echo %PATH%
on the commandline.
It seems that cygstart/runas
does not properly handle "$@"
and thus commands that have arguments containing spaces (and perhaps other shell meta-characters -- I didn't check) will not work correctly.
I decided to just write a small sudo
script that works by writing a temporary script that does the parameters correctly.
#! /bin/bash
# If already admin, just run the command in-line.
# This works on my Win10 machine; dunno about others.
if id -G | grep -q ' 544 '; then
"$@"
exit $?
fi
# cygstart/runas doesn't handle arguments with spaces correctly so create
# a script that will do so properly.
tmpfile=$(mktemp /tmp/sudo.XXXXXX)
echo "#! /bin/bash" >>$tmpfile
echo "export PATH=\"$PATH\"" >>$tmpfile
echo "$1 \\" >>$tmpfile
shift
for arg in "$@"; do
qarg=`echo "$arg" | sed -e "s/'/'\\\\\''/g"`
echo " '$qarg' \\" >>$tmpfile
done
echo >>$tmpfile
# cygstart opens a new window which vanishes as soon as the command is complete.
# Give the user a chance to see the output.
echo "echo -ne '\n$0: press <enter> to close window... '" >>$tmpfile
echo "read enter" >>$tmpfile
# Clean up after ourselves.
echo "rm -f $tmpfile" >>$tmpfile
# Do it as Administrator.
cygstart --action=runas /bin/bash $tmpfile
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
Use window.open
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
For example, you can put this line of code in a click handler:
window.open('/file.txt', '_blank');
It will open a new tab (because of the '_blank' window-name) and that tab will open the URL.
Your server-side code should also have something like this:
res.set('Content-Disposition', 'attachment; filename=file.txt');
And that way, the browser should prompt the user to save the file to disk, instead of just showing them the file. It will also automatically close the tab that it just opened.
Solved
Model
public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}
Controller
public class BookController : Controller
{
[HttpPost]
public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
{
throw new NotImplementedException();
}
}
And View
@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.EditorFor(m => m)
<input type="file" name="fileUpload[0]" /><br />
<input type="file" name="fileUpload[1]" /><br />
<input type="file" name="fileUpload[2]" /><br />
<input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}
Note title of parameter from controller action must match with name of input elements
IEnumerable<HttpPostedFileBase> fileUpload
-> name="fileUpload[0]"
fileUpload
must match
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
Going further with eruciform's answer, you can chain your new
call into your init
method.
function Foo () {
this.bar = 'baz';
}
Foo.prototype.init_1 = function (bar) {
this.bar = bar;
return this;
};
Foo.prototype.init_2 = function (baz) {
this.bar = 'something to do with '+baz;
return this;
};
var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');
An Enumerator
shows you the items in a list or collection.
Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current
) or move to the next one (IEnumerator.MoveNext
). When you write a foreach
loop in C#, the compiler generates code that uses an Enumerator.
An Enumerable
is a class that can give you Enumerator
s. It has a method called GetEnumerator
which gives you an Enumerator
that looks at its items. When you write a foreach
loop in C#, the code that it generates calls GetEnumerator
to create the Enumerator
used by the loop.
You can use NSArray as
NSString *string1=@"This"
NSString *string2=@"is just"
NSString *string3=@"a test"
NSArray *myStrings = [[NSArray alloc] initWithObjects:string1, string2, string3,nil];
NSString *fullLengthString = [myStrings componentsJoinedByString:@" "];
or
you can use
NSString *imageFullName=[NSString stringWithFormat:@"%@ %@ %@.", string1,string2,string3];
select development team in both project and target rest all things set to automatic then it will work
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
As of C++11, the memory-safe way to do this (still using a similar construction) is with std::unique_ptr
:
std::unique_ptr<int[]> array(new int[n]);
This creates a smart pointer to a memory block large enough for n
integers that automatically deletes itself when it goes out of scope. This automatic clean-up is important because it avoids the scenario where your code quits early and never reaches your delete [] array;
statement.
Another (probably preferred) option would be to use std::vector
if you need an array capable of dynamic resizing. This is good when you need an unknown amount of space, but it has some disadvantages (non-constant time to add/delete an element). You could create an array and add elements to it with something like:
std::vector<int> array;
array.push_back(1); // adds 1 to end of array
array.push_back(2); // adds 2 to end of array
// array now contains elements [1, 2]
Within a ServiceWorker
or Worker
, replace window
with self
:
self[method_prefix + method_name](arg1, arg2);
Workers have no access to the DOM, therefore window
is an invalid reference. The equivalent global scope identifier for this purpose is self
.
You need to add type assertion .(string)
. It is necessary because the map is of type map[string]interface{}
:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
Here is a simple example similar to Sachin's. It's recommended to use a "using" statement on the unmanaged file resource:
// using System.IO;
string filepath = @"C:\test.txt";
using (StreamWriter writer = new StreamWriter(filepath))
{
writer.WriteLine("some text");
}
Check in Jenkins.xml and update like below
<arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=8090</arguments>
If you have the button object, called b: b.disabled=false;
If you want a quick demo how you check for empty divs I'd suggest you to try this link:
http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/
Below you have some short examples:
Using CSS
If your div is empty without anything even no white-space, you can use CSS:
.someDiv:empty {
display: none;
}
Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y
.someDiv:empty ~ .anotherDiv {
display: none;
}
Using jQuery
Checking text length of element with text() function
if ( $('#leftmenu').text().length == 0 ) {
// length of text is 0
}
Check if element has any children tags inside
if ( $('#leftmenu').children().length == 0 ) {
// div has no other tags inside it
}
Check for empty elements if they have white-space
if ( $.trim( $('.someDiv').text() ).length == 0 ) {
// white-space trimmed, div is empty
}
You can use inline styling to limit the height:
<img src="" class="img-responsive" alt="" style="max-height: 400px;">
<VirtualHost *:80>
DocumentRoot /var/www/app1
ServerName app1.example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/example
ServerName example.com
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/wildcard
ServerName other.example.com
ServerAlias *.example.com
</VirtualHost>
Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.
You can do float('nan')
to get NaN.
Try this:
String sMillis = "10997195233";
double dMillis = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int millis = 0;
String sTime;
try {
dMillis = Double.parseDouble(sMillis);
} catch (Exception e) {
System.out.println(e.getMessage());
}
seconds = (int)(dMillis / 1000) % 60;
millis = (int)(dMillis % 1000);
if (seconds > 0) {
minutes = (int)(dMillis / 1000 / 60) % 60;
if (minutes > 0) {
hours = (int)(dMillis / 1000 / 60 / 60) % 24;
if (hours > 0) {
days = (int)(dMillis / 1000 / 60 / 60 / 24);
if (days > 0) {
sTime = days + " days " + hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
} else {
sTime = hours + " hours " + minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = minutes + " min " + seconds + " sec " + millis + " millisec";
}
} else {
sTime = seconds + " sec " + millis + " millisec";
}
} else {
sTime = dMillis + " millisec";
}
System.out.println("time: " + sTime);
In general .Net collections do not support being enumerated and modified at the same time. If you try to modify the collection list during enumeration, it raises an exception. So the issue behind this error is, we can not modify the list/dictionary while we are looping through the same.
If we iterate a dictionary using a list of its keys, in parallel we can modify the dictionary object, as we are iterating through the key-collection and not the dictionary(and iterating its key collection).
//get key collection from dictionary into a list to loop through
List<int> keys = new List<int>(Dictionary.Keys);
// iterating key collection using a simple for-each loop
foreach (int key in keys)
{
// Now we can perform any modification with values of the dictionary.
Dictionary[key] = Dictionary[key] - 1;
}
Here is a blog post about this solution.
And for a deep dive in StackOverflow: Why this error occurs?
if [ $( ls <file> ) ]; then rm <file>; fi
Also, if you redirect your output with >
instead of >>
it will overwrite the previous file
I thought I'd extend the scope of this question a bit, with some useful tidbits on the matter.
In order to get the canvas as an image, you should do the following:
var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png");
You can use this to write the image to the page:
document.write('<img src="'+image+'"/>');
Where "image/png" is a mime type (png is the only one that must be supported). If you would like an array of the supported types you can do something along the lines of this:
var imageMimes = ['image/png', 'image/bmp', 'image/gif', 'image/jpeg', 'image/tiff']; //Extend as necessary
var acceptedMimes = new Array();
for(i = 0; i < imageMimes.length; i++) {
if(canvas.toDataURL(imageMimes[i]).search(imageMimes[i])>=0) {
acceptedMimes[acceptedMimes.length] = imageMimes[i];
}
}
You only need to run this once per page - it should never change through a page's lifecycle.
If you wish to make the user download the file as it is saved you can do the following:
var canvas = document.getElementById("mycanvas");
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); //Convert image to 'octet-stream' (Just a download, really)
window.location.href = image;
If you're using that with different mime types, be sure to change both instances of image/png, but not the image/octet-stream. It is also worth mentioning that if you use any cross-domain resources in rendering your canvas, you will encounter a security error when you try to use the toDataUrl method.
Vue.set(object, prop, value)
For vuex you will want to do Vue.set(state.object, key, value)
So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val)
in favor of this.$set(this.items, index, val)
.
Splice is still available and here is a link to array mutation methods available in vue link.
I encountered this error while executing
SELECT * FROM table;
I traced the error to cursor.py line 195.
if args is not None:
if isinstance(args, dict):
nargs = {}
for key, item in args.items():
if isinstance(key, unicode):
key = key.encode(db.encoding)
nargs[key] = db.literal(item)
args = nargs
else:
args = tuple(map(db.literal, args))
try:
query = query % args
except TypeError as m:
raise ProgrammingError(str(m))
Given that I am entering any extra parameters, I got rid of all of "if args ..." branch. Now it works.
num = [1, 2, 3] #List containing Integers
with open("ex3.txt", 'r+') as file:
readcontent = file.read() # store the read value of exe.txt into
# readcontent
file.seek(0, 0) #Takes the cursor to top line
for i in num: # writing content of list One by One.
file.write(str(i) + "\n") #convert int to str since write() deals
# with str
file.write(readcontent) #after content of string are written, I return
#back content that were in the file
The easiest is setting a program variable (see GDB: assignment):
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
Or you can just update arbitrary (writable) location by address:
(gdb) set {int}0x83040 = 4
There's more. Read the manual.
PostgreSQL knows the ALTER TABLE tblname DISABLE TRIGGER USER
command, which seems to do what I need. See ALTER TABLE.
@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:
SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
SELECT artist_id
FROM feeds_artists fa
WHERE fa.feed_id = f.id
LIMIT 1
)
WHERE f.id = '13815'
You can have a simple class which can be used for this kind of measurements.
class duration_printer {
public:
duration_printer() : __start(std::chrono::high_resolution_clock::now()) {}
~duration_printer() {
using namespace std::chrono;
high_resolution_clock::time_point end = high_resolution_clock::now();
duration<double> dur = duration_cast<duration<double>>(end - __start);
std::cout << dur.count() << " seconds" << std::endl;
}
private:
std::chrono::high_resolution_clock::time_point __start;
};
The only thing is needed to do is to create an object in your function at the beginning of that function
void veryLongExecutingFunction() {
duration_calculator dc;
for(int i = 0; i < 100000; ++i) std::cout << "Hello world" << std::endl;
}
int main() {
veryLongExecutingFunction();
return 0;
}
and that's it. The class can be modified to fit your requirements.
open $arduinoHome/arduino in text editor and modify last string:
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel processing.app.Base "$@"
to
java -Dswing.defaultlaf=com.sun.java.swing.plaf.gtk.GTKLookAndFeel -Dgnu.io.rxtx.SerialPorts="/dev/ttyACMN" processing.app.Base "$@"
(set property gnu.io.rxtx.SerialPorts to /dev/ttyACMN,where ttyACMN is name of serial port which you use)
it may temporary fix bug in rxtx library. helped me to upload sketch with arduino1.0.5 IDE.
Maybe would helpful for someone.
For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
I prefer using Symfony for this. Their libraries are pretty nice.
Use the The DomCrawler Component
Example:
$browser = new HttpBrowser(HttpClient::create());
$crawler = $browser->request('GET', 'example.com');
$class = $crawler->filter('.class')->first();
Here's a short, simple generic answer with a nice syntax for a named tuple with default arguments:
import collections
def dnamedtuple(typename, field_names, **defaults):
fields = sorted(field_names.split(), key=lambda x: x in defaults)
T = collections.namedtuple(typename, ' '.join(fields))
T.__new__.__defaults__ = tuple(defaults[field] for field in fields[-len(defaults):])
return T
Usage:
Test = dnamedtuple('Test', 'one two three', two=2)
Test(1, 3) # Test(one=1, three=3, two=2)
Minified:
def dnamedtuple(tp, fs, **df):
fs = sorted(fs.split(), key=df.__contains__)
T = collections.namedtuple(tp, ' '.join(fs))
T.__new__.__defaults__ = tuple(df[i] for i in fs[-len(df):])
return T
You can combine the find command and the ls command. Use the path (.) and selector (*) to narrow down the files you're after. Surround the find command in back quotes. The argument to -name is doublequote star doublequote in case you can't read it.
ls -lart `find . -type f -name "*" `