NSURL *url= [NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
In .Net Standard 2
you can format DateTime
like belows:
DateTime dt = DateTime.Now;
CultureInfo iv = CultureInfo.InvariantCulture;
// Default formats
// D - long date Tuesday, 24 April 2018
// d - short date 04/24/2018
// F - full date long Tuesday, 24 April 2018 06:30:00
// f - full date short Tuesday, 24 April 2018 06:30
// G - general long 04/24/2018 06:30:00
// g - general short 04/24/2018 06:30
// U - universal full Tuesday, 24 April 2018 06:30:00
// u - universal sortable 2018-04-24 06:30:00
// s - sortable 2018-04-24T06:30:00
// T - long time 06:30:00
// t - short time 06:30
// O - ISO 8601 2018-04-24T06:30:00.0000000
// R - RFC 1123 Tue, 24 Apr 2018 06:30:00 GMT
// M - month April 24
// Y - year month 2018 April
Console.WriteLine(dt.ToString("D", iv));
// Custom formats
// M/d/yy 4/8/18
// MM/dd/yyyy 04/08/2018
// yy-MM-dd 08-04-18
// yy-MMM-dd ddd 08-Apr-18 Sun
// yyyy-M-d dddd 2018-4-8 Sunday
// yyyy MMMM dd 2018 April 08
// h:mm:ss tt zzz 4:03:05 PM -03
// HH:m:s tt zzz 16:03:05 -03:00
// hh:mm:ss t z 04:03:05 P -03
// HH:mm:ss tt zz 16:03:05 PM -03
Console.WriteLine(dt.ToString("M/d/yy", iv));
"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value
{ * * "ProjectID" * * : {
"name": "ProjectID",
"value": "16,36,8,7",
"group": "Genel",
"editor": {
"type": "combobox",
"options": {
"url": "..\/jsonEntityVarServices\/?id=6&task=7",
"valueField": "value",
"textField": "text",
"multiple": "true"
}
},
"id": "14",
"entityVarID": "16",
"EVarMemID": "47"
}
}
If you want to check if any item in the list violates a condition use all
:
if all([x[2] == 0 for x in lista]):
# Will run if all elements in the list has x[2] = 0 (use not to invert if necessary)
To remove all elements not matching, use filter
# Will remove all elements where x[2] is 0
listb = filter(lambda x: x[2] != 0, listb)
The answers above all are static. I thought I would provide a dynamic answer. The two files that will need to be in sync are the relative foo.xml
with the layout and activity_bar.java
which corresponds to the Java class corresponding to this R.layout.foo
.
In foo.xml
set an id for the entire layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/foo" .../>
And in activity_bar.java
set the color in the onCreate()
:
public class activity_bar extends AppCompatActivty {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foo);
//Set an id to the layout
RelativeLayout currentLayout =
(RelativeLayout) findViewById(R.id.foo);
currentLayout.setBackgroundColor(Color.RED);
...
}
...
}
I hope this helps.
This might work:
git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit
Use Thread.Sleep
when you want to block the current thread.
Use Task.Delay
when you want a logical delay without blocking the current thread.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.
edit
I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.
VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
Node.js is a server side JS platform build on V8 which is chrome java-script runtime.
It leverages the use of java-script on servers too.
You can use JS Date() function or Date class.
Here's a quick solution:
NSString *text = self.contentTextView.text;
NSArray *items = @[text];
UIActivityViewController *activity = [[UIActivityViewController alloc]
initWithActivityItems:items
applicationActivities:nil];
activity.excludedActivityTypes = @[UIActivityTypePostToWeibo];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
//activity.popoverPresentationController.sourceView = shareButtonBarItem;
activity.popoverPresentationController.barButtonItem = shareButtonBarItem;
[self presentViewController:activity animated:YES completion:nil];
}
[self presentViewController:activity animated:YES completion:nil];
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
What is happening is that stock_list.toArray()
is creating an Object[]
rather than a String[]
and hence the typecast is failing1.
The correct code would be:
String [] stockArr = stockList.toArray(new String[stockList.size()]);
or even
String [] stockArr = stockList.toArray(new String[0]);
For more details, refer to the javadocs for the two overloads of List.toArray
.
The latter version uses the zero-length array to determine the type of the result array. (Surprisingly, it is faster to do this than to preallocate ... at least, for recent Java releases. See https://stackoverflow.com/a/4042464/139985 for details.)
From a technical perspective, the reason for this API behavior / design is that an implementation of the List<T>.toArray()
method has no information of what the <T>
is at runtime. All it knows is that the raw element type is Object
. By contrast, in the other case, the array parameter gives the base type of the array. (If the supplied array is big enough to hold the list elements, it is used. Otherwise a new array of the same type and a larger size is allocated and returned as the result.)
1 - In Java, an Object[]
is not assignment compatible with a String[]
. If it was, then you could do this:
Object[] objects = new Object[]{new Cat("fluffy")};
Dog[] dogs = (Dog[]) objects;
Dog d = dogs[0]; // Huh???
This is clearly nonsense, and that is why array types are not generally assignment compatible.
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
Check out yowsup
https://github.com/tgalal/yowsup
Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.
A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.
Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.
Reflector and the File Disassembler add-in from Denis Bauer. It actually produces source projects from assemblies, where Reflector on its own only displays the disassembled source.
ADDED: My latest favourite is JetBrains' dotPeek.
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
if (string.IsNullOrEmpty(str)) return null;
var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
return date;
}
A function inside of a function is commonly used for closures.
(There is a lot of contention over what exactly makes a closure a closure.)
Here's an example using the built-in sum()
. It defines start
once and uses it from then on:
def sum_partial(start):
def sum_start(iterable):
return sum(iterable, start)
return sum_start
In use:
>>> sum_with_1 = sum_partial(1)
>>> sum_with_3 = sum_partial(3)
>>>
>>> sum_with_1
<function sum_start at 0x7f3726e70b90>
>>> sum_with_3
<function sum_start at 0x7f3726e70c08>
>>> sum_with_1((1,2,3))
7
>>> sum_with_3((1,2,3))
9
Built-in python closure
functools.partial
is an example of a closure.
From the python docs, it's roughly equivalent to:
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
(Kudos to @user225312 below for the answer. I find this example easier to figure out, and hopefully will help answer @mango's comment.)
Since a lot of people still do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
//code
}
I guess a lot of people still don't know that you can do:
using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
//code
}
You're looking for the document.documentElement.scrollTop
property.
I had Filezilla 3.6, and had the same issue as OP. I have upgraded to 3.10.3 thinking it would fix it. Nope, still the same.
Then I did a bit digging around the options, and what worked for me is:
Edit -> Settings -> FTP -> Passive Mode and switched from "Fall back to active mode" to "Use the server's external IP address instead"
There is a library that will do all of this for you, check out mongoose-paginate-v2
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
I had similar issues when migrating to androidx. this issue comes due to the Old Butter Knife library dependency.
if you are using butter knife then you should use at least butter knife version 9.0.0-SNAPSHOT or above.
implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'
Hello in wich file i have to put this code for a french translation, i don't realy understand the process for the translation
$('#userList').DataTable({
"language": {
"sProcessing": "Traitement en cours ...",
"sLengthMenu": "Afficher _MENU_ lignes",
"sZeroRecords": "Aucun résultat trouvé",
"sEmptyTable": "Aucune donnée disponible",
"sInfo": "Lignes _START_ à _END_ sur _TOTAL_",
"sInfoEmpty": "Aucune ligne affichée",
"sInfoFiltered": "(Filtrer un maximum de_MAX_)",
"sInfoPostFix": "",
"sSearch": "Chercher:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Chargement...",
"oPaginate": {
"sFirst": "Premier", "sLast": "Dernier", "sNext": "Suivant", "sPrevious": "Précédent"
},
"oAria": {
"sSortAscending": ": Trier par ordre croissant", "sSortDescending": ": Trier par ordre décroissant"
}
}
});
From my research and starting on this post, i think this is the best option:
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p>
_x000D_
This option allow resizes of the page and even if the page is blank it will stick at the bottom.
You are using wrong formatting sequence for double
, you should use %lf
instead of %ld
:
double a;
scanf("%lf",&a);
Since Java 8 you can use the argument-less any
method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
In this case the parameter type of doStuff
will be the target type for any()
, and the return value type of any()
will get chosen to match that argument type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
This doesn't work with primitive types, unfortunately:
public interface IBar {
void doPrimitiveStuff(int i);
}
verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
The problem is that the compiler will infer Integer
as the return value type of any()
. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null
. The runtime will try to unbox the return value by calling the intValue
method on it before passing it to doStuff
, and the exception gets thrown.
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
Try this:
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:
npm cache clean
And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.
This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.
The way to fix this sort of problem is to redefine the relevant list environment. The enumitem
package is my favourite way to do this sort of thing; it has many options and parameters that can be varied, either for all lists or for each list individually.
Here's how to do (something like) what it is I think you want:
\usepackage{enumitem} \setlist{nolistsep}
or
\usepackage{enumitem} \setlist{nosep}
This does the job without any library. Used recursion and it is Indian style. -- Ravi.
def spellNumber(no):
# str(no) will result in 56.9 for 56.90 so we used the method which is given below.
strNo = "%.2f" %no
n = strNo.split(".")
rs = numberToText(int(n[0])).strip()
ps =""
if(len(n)>=2):
ps = numberToText(int(n[1])).strip()
rs = "" + ps+ " paise" if(rs.strip()=="") else (rs + " and " + ps+ " paise").strip()
return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))
def numberToText(no):
ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
text = ""
if len(str(no))<=2:
if(no<20):
text = ones[no]
else:
text = tens[no//10-1] +" " + ones[(no %10)]
elif len(str(no))==3:
text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
elif len(str(no))<=5:
text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
elif len(str(no))<=7:
text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
else:
text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
return text
Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.
Back in Management Studio attach the database again. In the attach window remove the log file from list of files.
The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.
You probably ought not use this for production databases.
You can also use the sqldf package in R.
Z <- sqldf('SELECT DISTINCT tablename.columnname FROM tablename ')
You can also Make use of the Following if you want to Cast and Round as well. That may help you or someone else.
SELECT CAST(ROUND(Column_Name, 2) AS DECIMAL(10,2), Name FROM Table_Name
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.standingsButton) {
startActivity(new Intent(MainActivity.this,StandingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
Try this:
> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
Code Value
1 A 1
2 B 2
1.1 A 1
1.2 A 1
I don't fully understand but, can use pandas
for getting times in right format:
>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>>
And:
>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']
But it's storing strings but easy to convert:
>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
Expanding on zoul's answer:
If you want to setup Vim to use specific settings when editing a particular filetype, you'll want to use autocommands:
autocmd Filetype css setlocal tabstop=4
This will make it so that tabs are displayed as 4 spaces. Setting expandtab
will cause Vim to actually insert spaces (the number of them being controlled by tabstop
) when you press tab; you might want to use softtabstop
to make backspace work properly (that is, reduce indentation when that's what would happen should tabs be used, rather than always delete one char at a time).
To make a fully educated decision as to how to set things up, you'll need to read Vim docs on tabstop
, shiftwidth
, softtabstop
and expandtab
. The most interesting bit is found under expandtab
(:help 'expandtab
):
There are four main ways to use tabs in Vim:
Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.
Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' is changed.
I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.
I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.
I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.
If need to run ant in eclipse with inbuilt eclipse jdk add the below line in build.xml
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.
Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:
This happened to me when my SourceTree application crashed during staging. And on the command line, it seemed like the previous git add
had been corrupted. If this is the case, try:
git init
git add -A
git commit -m 'Fix bad repo'
git push
On the last command, you might need to set the branch.
git push --all origin master
Bear in mind that this is enough if you haven't done any branching or any of that sort. In that case, make sure you push to the correct branch like git push origin develop
.
There is an excellent answer provided by @Adem Öztas, for use with httplib
and urllib2
. For requests
, if the question is strictly about resource existence, then the answer can be improved upon in the case of large resource existence.
The previous answer for requests
suggested something like the following:
def uri_exists_get(uri: str) -> bool:
try:
response = requests.get(uri)
try:
response.raise_for_status()
return True
except requests.exceptions.HTTPError:
return False
except requests.exceptions.ConnectionError:
return False
requests.get
attempts to pull the entire resource at once, so for large media files, the above snippet would attempt to pull the entire media into memory. To solve this, we can stream the response.
def uri_exists_stream(uri: str) -> bool:
try:
with requests.get(uri, stream=True) as response:
try:
response.raise_for_status()
return True
except requests.exceptions.HTTPError:
return False
except requests.exceptions.ConnectionError:
return False
I ran the above snippets with timers attached against two web resources:
1) http://bbb3d.renderfarming.net/download.html, a very light html page
2) http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4, a decently sized video file
Timing results below:
uri_exists_get("http://bbb3d.renderfarming.net/download.html")
# Completed in: 0:00:00.611239
uri_exists_stream("http://bbb3d.renderfarming.net/download.html")
# Completed in: 0:00:00.000007
uri_exists_get("http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4")
# Completed in: 0:01:12.813224
uri_exists_stream("http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4")
# Completed in: 0:00:00.000007
As a last note: this function also works in the case that the resource host doesn't exist. For example "http://abcdefghblahblah.com/test.mp4"
will return False
.
There is a far easier solution (IMO) in Bootstrap 3 that does not require you to compile any custom LESS. You just have to leverage the cascade in "Cascading Style Sheets."
Set up your CSS loading like so...
<link type="text/css" rel="stylesheet" href="/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/css/custom.css" />
Where /css/custom.css
is your unique style definitions. Inside that file, add the following definition...
@media (min-width: 1200px) {
.container {
width: 970px;
}
}
This will override Bootstrap's default width: 1170px
setting when the viewport is 1200px or bigger.
Tested in Bootstrap 3.0.2
The jQuery method .data()
updates an internal object managed by jQuery through the use of the method, if I'm correct.
If you'd like to update your data-attributes
with some spread, use --
$('body').attr({ 'data-test': 'text' });
-- otherwise, $('body').attr('data-test', 'text');
will work just fine.
Another way you could accomplish this is using --
$.extend( $('body')[0].dataset, { datum: true } );
-- which restricts any attribute change to HTMLElement.prototype.dataset
, not any additional HTMLElement.prototype.attributes
.
As Andrie said, system.time()
works fine. For short function I prefer to put replicate()
in it:
system.time( replicate(10000, myfunction(with,arguments) ) )
Facing similar concern, I found the following tool with a trivial Google search :
JPSoft's "Take Command" includes a batch file IDE/debugger. Their short presentation video demonstrates it nicely.
I'm using the trial version since a few hours. Here is my first humble opinion:
It deverves a try.
If you're trying to write a newline to a file, you could simply use BufferedWriter's newLine() method.
Easiest way to do it with javax.xml.bind.DatatypeConverter
:
String hex = "75546f7272656e745c436f6d706c657465645c6e667375635f6f73745f62795f6d757374616e675c50656e64756c756d2d392c303030204d696c65732e6d7033006d7033006d7033004472756d202620426173730050656e64756c756d00496e2053696c69636f00496e2053696c69636f2a3b2a0050656e64756c756d0050656e64756c756d496e2053696c69636f303038004472756d2026204261737350656e64756c756d496e2053696c69636f30303800392c303030204d696c6573203c4d757374616e673e50656e64756c756d496e2053696c69636f3030380050656e64756c756d50656e64756c756d496e2053696c69636f303038004d50330000";
byte[] s = DatatypeConverter.parseHexBinary(hex);
System.out.println(new String(s));
Both works fine. But according to the Apache docs you should avoid using mod_rewrite
for simple redirections, and use Redirect
instead. So according to them, you should preferably do:
<VirtualHost *:80>
ServerName www.example.com
Redirect / https://www.example.com/
</VirtualHost>
<VirtualHost *:443>
ServerName www.example.com
# ... SSL configuration goes here
</VirtualHost>
The first /
after Redirect
is the url, the second part is where it should be redirected.
You can also use it to redirect URLs to a subdomain:
Redirect /one/ http://one.example.com/
use...
# chmod 400 ec2-keypair.pem
don't use the 600 permission otherwise you might overwrite your key accidently.
The best, non-VBA, way to do this is using the TEXT formula. It takes a string as an argument and converts it to a value.
For example, =TEXT ("0.4*A1",'##') will return the value of 0.4 * the value that's in cell A1 of that worksheet.
If you need to clear the NuGet cache for your build server/agent you can find the cache for NuGet packages here:
%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache
Example:
C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.select(cb.count(cq.from(MyEntity.class)));
return em.createQuery(cq).getSingleResult();
Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.
var test = {};
test[2300] = 'some string';
console.log(test);
Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists()
function called.
<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
echo "This is Button1 that is selected";
}
function button2() {
echo "This is Button2 that is selected";
}
?>
<form method="post">
<input type="submit" name="button1" class="button" value="Button1" />
<input type="submit" name="button2" class="button" value="Button2" />
</form>
source: geeksforgeeks.org
You don't need MockRestServiceServer
object. The annotation is @InjectMocks
not @Inject
. Below is an example code that should work
@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private SomeService underTest;
@Test
public void testGetObjectAList() {
ObjectA myobjectA = new ObjectA();
//define the entity you want the exchange to return
ResponseEntity<List<ObjectA>> myEntity = new ResponseEntity<List<ObjectA>>(HttpStatus.ACCEPTED);
Mockito.when(restTemplate.exchange(
Matchers.eq("/objects/get-objectA"),
Matchers.eq(HttpMethod.POST),
Matchers.<HttpEntity<List<ObjectA>>>any(),
Matchers.<ParameterizedTypeReference<List<ObjectA>>>any())
).thenReturn(myEntity);
List<ObjectA> res = underTest.getListofObjectsA();
Assert.assertEquals(myobjectA, res.get(0));
}
I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.
cmd /k mybatchfile.cmd
if you want the command window to stay (on desktop) after batch script have finished.Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
brew install gradle
gradle-6.0.1-all.zip
) and added gradle path
into environment variable PATH
~/.bashrc
or ~/.zshrc
etc.):export GRADLE_HOME=/path_to_your_gradle/gradle-6.0.1
export PATH=$GRADLE_HOME/bin:$PATH
PATH
take effect immediately?A: use source
:
source ~/.bashrc
it will make/execute your .bashrc
, so make PATH
become your expected latest values, which include your added gradle path.
PATH
is really take effect/working now?A: use echo
to see your added path in indeed in your PATH
? ~ echo $PATH
xxx:/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin:xxx
you can see we added /Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin
into your PATH
gradle
is installed correctly on my Mac ?A: use which
to make sure can find gradle
? ~ which gradle
/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin/gradle
AND to check and see gradle version
? ~ gradle --version
------------------------------------------------------------
Gradle 6.0.1
------------------------------------------------------------
Build time: 2019-11-18 20:25:01 UTC
Revision: fad121066a68c4701acd362daf4287a7c309a0f5
Kotlin: 1.3.50
Groovy: 2.5.8
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM: 1.8.0_112 (Oracle Corporation 25.112-b16)
OS: Mac OS X 10.14.6 x86_64
this means the (latest) gradle is correctly installed on your mac ^_^.
for more detail please refer my (Chinese) post ?????mac???maven
I had the same problem. Try this.
<nav>
<ul>
<li><a href="#">AnaSayfa</a></li>
<li><a href="#">Hakkimizda</a></li>
<li><a href="#">Iletisim</a></li>
</ul>
</nav>
@charset "utf-8";
nav {
background-color: #9900CC;
height: 80px;
width: 400px;
}
ul {
list-style: none;
float: right;
margin: 0;
}
li {
float: left;
width: 100px;
line-height: 80px;
vertical-align: middle;
text-align: center;
margin: 0;
}
nav li a {
width: 100px;
text-decoration: none;
color: #FFFFFF;
}
Should be easier than that. Just use:
<Checkbox IsChecked="{Binding Path=myVar, UpdateSourceTrigger=PropertyChanged}" />
The problem is that passing an undefined variable to a function causes an error.
This means you have to run typeof before passing it as an argument.
The cleanest way I found to do this is like so:
function isset(v){
if(v === 'undefined'){
return false;
}
return true;
}
Usage:
if(isset(typeof(varname))){
alert('is set');
} else {
alert('not set');
}
Now the code is much more compact and readable.
This will still give an error if you try to call a variable from a non instantiated variable like:
isset(typeof(undefVar.subkey))
thus before trying to run this you need to make sure the object is defined:
undefVar = isset(typeof(undefVar))?undefVar:{};
Starting with Vue2, the triple braces were deprecated, you are to use v-html
.
<div v-html="task.html_content"> </div>
It is unclear from the documentation link as to what we are supposed to place inside v-html
, your variables goes inside v-html
.
Also, v-html
works only with <div>
or <span>
but not with <template>
.
If you want to see this live in an app, click here.
Please make sure that id datatype is Long instead of String, if that will be string then @GeneratedValue annotation will not work and the sql generating for
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
that needs to be
create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
The way I do this is to hold Alt then press Space, then E and finally P.
On Windows Alt jumps to the window menu, Space opens it, E selects Edit and P executes the Paste command.
Get these correct in succession and you can paste a snippet in under 2 seconds.
if you use the preset for react-native it accepts the import
npm i babel-preset-react-native --save-dev
and put it inside your .babelrc file
{
"presets": ["react-native"]
}
in your project root directory
In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link
I just did this (Shadi's first answer) and it works a treat:
public ActionResult Create()
{
Article article = new Article();
article.Active = true;
article.DatePublished = DateTime.Now;
ViewData.Model = article;
return View();
}
I could put the default values in my model like a propper MVC addict: (I'm using Entity Framework)
public partial class Article
{
public Article()
{
Active = true;
DatePublished = Datetime.Now;
}
}
public ActionResult Create()
{
Article article = new Article();
ViewData.Model = article;
return View();
}
Can anyone see any downsides to this?
This C# method will check for even and odd length palindrome string (Recursive Approach):
public static bool IsPalindromeResursive(int rightIndex, int leftIndex, char[] inputString)
{
if (rightIndex == leftIndex || rightIndex < leftIndex)
return true;
if (inputString[rightIndex] == inputString[leftIndex])
return IsPalindromeResursive(--rightIndex, ++leftIndex, inputString);
else
return false;
}
Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset
int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();
timezoneId is the id of the user's timezone (such as EST).
%RANDOM%
gives you a random number between 0 and 32767.
Using an expression like SET /A test=%RANDOM% * 100 / 32768 + 1
, you can change the range to anything you like (here the range is [1…100] instead of [0…32767]).
lsof -n -i | awk '{ print $1,$9; }' | sort -u
This displays who's doing what. Remove -n to see hostnames (a bit slower).
Also be careful how you execute the js on the page. For example if you do something like this:
(function(window, document, undefined){
var foo = document.getElementById("foo");
console.log(foo);
})(window, document, undefined);
This will return null because you'd be calling the document before it was loaded.
Better option..
(function(window, document, undefined){
// code that should be taken care of right away
window.onload = init;
function init(){
// the code to be called when the dom has loaded
// #document has its nodes
}
})(window, document, undefined);
You can also get that error in VB if the function you're calling starts with Public Shared Function rather than Public Function in the webservice. (As might happen if you move or copy the function out of a class). Just another thing to watch for.
declare
x number;
begin
x := myfunc(myargs);
end;
Alternatively:
select myfunc(myargs) from dual;
Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.
This question mentions a few options.
If you are using angular
and ie 9, 10
or edge
use :
myModule.config(['$httpProvider', function($httpProvider) {
//initialize get if not there
if (!$httpProvider.defaults.headers.get) {
$httpProvider.defaults.headers.get = {};
}
// Answer edited to include suggestions from comments
// because previous version of code introduced browser-related errors
//disable IE ajax request caching
$httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
// extra
$httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
$httpProvider.defaults.headers.get['Pragma'] = 'no-cache';
}]);
To completely disable cache
.
I have changed the java installation path from c:\Program Files (x86)\java
to another folder like c:\java\jdk1.7
and updated the %Java_HOME%
and path values accordingly,it worked.
example
%JAVA_HOME% = C:\java\JDK1.7
path-C:\java\JDK1.7\bin;
I ran into this issue with custom types in stored procedures, and solved it with the script below. I didn't fully understand the scripts above, and I follow the rule of "if you don't know what it does, don't do it".
In a nutshell, I rename the old type, and create a new one with the original type name. Then, I tell SQL Server to refresh its details about each stored procedure using the custom type. You have to do this, as everything is still "compiled" with reference to the old type, even with the rename. In this case, the type I needed to change was "PrizeType". I hope this helps. I'm looking for feedback, too, so I learn :)
Note that you may need to go to Programmability > Types > [Appropriate User Type] and delete the object. I found that DROP TYPE doesn't appear to always drop the type even after using the statement.
/* Rename the UDDT you want to replace to another name */
exec sp_rename 'PrizeType', 'PrizeTypeOld', 'USERDATATYPE';
/* Add the updated UDDT with the new definition */
CREATE TYPE [dbo].[PrizeType] AS TABLE(
[Type] [nvarchar](50) NOT NULL,
[Description] [nvarchar](max) NOT NULL,
[ImageUrl] [varchar](max) NULL
);
/* We need to force stored procedures to refresh with the new type... let's take care of that. */
/* Get a cursor over a list of all the stored procedures that may use this and refresh them */
declare sprocs cursor
local static read_only forward_only
for
select specific_name from information_schema.routines where routine_type = 'PROCEDURE'
declare @sprocName varchar(max)
open sprocs
fetch next from sprocs into @sprocName
while @@fetch_status = 0
begin
print 'Updating ' + @sprocName;
exec sp_refreshsqlmodule @sprocName
fetch next from sprocs into @sprocName
end
close sprocs
deallocate sprocs
/* Drop the old type, now that everything's been re-assigned; must do this last */
drop type PrizeTypeOld;
As answered by others, you will probably be happy with Apache Dbcp or c3p0. Both are popular, and work fine.
Regarding your doubt
Doesn't javax.sql or java.sql have pooled connection implementations? Why wouldn't it be best to use these?
They don't provide implementations, rather interfaces and some support classes, only revelant to the programmers that implement third party libraries (pools or drivers). Normally you don't even look at that. Your code should deal with the connections from your pool just as they were "plain" connections, in a transparent way.
Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.
function create-console-spanner() {
# 1: left-side-text, 2: right-side-text
local spanner="";
eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
printf "%s %s %s" "$1" "$spanner" "$2";
}
Example: create-console-spanner "loading graphics module" "[success]"
Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.
# Author: Triston J. Taylor <[email protected]>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite
declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);
declare -i PAINT_ACTIVE=1;
function paint-replace() {
local contents=$(cat)
echo "${contents//$1/$2}"
}
source <(cat <<EOF
function paint-activate() {
echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)
source <(cat <<EOF
function paint-deactivate(){
echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;
}
EOF
)
function paint-get-spanner() {
(( $# == 0 )) && set -- - 0;
declare -i l=$(( `tput cols` - ${2}))
eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}
function paint-span() {
local left_format=$1 right_format=$3
local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
paint-format "$left_format";
paint-get-spanner "$2" $(( left_length + right_length));
paint-format "$right_format";
}
function paint-format() {
local VAR="" OPTIONS='';
local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
done;
OPTIONS+=" --"
local format="$1"; shift;
if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
format=$(paint-activate "$format&none;")
else
format=$(paint-deactivate "$format")
fi
printf $OPTIONS "${format}" "$@";
(( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}
function paint-show-pallette() {
local -i PAINT_ACTIVE=1
paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
paint-format " Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}
To print a color, that's simple enough: paint-format "&red;This is %s\n" red
And you might want to get bold later on: paint-format "&bold;%s!\n" WOW
The -l
option to the paint-format
function measures the text so you can do console font metrics operations.
The -v
option to the paint-format
function works the same as printf
but cannot be supplied with -l
Now for the spanning!
paint-span "hello " . " &blue;world"
[note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]
and the output of that is:
hello ............................. world
Put
finish();
immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add
onCreate(){
getActionBar().setDisplayHomeAsUpEnabled(false);
...
}
to the activity you are starting.
In my case:
PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.synchronous = NO;
Was trying to do this with dispatch_group
As Greg Hewgill said, the typedef means you no longer have to write struct
all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef
, is the case I guess.
Also note that while your example (and mine) omitted naming the struct
itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
typedef struct Point Point;
Point * point_new(int x, int y);
and then provide the struct
definition in the implementation file:
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.
UPDATE Note that there are also highly-regarded C projects where this use of typedef
to hide struct
is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
If you are using microsoft query, you can add "?" to your query...
select name from user where id= ?
that will popup a small window asking for the cell/data/etc when you go back to excel.
In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.
You can disable port 80 and 443 as alternative incoming connections in Skype settings - Advanced settings - Connection.
(source: ctrlv.in)
CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.
Initializing a Session
To initialize the Session class manually in our controller constructor use following code.
Adding Custom Session Data
We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.
$this->session->set_userdata($newarray);
Where $newarray is an associative array containing our new data.
$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray);
Retrieving Session
$session_id = $this->session->userdata('session_id');
Above function returns FALSE (boolean) if the session array does not exist.
Retrieving All Session Data
$this->session->all_userdata()
I have taken reference from http://www.tutsway.com/codeigniter-session.php.
If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">
You can also filter on multiple properties of an object just by adding them to your filter object:
<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">
This was a major pain to get working. I hit a bunch of dead ends, but the final result is reasonably straight forward. Hopefully it can be of benefit to someone. It may need a little spit and polish that's all.
Note: _addressFinder.CompleteAsync returns a list of KeyValuePairs.
public partial class MyForm : Form
{
private readonly AddressFinder _addressFinder;
private readonly AddressSuggestionsUpdatedEventHandler _addressSuggestionsUpdated;
private delegate void AddressSuggestionsUpdatedEventHandler(object sender, AddressSuggestionsUpdatedEventArgs e);
public MyForm()
{
InitializeComponent();
_addressFinder = new AddressFinder(new AddressFinderConfigurationProvider());
_addressSuggestionsUpdated += AddressSuggestions_Updated;
MyComboBox.DropDownStyle = ComboBoxStyle.DropDown;
MyComboBox.DisplayMember = "Value";
MyComboBox.ValueMember = "Key";
}
private void MyComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsControl(e.KeyChar))
{
return;
}
var searchString = ThreadingHelpers.GetText(MyComboBox);
if (searchString.Length > 1)
{
Task.Run(() => GetAddressSuggestions(searchString));
}
}
private async Task GetAddressSuggestions(string searchString)
{
var addressSuggestions = await _addressFinder.CompleteAsync(searchString).ConfigureAwait(false);
if (_addressSuggestionsUpdated.IsNotNull())
{
_addressSuggestionsUpdated.Invoke(this, new AddressSuggestionsUpdatedEventArgs(addressSuggestions));
}
}
private void AddressSuggestions_Updated(object sender, AddressSuggestionsUpdatedEventArgs eventArgs)
{
try
{
ThreadingHelpers.BeginUpdate(MyComboBox);
var text = ThreadingHelpers.GetText(MyComboBox);
ThreadingHelpers.ClearItems(MyComboBox);
foreach (var addressSuggestions in eventArgs.AddressSuggestions)
{
ThreadingHelpers.AddItem(MyComboBox, addressSuggestions);
}
ThreadingHelpers.SetDroppedDown(MyComboBox, true);
ThreadingHelpers.ClearSelection(MyComboBox);
ThreadingHelpers.SetText(MyComboBox, text);
ThreadingHelpers.SetSelectionStart(MyComboBox, text.Length);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
ThreadingHelpers.EndUpdate(MyComboBox);
}
}
private class AddressSuggestionsUpdatedEventArgs : EventArgs
{
public IList<KeyValuePair<string, string>> AddressSuggestions { get; private set; }
public AddressSuggestionsUpdatedEventArgs(IList<KeyValuePair<string, string>> addressSuggestions)
{
AddressSuggestions = addressSuggestions;
}
}
}
ThreadingHelpers is just a set of static methods of the form:
public static string GetText(ComboBox comboBox)
{
if (comboBox.InvokeRequired)
{
return (string)comboBox.Invoke(new Func<string>(() => GetText(comboBox)));
}
lock (comboBox)
{
return comboBox.Text;
}
}
public static void SetText(ComboBox comboBox, string text)
{
if (comboBox.InvokeRequired)
{
comboBox.Invoke(new Action(() => SetText(comboBox, text)));
return;
}
lock (comboBox)
{
comboBox.Text = text;
}
}
This worked perfectly for me:
$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
In Angular 2, change detection is automatic... $scope.$watch()
and $scope.$digest()
R.I.P.
Unfortunately, the Change Detection section of the dev guide is not written yet (there is a placeholder near the bottom of the Architecture Overview page, in section "The Other Stuff").
Here's my understanding of how change detection works:
setTimeout()
inside our components rather than something like $timeout
... because setTimeout()
is monkey patched.ChangeDetectorRef
.) These change detectors are created when Angular creates components. They keep track of the state of all of your bindings, for dirty checking. These are, in a sense, similar to the automatic $watches()
that Angular 1 would set up for {{}}
template bindings.onPush
change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
ngOnChanges()
to be notified of changes. ngDoCheck()
(see this SO answer for more on this). Other references to learn more:
onPush
.This can also be a issue when you enter wrong password for your sign key.
Remove ~
character in location
so
path="~/Admin/SomePage.aspx"
becomes
path="Admin/SomePage.aspx"
In addition to 200 and 204, 205 (Reset Content) could be a valid response.
The server has fulfilled the request and the user agent SHOULD reset the document view which caused the request to be sent ... [e.g.] clearing of the form in which the input is given.
If you want to check contents are equal or not then just use JSON.stringify(obj)
Eg - var a ={key:val};
var b ={key:val};
JSON.stringify(a) == JSON.stringify(b) -----> If contents are same you gets true.
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
Firefox 44 includes a built-in JSON viewer (no add-ons required). The feature is turned off by default, so turn on devtools.jsonview.enabled
:
How can you disable the new JSON Viewer/Reader in Firefox Developer Edition?
Here is a work around but not always a great one, depending on how much you scale it. Explanation can be found here: https://www.geekgoddess.com/how-to-resize-the-google-nocaptcha-recaptcha/
.g-recaptcha {
transform:scale(0.77);
transform-origin:0 0;
}
UPDATE: Google has added support for a smaller size via a parameter. Have a look at the docs - https://developers.google.com/recaptcha/docs/display#render_param
I ran into an article that illustrates a method where the data from the same excel sheet can be imported in the selected table until there is no modifications in excel with data types.
If the data is inserted or overwritten with new ones, importing process will be successfully accomplished, and the data will be added to the table in SQL database.
The article may be found here: http://www.sqlshack.com/using-ssis-packages-import-ms-excel-data-database/
Hope it helps.
Enums in C++ are like integers masked by the names you give them, when you declare your enum-values (this is not a definition only a hint how it works).
But there are two errors in your code:
enum
all lower caseDays.
before Saturday.if (day == YourClass::Saturday){}
I tried changing the repository list with:
http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe
But none of them seem to work, but I finally found a repository that works running the following command
add-apt-repository ppa:ondrej/php
And then updating and installing normally the package using apt-get
As you can see it's installed at last.
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Make it a background image that is centered.
.wrapper {background:transparent url(yourimage.jpg) no-repeat center center;}
<div class="wrapper">
...input boxes and labels and submit button here
</div>
Try this:
{[0-9]{1,3}:[0-9]{1,3}}
The {1,3}
means "match between 1 and 3 of the preceding characters".
I faced the same issue. To get rid of this issue, I followed the below steps and it worked for me.
What Django actually says is:
Userprofile table has data in it and there might be
new_field
values which are null, but I do not know, so are you sure you want to mark property as non nullable, because if you do you might get an error if there are values with NULL
If you are sure that none of values in the userprofile
table are NULL - fell free and ignore the warning.
The best practice in such cases would be to create a RunPython migration to handle empty values as it states in option 2
2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
In RunPython migration you have to find all UserProfile
instances with empty new_field
value and put a correct value there (or a default value as Django asks you to set in the model).
You will get something like this:
# please keep in mind that new_value can be an empty string. You decide whether it is a correct value.
for profile in UserProfile.objects.filter(new_value__isnull=True).iterator():
profile.new_value = calculate_value(profile)
profile.save() # better to use batch save
Have fun!
PROPAGATION_REQUIRED = 0; If DataSourceTransactionObject T1 is already started for Method M1. If for another Method M2 Transaction object is required, no new Transaction object is created. Same object T1 is used for M2.
PROPAGATION_MANDATORY = 2; method must run within a transaction. If no existing transaction is in progress, an exception will be thrown.
PROPAGATION_REQUIRES_NEW = 3; If DataSourceTransactionObject T1 is already started for Method M1 and it is in progress (executing method M1). If another method M2 start executing then T1 is suspended for the duration of method M2 with new DataSourceTransactionObject T2 for M2. M2 run within its own transaction context.
PROPAGATION_NOT_SUPPORTED = 4; If DataSourceTransactionObject T1 is already started for Method M1. If another method M2 is run concurrently. Then M2 should not run within transaction context. T1 is suspended till M2 is finished.
PROPAGATION_NEVER = 5; None of the methods run in transaction context.
An isolation level: It is about how much a transaction may be impacted by the activities of other concurrent transactions. It a supports consistency leaving the data across many tables in a consistent state. It involves locking rows and/or tables in a database.
The problem with multiple transaction
Scenario 1. If T1 transaction reads data from table A1 that was written by another concurrent transaction T2. If on the way T2 is rollback, the data obtained by T1 is invalid one. E.g. a=2 is original data. If T1 read a=1 that was written by T2. If T2 rollback then a=1 will be rollback to a=2 in DB. But, now, T1 has a=1 but in DB table it is changed to a=2.
Scenario2. If T1 transaction reads data from table A1. If another concurrent transaction (T2) update data on table A1. Then the data that T1 has read is different from table A1. Because T2 has updated the data on table A1. E.g. if T1 read a=1 and T2 updated a=2. Then a!=b.
Scenario 3. If T1 transaction reads data from table A1 with certain number of rows. If another concurrent transaction (T2) inserts more rows on table A1. The number of rows read by T1 is different from rows on table A1.
Scenario 1 is called Dirty reads.
Scenario 2 is called Non-repeatable reads.
Scenario 3 is called Phantom reads.
So, isolation level is the extend to which Scenario 1, Scenario 2, Scenario 3 can be prevented. You can obtain complete isolation level by implementing locking. That is preventing concurrent reads and writes to the same data from occurring. But it affects performance. The level of isolation depends upon application to application how much isolation is required.
ISOLATION_READ_UNCOMMITTED: Allows to read changes that haven’t yet been committed. It suffer from Scenario 1, Scenario 2, Scenario 3.
ISOLATION_READ_COMMITTED: Allows reads from concurrent transactions that have been committed. It may suffer from Scenario 2 and Scenario 3. Because other transactions may be updating the data.
ISOLATION_REPEATABLE_READ: Multiple reads of the same field will yield the same results untill it is changed by itself. It may suffer from Scenario 3. Because other transactions may be inserting the data.
ISOLATION_SERIALIZABLE: Scenario 1, Scenario 2, Scenario 3 never happen. It is complete isolation. It involves full locking. It affects performace because of locking.
You can test using:
public class TransactionBehaviour {
// set is either using xml Or annotation
DataSourceTransactionManager manager=new DataSourceTransactionManager();
SimpleTransactionStatus status=new SimpleTransactionStatus();
;
public void beginTransaction()
{
DefaultTransactionDefinition Def = new DefaultTransactionDefinition();
// overwrite default PROPAGATION_REQUIRED and ISOLATION_DEFAULT
// set is either using xml Or annotation
manager.setPropagationBehavior(XX);
manager.setIsolationLevelName(XX);
status = manager.getTransaction(Def);
}
public void commitTransaction()
{
if(status.isCompleted()){
manager.commit(status);
}
}
public void rollbackTransaction()
{
if(!status.isCompleted()){
manager.rollback(status);
}
}
Main method{
beginTransaction()
M1();
If error(){
rollbackTransaction()
}
commitTransaction();
}
}
You can debug and see the result with different values for isolation and propagation.
Very old post, but since it helped me after I made some modifications, I thought I'd share. If you're checking to see if a directory exists, you'll want to add the vbDirectory argument to the Dir function, otherwise you'll return 0
each time. (Edit: this was in response to Roy's answer, but I accidentally made it a regular answer.)
Private Function FileExists(fullFileName As String) As Boolean
FileExists = Len(Dir(fullFileName, vbDirectory)) > 0
End Function
You can do so from within vim and use its own windows or tabs.
One way to go is to utilize the built-in file explorer; activate it via :Explore
, or :Texplore
for a tabbed interface (which I find most comfortable).
:Texplore
(and :Sexplore
) will also guard you from accidentally exiting the current buffer (editor) on :q
once you're inside the explorer.
To toggle between open tabs when using tab pages use gt
or gT
(next tab and previous tab, respectively).
See also Using tab pages on the vim wiki.
Use this code.it will help you for achieving your goal.
Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.profileimage);
if (bmp!=null) {
Bitmap bitmap_round=getRoundedShape(bmp);
if (bitmap_round!=null) {
profileimage.setImageBitmap(bitmap_round);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 100;
int targetHeight = 100;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), new Paint(Paint.FILTER_BITMAP_FLAG));
return targetBitmap;
}
Simply use
<span onClick={() => this.props.history.goBack()}>Back</span>
This is one way to do it:
SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
2 /
Type created
SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
2 BEGIN
3 FOR i IN 1..t_in.count LOOP
4 dbms_output.put_line(t_in(i));
5 END LOOP;
6 END;
7 /
Procedure created
SQL> DECLARE
2 v_t MyType;
3 BEGIN
4 v_t := MyType();
5 v_t.EXTEND(10);
6 v_t(1) := 'this is a test';
7 v_t(2) := 'A second test line';
8 testing(v_t);
9 END;
10 /
this is a test
A second test line
To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:
SQL> CREATE OR REPLACE PACKAGE p IS
2 TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
3
4 PROCEDURE pp (inp p_type);
5 END p;
6 /
Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
2 PROCEDURE pp (inp p_type) IS
3 BEGIN
4 FOR i IN 1..inp.count LOOP
5 dbms_output.put_line(inp(i));
6 END LOOP;
7 END pp;
8 END p;
9 /
Package body created
SQL> DECLARE
2 v_t p.p_type;
3 BEGIN
4 v_t(1) := 'this is a test of p';
5 v_t(2) := 'A second test line for p';
6 p.pp(v_t);
7 END;
8 /
this is a test of p
A second test line for p
PL/SQL procedure successfully completed
SQL>
This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.
I had the same issue happening. When I checked the error.log I found that my disk was full.
Use:
df -h
on the command line. it will tell you how much space you have left. mine was full. found my error.log file was 4.77GB. I downloaded it and then deleted it. Then I used service mysqld start and it worked.
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine
line, as that is handled internally by express.
For Sublime Text Editor
Indentation Error generally occurs when the code contains a mix of both tabs and spaces for indentation. I have got a very nice solution to correct it, just open your code in a sublime text editor and find 'Tab Size'
in the bottom right corner of Sublime Text Editor and click it. Now select either
'Convert Indentation to Spaces'
OR
'Convert Indentation to Tabs'
Your code will work in either case.
Additionally, if you want Sublime text to do it automatically for you for every code you can update the Preference settings as below:-
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
The best way to put is that hg forget
is identical to hg remove
except that it leaves the files behind in your working copy. The files are left behind as untracked files and can now optionally be ignored with a pattern in .hgignore
.
In other words, I cannot tell if you used hg forget
or hg remove
when I pull from you. A file that you ran hg forget
on will be deleted when I update to that changeset — just as if you had used hg remove
instead.
I'll take a little exception to jichao's answer. You can actually do everything he just talked about fairly easily. Instead of looking for a \n
, just look for carriage return at the end of the line.
sed -i 's/\r$//' "${FILE_NAME}"
To change from unix back to dos, simply look for the last character on the line and add a form feed to it. (I'll add -r
to make this easier with grep regular expressions.)
sed -ri 's/(.)$/\1\r/' "${FILE_NAME}"
Theoretically, the file could be changed to mac style by adding code to the last example that also appends the next line of input to the first line until all lines have been processed. I won't try to make that example here, though.
Warning: -i changes the actual file. If you want a backup to be made, add a string of characters after -i
. This will move the existing file to a file with the same name with your characters added to the end.
$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
'langs' => $langs
]);
then in view
<script type="text/javascript">
var langs = {{json_encode($langs)}};
console.log(langs);
</script>
Its not pretty tho
Edit:
Sorry i forgot about pluck()
as many have commented :
Easiest way is :
return DB::table('users')->where('username', $username)->pluck('groupName');
Which will directly return the only the first result for the requested row as a string.
Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner
$result = DB::table('users')->select('groupName')->where('username', $username)->first();
The first()
tells the queryBuilder to return only one row so no array, so you can do :
return $result->groupName;
Hope it helps
kindly use:
$('#myIframe').on('load', function(){
//your code (will be called once iframe is done loading)
});
Updated my answer as the standards changed.
To install Openjdk 11 in Ubuntu, the following commands worked well.
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt install openjdk-11-jdk
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
Acked Unseen sample
Hi guys! Just some observations from what I just found in my capture:
On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client
Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC
In the capture example above, frame 67795 sends an ACK for 10384
Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
To get records from the last 24 hours:
SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
For anyone on a Mac who has Docker Desktop installed. I was able to just click the tray icon and say Restart Docker
. Once it restarted was able to delete the containers.
PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:
http_response_code(500);
I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.
To answer your follow-up question, the HTTP 1.1 RFC says:
The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.
That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).
With the excellent matplotlib
and numpy
packages
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
There is no dict literal to create dict-inherited classes, custom dict classes with additional methods. In such case custom dict class constructor should be used, for example:
class NestedDict(dict):
# ... skipped
state_type_map = NestedDict(**{
'owns': 'Another',
'uses': 'Another',
})
Follow this path.
C:\Program Files\MongoDB\Server\4.2\bin
Run the cmd in bin folder and paste the below command
mongorestore --db <name-your-database-want-to-restore-as> <path-of-dumped-database>
For Example:
mongorestore --db testDb D:\Documents\Dump\myDb
Something like this:
DataTable dt = new DataTable();
// For each row, print the values of each column.
foreach(DataRow row in dt .Rows)
{
foreach(DataColumn column in dt .Columns)
{
Console.WriteLine(row[column]);
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.rows.aspx
Some thoughts:
class Model(model.Model):
_image=models.ImageField(upload_to='folder')
thumb=models.ImageField(upload_to='folder')
description=models.CharField()
def set_image(self, val):
self._image = val
self._image_changed = True
# Or put whole logic in here
small = rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
def get_image(self):
return self._image
image = property(get_image, set_image)
# this is not needed if small_image is created at set_image
def save(self, *args, **kwargs):
if getattr(self, '_image_changed', True):
small=rescale_image(self.image,width=100,height=100)
self.image_small=SimpleUploadedFile(name,small_pic)
super(Model, self).save(*args, **kwargs)
Not sure if it would play nice with all pseudo-auto django tools (Example: ModelForm, contrib.admin etc).
Why hasn't anyone suggested extension methods on ViewData?
Option #1
Seems to me by far the least intrusive and simplest solution to the problem. No hardcoded strings. No imposed restrictions. No magic coding. No complex code.
public static class ViewDataExtensions
{
private const string TitleData = "Title";
public static void SetTitle<T>(this ViewDataDictionary<T> viewData, string value) => viewData[TitleData] = value;
public static string GetTitle<T>(this ViewDataDictionary<T> viewData) => (string)viewData[TitleData] ?? "";
}
Set data in the page
ViewData.SetTitle("abc");
Option #2
Another option, making the field declaration easier.
public static class ViewDataExtensions
{
public static ViewDataField<string, V> Title<V>(this ViewDataDictionary<V> viewData) => new ViewDataField<string, V>(viewData, "Title", "");
}
public class ViewDataField<T,V>
{
private readonly ViewDataDictionary<V> _viewData;
private readonly string _field;
private readonly T _defaultValue;
public ViewDataField(ViewDataDictionary<V> viewData, string field, T defaultValue)
{
_viewData = viewData;
_field = field;
_defaultValue = defaultValue;
}
public T Value {
get => (T)(_viewData[_field] ?? _defaultValue);
set => _viewData[_field] = value;
}
}
Set data in the page. Declaration is easier than first option, but usage syntax is slightly longer.
ViewData.Title().Value = "abc";
Option #3
Then can combine that with returning a single object containing all layout-related fields with their default values.
public static class ViewDataExtensions
{
private const string LayoutField = "Layout";
public static LayoutData Layout<T>(this ViewDataDictionary<T> viewData) =>
(LayoutData)(viewData[LayoutField] ?? (viewData[LayoutField] = new LayoutData()));
}
public class LayoutData
{
public string Title { get; set; } = "";
}
Set data in the page
var layout = ViewData.Layout();
layout.Title = "abc";
This third option has several benefits and I think is the best option in most cases:
Simplest declaration of fields and default values.
Simplest usage syntax when setting multiple fields.
Allows setting various kinds of data in the ViewData (eg. Layout, Header, Navigation).
Allows additional code and logic within LayoutData class.
P.S. Don't forget to add the namespace of ViewDataExtensions in _ViewImports.cshtml
More often than you think, C needs to do things that seem to be unneccessary from an Assembly coder's point of view just because the C standards say so.
Integer promotion, for example. If you want to shift a char variable in C, one would usually expect that the code would do in fact just that, a single bit shift.
The standards, however, enforce the compiler to do a sign extend to int before the shift and truncate the result to char afterwards which might complicate code depending on the target processor's architecture.
Below conf works for me:
JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME
JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"
/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"
None of the other answers were working for me immediately on ElementaryOS Freya (based on Ubuntu 14.04); I was getting the
[TerminalIPythonApp] WARNING | File not found: 'kernelspec'
error that quickbug described under Matt's answer. I had to first do:
sudo apt-get install pip3
, then
sudo pip3 install ipython[all]
At that point you can then run the commands that Matt suggested; namely: ipython kernelspec install-self
and ipython3 kernelspec install-self
Now when I launch ipython notebook
and then open a notebook, I am able to select the Python 3 kernel from the Kernel menu.
Get list commit
git log --oneline
For example, Stable commit has hash: 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git reset --hard 45ff319c360cd7bd5442c0fbbe14202d20ccdf81
git push -ff origin master
Try this:
alerts.splice(0,0,{"app":"goodbyeworld","message":"cya"});
Works pretty well, it'll add it to the start of the array.
mvn validate clean install | egrep -v "(^\[INFO\])"
or
mvn validate clean install | egrep -v "(^\[INFO\]|^\[DEBUG\])"
mvn validate clean install | findstr /V /R "^\[INFO\] ^\[DEBUG\]"
You can leverage Conditional Formatting
as follows.
H8
select Format > Conditional Formatting...=I8="Elementary"
Format...
and select the color you want etc.Add>>
and repeat steps 1 to 4Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?
If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
It's a custom html attribute but probably in this case is used by the Facebook React JS Library.
Take a look: http://facebook.github.io/react/
Use the layout_weight
attribute. The layout will roughly look like this:
<LinearLayout android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
<LinearLayout
android:layout_weight="1"
android:layout_height="fill_parent"
android:layout_width="0dp"/>
</LinearLayout>
<?php _x000D_
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));_x000D_
if(isset($_POST[add]))_x000D_
{_x000D_
$sno = mysqli_real_escape_string($con,$_POST[sno]);_x000D_
$name = mysqli_real_escape_string($con,$_POST[sname]);_x000D_
$course = mysqli_real_escape_string($con,$_POST[course]);_x000D_
_x000D_
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";_x000D_
//echo $query;_x000D_
$result = mysqli_query($con,$query);_x000D_
printf ("New Record has id %d.\n", mysqli_insert_id($con));_x000D_
mysqli_close($con);_x000D_
_x000D_
} _x000D_
?>_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>mysql_insert_id Example</title>_x000D_
</head>_x000D_
<body>_x000D_
<form action="" method="POST">_x000D_
Enter S.NO: <input type="text" name="sno"/><br/>_x000D_
Enter Student Name: <input type="text" name="sname"/><br/>_x000D_
Enter Course: <input type="text" name="course"/><br/>_x000D_
<input type="submit" name="add" value="Add Student"/>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
Use ViewPager. It's work for me.
final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager);
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewPager.setCurrentItem(1);
}
});
I navigated to C:\wamp\bin\apache\Apache2.4.4\bin run httpd and the apache (pink and white icon) loads into the system tray. The orange W also turned green.
The apacheapache service wasn't running, it wasn't on the services list (start > type services) which is why it's orange not green.
Solution: A re-install worked for me.
My version is: WAMPSERVER (64Bits & PHP 5.4) 2.4 Apache : 2.4.4 MySQL : 5.6.12 PHP : 5.4.12 PHPMyAdmin : 4.0.4 SqlBuddy : 1.3.3 XDebug : 2.2.3 http://www.wampserver.com/en/
Note: You can first preview what your patch will do:
First the stats:
git apply --stat a_file.patch
Then a dry run to detect errors:
git apply --check a_file.patch
Finally, you can use git am
to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.
git am --signoff < a_file.patch
See an example in this article:
In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.
Use the (ngModelChange)
event to detect changes on the model
try this, for Programmatically to set a background with radius to LinearLayout or any View.
private Drawable getDrawableWithRadius() {
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadii(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
gradientDrawable.setColor(Color.RED);
return gradientDrawable;
}
LinearLayout layout = new LinearLayout(this);
layout.setBackground(getDrawableWithRadius());
For future reference to people who find this page later you can use:
<audio controls autoplay loop hidden>
<source src="kooche.mp3" type="audio/mpeg">
<p>If you can read this, your browser does not support the audio element.</p>
</audio>
I help develop the Colectica for Excel addin, which opens SPSS and Stata data files in Excel. This does not require ODBC configuration; it reads the file and then inserts the data and metadata into your worksheet.
The addin is downloadable from http://www.colectica.com/software/colecticaforexcel
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
http://getbootstrap.com/examples/offcanvas/
This is the official example, may be better for some. It is under their Experiments examples section, but since it is official, it should be kept up to date with the current bootstrap release.
Looks like they have added an off canvas css file used in their example:
http://getbootstrap.com/examples/offcanvas/offcanvas.css
And some JS code:
$(document).ready(function () {
$('[data-toggle="offcanvas"]').click(function () {
$('.row-offcanvas').toggleClass('active')
});
});
I built a general method for that with following features:
Here the code:
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
File repositoryFile = new File("c:/temp/myfile.png");
return returnFile(repositoryFile, modified);
}
/**
*
* Sends the file if modified and "not modified" if not modified
* future work may put each file with a unique id in a separate folder in tomcat
* * use that static URL for each file
* * if file is modified, URL of file changes
* * -> client always fetches correct file
*
* method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
*
* @param file to send
* @param modified - HeaderField "If-Modified-Since" - may be "null"
* @return Response to be sent to the client
*/
public static Response returnFile(File file, String modified) {
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
// do we really need to send the file or can send "not modified"?
if (modified != null) {
Date modifiedDate = null;
// we have to switch the locale to ENGLISH as parseDate parses in the default locale
Locale old = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
try {
modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
Locale.setDefault(old);
if (modifiedDate != null) {
// modifiedDate does not carry milliseconds, but fileDate does
// therefore we have to do a range-based comparison
// 1000 milliseconds = 1 second
if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
return Response.status(Status.NOT_MODIFIED).build();
}
}
}
// we really need to send the file
try {
Date fileDate = new Date(file.lastModified());
return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
} catch (FileNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
public static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1036,
PATTERN_RFC1123,
PATTERN_ASCTIME
};
Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...
Either you initialize the variable to something
char retChar = 'x';
or you leave it automatically initialized, which is
char retChar = '\0';
an ascii 0, the same as
char retChar = (char) 0;
What can one initialize char values to?
Sounds undecided between automatic initialisation, which means, you have no influence, or explicit initialisation. But you cannot change the default.
Inline is not actually the inline we maybe require - i.e. display:inline
Bootstrap inline as far as I observer is more of a horizontal orientation
To display the list inline with other elements then we do need
display: inline; added to the UL
<ul class="unstyled inline" style="display:inline">
NB// Add to stylesheet
CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}
, doing the following should succeed:
add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)
Try it.
You can just pass the path to the style sheet .
{!! HTML::style('css/style.css') !!}
You can just pass the path to the javascript.
{!! HTML::script('js/script.js') !!}
Add the following lines in the require section of composer.json file and run composer update "illuminate/html": "5.*".
Register the service provider in config/app.php by adding the following value into the providers array:
'Illuminate\Html\HtmlServiceProvider'
Register facades by adding these two lines in the aliases array:
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade'
myOptions = {
center: myLatlng,
minZoom: 6,
maxZoom: 9,
styles: customStyles,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Try this it works for me:
/^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;
Math.floor(1+7/8)
Use this one:
Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & ws.Name & "'!" & range1.Address
End With
Note that when you're using Dim range1, rng As range
, only rng
has type of Range
, but range1
is Variant
. That's why I'm using Dim range1 As Range, rng As Range
.
About meaning of parameters you can read is MSDN, but in short:
Type:=xlValidateList
means validation type, in that case you should select value from listAlertStyle:=xlValidAlertStop
specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.Operator:= xlBetween
is odd. It can be used only if two formulas are provided for validation.Formula1:="='" & ws.Name & "'!" & range1.Address
for list data validation provides address of list with values (in format =Sheet!A1:A5
)If the indices match then:
df['B'] = df1['E']
should work otherwise:
df['B'] = df1['E'].values
will work so long as the length of the elements matches
Set the CSS position: relative;
on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:
position: absolute;
bottom: 0;
right: 0;
If you need to space the text farther away from the edge, you could change 0
to 2px
or similar.
To expand on cristobalito's answer:
I assume you're talking about on the command-line - if it's in a script, then a new-line >acts as a command delimiter.
On the command line, use a semi-colon ';'
For example:
Sign a PowerShell script on the command-line. No line breaks.
powershell -Command "&{$cert=Get-ChildItem –Path cert:\CurrentUser\my -codeSigningCert ; Set-AuthenticodeSignature -filepath Z:\test.ps1 -Cert $cert}
try using
background-color: none;
that worked for me.
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
You're looking for this on the command line (for a class called MyClass):
On Unix/Linux:
javap -verbose MyClass | grep "major"
On Windows:
javap -verbose MyClass | findstr "major"
You want the major version from the results. Here are some example values:
Here is the sample MYSQL Stored Procedure with delimiter and how to call..
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_user_login` $$
CREATE DEFINER=`root`@`%` PROCEDURE `sp_user_login`(
IN loc_username VARCHAR(255),
IN loc_password VARCHAR(255)
)
BEGIN
SELECT user_id,
user_name,
user_emailid,
user_profileimage,
last_update
FROM tbl_user
WHERE user_name = loc_username
AND password = loc_password
AND status = 1;
END $$
DELIMITER ;
and call by, mysql_connection specification and
$loginCheck="call sp_user_login('".$username."','".$password."');";
it will return the result from the procedure.
INNER JOIN
is ANSI syntax that you should use.
It is generally considered more readable, especially when you join lots of tables.
It can also be easily replaced with an OUTER JOIN
whenever a need arises.
The WHERE
syntax is more relational model oriented.
A result of two tables JOIN
ed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.
It's easier to see this with the WHERE
syntax.
As for your example, in MySQL (and in SQL generally) these two queries are synonyms.
Also, note that MySQL also has a STRAIGHT_JOIN
clause.
Using this clause, you can control the JOIN
order: which table is scanned in the outer loop and which one is in the inner loop.
You cannot control this in MySQL using WHERE
syntax.
I'm adding this because it's not mentioned in any of the other answers. You can give a container a specific hostname at runtime with the -h directive.
docker run -h=my.docker.container.example.com ubuntu:latest
You can use backticks (or whatever equivalent your shell uses) to get the output of hosthame into the -h argument.
docker run -h=`hostname` ubuntu:latest
There is a caveat, the value of hostname will be taken from the host you run the command from, so if you want the hostname of a virtual machine that's running your docker container then using hostname as an argument may not be correct if you are using the host machine to execute docker commands on the virtual machine.
I solved this issue by killing all instances of iexplorer and iexplorer*32. It looks like Internet Explorer was still in memory holding the port open even though the application window was closed.
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
According to the Python doc, we can also use class.__mro__
attribute or class.mro()
method:
class Suit:
pass
class Heart(Suit):
pass
class Spade(Suit):
pass
class Diamond(Suit):
pass
class Club(Suit):
pass
>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)
Suit in Heart.mro() # True
object in Heart.__mro__ # True
Spade in Heart.mro() # False
I tried some of the sources online and finally, the below selection works fine for me (Dreamweaver on Mac). For versions above Adobe Dreamweaver CC 2017 and above:
Adobe says:
Edit > Code > Apply Source Formatting
Moreover, full documentation with other supporting information for tasks such as setting defaults, etc. on https://helpx.adobe.com/dreamweaver/using/format-code.html.
The opposite of this is to flatten a column into a csv eg
SELECT STRING_AGG ([value],',') FROM STRING_SPLIT('Akio,Hiraku,Kazuo', ',')
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
.str.get
This is the simplest to specify string methods
# Setup
df = pd.DataFrame({'A': ['xyz', 'abc', 'foobar'], 'B': [123, 456, 789]})
df
A B
0 xyz 123
1 abc 456
2 foobar 789
df.dtypes
A object
B int64
dtype: object
For string (read:object
) type columns, use
df['C'] = df['A'].str[0]
# Similar to,
df['C'] = df['A'].str.get(0)
.str
handles NaNs by returning NaN as the output.
For non-numeric columns, an .astype
conversion is required beforehand, as shown in @Ed Chum's answer.
# Note that this won't work well if the data has NaNs.
# It'll return lowercase "n"
df['D'] = df['B'].astype(str).str[0]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
There is enough evidence to suggest a simple list comprehension will work well here and probably be faster.
# For string columns
df['C'] = [x[0] for x in df['A']]
# For numeric columns
df['D'] = [str(x)[0] for x in df['B']]
df
A B C D
0 xyz 123 x 1
1 abc 456 a 4
2 foobar 789 f 7
If your data has NaNs, then you will need to handle this appropriately with an if
/else
in the list comprehension,
df2 = pd.DataFrame({'A': ['xyz', np.nan, 'foobar'], 'B': [123, 456, np.nan]})
df2
A B
0 xyz 123.0
1 NaN 456.0
2 foobar NaN
# For string columns
df2['C'] = [x[0] if isinstance(x, str) else np.nan for x in df2['A']]
# For numeric columns
df2['D'] = [str(x)[0] if pd.notna(x) else np.nan for x in df2['B']]
A B C D
0 xyz 123.0 x 1
1 NaN 456.0 NaN 4
2 foobar NaN f NaN
Let's do some timeit tests on some larger data.
df_ = df.copy()
df = pd.concat([df_] * 5000, ignore_index=True)
%timeit df.assign(C=df['A'].str[0])
%timeit df.assign(D=df['B'].astype(str).str[0])
%timeit df.assign(C=[x[0] for x in df['A']])
%timeit df.assign(D=[str(x)[0] for x in df['B']])
12 ms ± 253 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
27.1 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
3.77 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
7.84 ms ± 145 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
List comprehensions are 4x faster.
UPDATE TABLE
SET EndDate = CAST('2017-12-31' AS DATE)
WHERE Id = '123'
Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$
and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready
$(document).ready(function() {
$('selectorForTextbox').bind('keyup', function(e) {
if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
$(this).addClass('invalid');
} else {
$(this).removeClass('invalid');
}
});
});
Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.
The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.
Go to http://opengapps.org/ and download the pico version of your platform and android version. Unzip the downloaded folder to get
1. GmsCore.apk
2. GoogleServicesFramework.apk
3. GoogleLoginService.apk
4. Phonesky.apk
Then, locate your emulator.exe. You will probably find it in
C:\Users\<YOUR_USER_NAME>\AppData\Local\Android\sdk\tools
Run the command:
emulator -avd <YOUR_EMULATOR'S_NAME> -netdelay none -netspeed full -no-boot-anim -writable-system
Note: Use -writable-system to start your emulator with writable system image.
Then,
adb root
adb remount
adb push <PATH_TO GmsCore.apk> /system/priv-app
adb push <PATH_TO GoogleServicesFramework.apk> /system/priv-app
adb push <PATH_TO GoogleLoginService.apk> /system/priv-app
adb push <PATH_TO Phonesky.apk> /system/priv-app
Then, reboot the emulator
adb shell stop
adb shell start
To verify run,
adb shell pm list packages and you will find com.google.android.gms package for google
Without changing the position to absolute, see below. This supports all recent browsers as well.
.vranger {_x000D_
margin-top: 50px;_x000D_
transform: rotate(270deg);_x000D_
-moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
for very old browsers, you can use -sand-transform: rotate(10deg);
from CSS sandpaper
or use
prefix selector such as -ms-transform: rotate(270deg);
for IE9
Here is my method made with pure PHP and CSS :
/** PHP code */
<?php
$string = "the string with linebreaks";
$string = strtr($string,array("."=>".\r\r",":"=>" : \r","-"=>"\r - "));
?>
And the CSS :
.your_textarea_class {
style='white-space:pre-wrap';
}
You can do the same with regex (I'm learning how to build regex with pregreplace using an associative array, seems to be better for adding the \n\r which makes the breaks display).
Well I faced this issue today and as workaround (not the best) I did below
<script type="text/javascript" src="testWeb/scripts/inline.31e1fb380eb7cf3d75b1.bundle.js"></script>
where testWeb
is my root app folder in my htdoc dir. in windows (using xampp) or in /var/www/html directory as for some reason I do not know yet
<script type="text/javascript" src="scripts/inline.31e1fb380eb7cf3d75b1.bundle.js"></script>
not loading while html index file beside scripts folder in same directory.
Either structure is valid and accessible, but the for
attribute should be equal to the id
of the input element:
<input type="radio" ... id="r1" /><label for="r1">button text</label>
or
<label for="r1"><input type="radio" ... id="r1" />button text</label>
The for
attribute is optional in the second version (label containing input), but IIRC there were some older browsers that didn't make the label text clickable unless you included it. The first version (label after input) is easier to style with CSS using the adjacent sibling selector +
:
input[type="radio"]:checked+label {font-weight:bold;}
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))
Avoid semicolon in the end of any environment variables... from JAVA_HOME or JRE_HOME
JAVA_HOME=C:\Program Files\Java\jdk1.6.0_25\bin
and
JRE_HOME=C:\Program Files\Java\jdk1.6.0_32\jre
should be like as shown...
Your construction is illegal. You cannot include parameters in the action value of a form. What happens if you try this is going to depend on quirks of the browser. I wouldn't be surprised if it worked with one browser and not another. Even if it appeared to work, I would not rely on it, because the next version of the browser might change the behavior.
"But lets say I have parameters in query string and in hidden inputs, what can I do?" What you can do is fix the error. Not to be snide, but this is a little like asking, "But lets say my URL uses percent signs instead of slashes, what can I do?" The only possible answer is, you can fix the URL.
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details