There is also
which aims
- To encode entire script in a proprietary PHP application
- To encode some classes and/or functions in a proprietary PHP application
- To enable the production of php-gtk applications that could be used on client desktops, without the need for a php.exe.
- To do the feasibility study for a PHP to C converter
The extension is available from PECL.
While not directly related to the question's environment, just for the curiosity, I did the same test on .NET Core 2.1, x64, release mode.
Here is the interesting result, confirming similar phonomena (other way around) happening over the dark side of the force. Code:
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
Console.WriteLine("2 * (i * i)");
for (int a = 0; a < 10; a++)
{
int n = 0;
watch.Restart();
for (int i = 0; i < 1000000000; i++)
{
n += 2 * (i * i);
}
watch.Stop();
Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds} ms");
}
Console.WriteLine();
Console.WriteLine("2 * i * i");
for (int a = 0; a < 10; a++)
{
int n = 0;
watch.Restart();
for (int i = 0; i < 1000000000; i++)
{
n += 2 * i * i;
}
watch.Stop();
Console.WriteLine($"result:{n}, {watch.ElapsedMilliseconds}ms");
}
}
Result:
2 * (i * i)
2 * i * i
As already said in the previous posts, JIT can compile IL/bytecode into native code at runtime. The cost of that was mentionned, but not to its conclusion:
JIT has one massive problem is that it can't compile everything: JIT compiling takes time, so the JIT will compile only some parts of the code, whereas a static compiler will produce a full native binary: For some kind of programs, the static compiler will simply easily outperform the JIT.
Of course, C# (or Java, or VB) is usually faster to produce viable and robust solution than is C++ (if only because C++ has complex semantics, and C++ standard library, while interesting and powerful, is quite poor when compared with the full scope of the standard library from .NET or Java), so usually, the difference between C++ and .NET or Java JIT won't be visible to most users, and for those binaries that are critical, well, you can still call C++ processing from C# or Java (even if this kind of native calls can be quite costly in themselves)...
Note that usually, you are comparing C++ runtime code with its equivalent in C# or Java. But C++ has one feature that can outperform Java/C# out of the box, that is template metaprograming: The code processing will be done at compilation time (thus, increasing vastly compilation time), resulting into zero (or almost zero) runtime.
I have yet so see a real life effect on this (I played only with concepts, but by then, the difference was seconds of execution for JIT, and zero for C++), but this is worth mentioning, alongside the fact template metaprograming is not trivial...
Edit 2011-06-10: In C++, playing with types is done at compile time, meaning producing generic code which calls non-generic code (e.g. a generic parser from string to type T, calling standard library API for types T it recognizes, and making the parser easily extensible by its user) is very easy and very efficient, whereas the equivalent in Java or C# is painful at best to write, and will always be slower and resolved at runtime even when the types are known at compile time, meaning your only hope is for the JIT to inline the whole thing.
...
Edit 2011-09-20: The team behind Blitz++ (Homepage, Wikipedia) went that way, and apparently, their goal is to reach FORTRAN's performance on scientific calculations by moving as much as possible from runtime execution to compilation time, via C++ template metaprogramming. So the "I have yet so see a real life effect on this" part I wrote above apparently does exist in real life.
C++ has a memory usage different from Java/C#, and thus, has different advantages/flaws.
No matter the JIT optimization, nothing will go has fast as direct pointer access to memory (let's ignore for a moment processor caches, etc.). So, if you have contiguous data in memory, accessing it through C++ pointers (i.e. C pointers... Let's give Caesar its due) will goes times faster than in Java/C#. And C++ has RAII, which makes a lot of processing a lot easier than in C# or even in Java. C++ does not need using
to scope the existence of its objects. And C++ does not have a finally
clause. This is not an error.
:-)
And despite C# primitive-like structs, C++ "on the stack" objects will cost nothing at allocation and destruction, and will need no GC to work in an independent thread to do the cleaning.
As for memory fragmentation, memory allocators in 2008 are not the old memory allocators from 1980 that are usually compared with a GC: C++ allocation can't be moved in memory, true, but then, like on a Linux filesystem: Who needs hard disk defragmenting when fragmentation does not happen? Using the right allocator for the right task should be part of the C++ developer toolkit. Now, writing allocators is not easy, and then, most of us have better things to do, and for the most of use, RAII or GC is more than good enough.
Edit 2011-10-04: For examples about efficient allocators: On Windows platforms, since Vista, the Low Fragmentation Heap is enabled by default. For previous versions, the LFH can be activated by calling the WinAPI function HeapSetInformation). On other OSes, alternative allocators are provided (see https://secure.wikimedia.org/wikipedia/en/wiki/Malloc for a list)
Now, the memory model is somewhat becoming more complicated with the rise of multicore and multithreading technology. In this field, I guess .NET has the advantage, and Java, I was told, held the upper ground. It's easy for some "on the bare metal" hacker to praise his "near the machine" code. But now, it is quite more difficult to produce better assembly by hand than letting the compiler to its job. For C++, the compiler became usually better than the hacker since a decade. For C# and Java, this is even easier.
Still, the new standard C++0x will impose a simple memory model to C++ compilers, which will standardize (and thus simplify) effective multiprocessing/parallel/threading code in C++, and make optimizations easier and safer for compilers. But then, we'll see in some couple of years if its promises are held true.
Note: In this section, I am talking about C++/CLI, that is, the C++ hosted by .NET, not the native C++.
Last week, I had a training on .NET optimization, and discovered that the static compiler is very important anyway. As important than JIT.
The very same code compiled in C++/CLI (or its ancestor, Managed C++) could be times faster than the same code produced in C# (or VB.NET, whose compiler produces the same IL than C#).
Because the C++ static compiler was a lot better to produce already optimized code than C#'s.
For example, function inlining in .NET is limited to functions whose bytecode is less or equal than 32 bytes in length. So, some code in C# will produce a 40 bytes accessor, which won't be ever inlined by the JIT. The same code in C++/CLI will produce a 20 bytes accessor, which will be inlined by the JIT.
Another example is temporary variables, that are simply compiled away by the C++ compiler while still being mentioned in the IL produced by the C# compiler. C++ static compilation optimization will result in less code, thus authorizes a more aggressive JIT optimization, again.
The reason for this was speculated to be the fact C++/CLI compiler profited from the vast optimization techniques from C++ native compiler.
I love C++.
But as far as I see it, C# or Java are all in all a better bet. Not because they are faster than C++, but because when you add up their qualities, they end up being more productive, needing less training, and having more complete standard libraries than C++. And as for most of programs, their speed differences (in one way or another) will be negligible...
I have now 5 months of almost exclusive professional C# coding (which adds up to my CV already full of C++ and Java, and a touch of C++/CLI).
I played with WinForms (Ahem...) and WCF (cool!), and WPF (Cool!!!! Both through XAML and raw C#. WPF is so easy I believe Swing just cannot compare to it), and C# 4.0.
The conclusion is that while it's easier/faster to produce a code that works in C#/Java than in C++, it's a lot harder to produce a strong, safe and robust code in C# (and even harder in Java) than in C++. Reasons abound, but it can be summarized by:
using
is not as easy and powerful because writing a correct Dispose implementations is difficult)readonly
and Java final
are nowhere as useful as C++'s const
(There's no way you can expose readonly complex data (a Tree of Nodes, for example) in C# without tremendous work, while it's a built-in feature of C++. Immutable data is an interesting solution, but not everything can be made immutable, so it's not even enough, by far).So, C# remains an pleasant language as long as you want something that works, but a frustrating language the moment you want something that always and safely works.
Java is even more frustrating, as it has the same problems than C#, and more: Lacking the equivalent of C#'s using
keyword, a very skilled colleague of mine spent too much time making sure its resources where correctly freed, whereas the equivalent in C++ would have been easy (using destructors and smart pointers).
So I guess C#/Java's productivity gain is visible for most code... until the day you need the code to be as perfect as possible. That day, you'll know pain. (you won't believe what's asked from our server and GUI apps...).
I kept contact with the server teams (I worked 2 years among them, before getting back to the GUI team), at the other side of the building, and I learned something interesting.
Last years, the trend was to have the Java server apps be destined to replace the old C++ server apps, as Java has a lot of frameworks/tools, and is easy to maintain, deploy, etc. etc..
...Until the problem of low-latency reared its ugly head the last months. Then, the Java server apps, no matter the optimization attempted by our skilled Java team, simply and cleanly lost the race against the old, not really optimized C++ server.
Currently, the decision is to keep the Java servers for common use where performance while still important, is not concerned by the low-latency target, and aggressively optimize the already faster C++ server applications for low-latency and ultra-low-latency needs.
Nothing is as simple as expected.
Java, and even more C#, are cool languages, with extensive standard libraries and frameworks, where you can code fast, and have result very soon.
But when you need raw power, powerful and systematic optimizations, strong compiler support, powerful language features and absolute safety, Java and C# make it difficult to win the last missing but critical percents of quality you need to remain above the competition.
It's as if you needed less time and less experienced developers in C#/Java than in C++ to produce average quality code, but in the other hand, the moment you needed excellent to perfect quality code, it was suddenly easier and faster to get the results right in C++.
Of course, this is my own perception, perhaps limited to our specific needs.
But still, it is what happens today, both in the GUI teams and the server-side teams.
Of course, I'll update this post if something new happens.
"We find that in regards to performance, C++ wins out by a large margin. However, it also required the most extensive tuning efforts, many of which were done at a level of sophistication that would not be available to the average programmer.
[...] The Java version was probably the simplest to implement, but the hardest to analyze for performance. Specifically the effects around garbage collection were complicated and very hard to tune."
Sources:
"The going word at Facebook is that 'reasonably written C++ code just runs fast,' which underscores the enormous effort spent at optimizing PHP and Java code. Paradoxically, C++ code is more difficult to write than in other languages, but efficient code is a lot easier [to write in C++ than in other languages]."
– Herb Sutter at //build/, quoting Andrei Alexandrescu
Sources:
From the source code of Android's 2.2 Email App:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_selected="true"
android:drawable="@android:color/transparent" />
<item android:state_selected="true"
android:drawable="@android:color/transparent" />
<item android:state_pressed="true" android:state_selected="false"
android:drawable="@android:color/transparent" />
<item android:state_selected="false"
android:drawable="@color/message_item_read" />
</selector>
Nothing more to say...
Existing answers paraphrase the main point quite well.
The main point is that ECMAScript is the bare abstract language, without any domain specific extensions, it's useless in itself. The specification defines only the language and the core objects of it.
While JavaScript and ActionScript and other dialects add the domain specific library to it, so you can use it for something meaningful.
There are many ECMAScript engines, some of them are open source, others are proprietary. You can link them into your program then add your native functions to the global object so your program becomes scriptable. Although most often they are used in browsers.
You simply pass the FormControl an array of validators.
Here's an example showing how you can add validators to an existing FormControl:
this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
Note, this will reset any existing validators you added when you created the FormControl.
I've stumbled upon this problem while trying to augment my WebAPI controllers with extra actions.
Assume you would have
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
[HttpGet]
public void ReSeed()
{
// Your custom action here
}
There are now two methods that satisfy the request for /api/controller which triggers the problem described by TS.
I didn't want to add "dummy" parameters to my additional actions so I looked into default actions and came up with:
[ActionName("builtin")]
public IEnumerable<string> Get()
{
return this.Repository.GetAll();
}
for the first method in combination with the "dual" route binding:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { action = "builtin", id = RouteParameter.Optional },
constraints: new { id = @"\d+" });
config.Routes.MapHttpRoute(
name: "CustomActionApi",
routeTemplate: "api/{controller}/{action}");
Note that even though there is no "action" parameter in the first route template apparently you can still configure a default action allowing us to separate the routing of the "normal" WebAPI calls and the calls to the extra action.
To do this in any ES5-compatible environment, such as Node, Chrome, IE 9+, Firefox 4+, or Safari 5+:
Object.keys(obj).length
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
rsync is work!
#file:
rsync -aqz _vimrc ~/.vimrc
#directory:
rsync -aqz _vim/ ~/.vim
My way
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class ReadAnnotation {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadAnnotation.class);
public static boolean hasIgnoreAnnotation(String fieldName, Class entity) throws NoSuchFieldException {
return entity.getDeclaredField(fieldName).isAnnotationPresent(IgnoreAnnotation.class);
}
public static boolean isSkip(PropertyDescriptor propertyDescriptor, Class entity) {
boolean isIgnoreField;
try {
isIgnoreField = hasIgnoreAnnotation(propertyDescriptor.getName(), entity);
} catch (NoSuchFieldException e) {
LOGGER.error("Can not check IgnoreAnnotation", e);
isIgnoreField = true;
}
return isIgnoreField;
}
public void testIsSkip() throws Exception {
Class<TestClass> entity = TestClass.class;
BeanInfo beanInfo = Introspector.getBeanInfo(entity);
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
System.out.printf("Field %s, has annotation %b", propertyDescriptor.getName(), isSkip(propertyDescriptor, entity));
}
}
}
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
or
for(String value : array)
{
System.out.println(value);
}
The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.
Just for completeness you can do the while loop this way:
int index = 0;
while(index < myArray.length)
{
final String value;
value = myArray[index];
System.out.println(value);
index++;
}
But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).
For global replacement of '/r', this code worked for me.
mystring = mystring.replace(/\/r/g,'');
public function addGetParamToUrl($url, $params)
{
foreach ($params as $param) {
if (strpos($url, "?"))
{
$url .= "&" .http_build_query($param);
}
else
{
$url .= "?" .http_build_query($param);
}
}
return $url;
}
I would like to add that if it's a named list you can simply use within
.
l <- list(a = 1, b = 2)
> within(l, rm(a))
$b
[1] 2
So you can overwrite the original list
l <- within(l, rm(a))
to remove element named a
from list l
.
It will look like this
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
You can use the @Qualifier annotation
From here
Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
class Main {
private Country country;
@Autowired
@Qualifier("country")
public void setCountry(Country country) {
this.country = country;
}
}
This will use the UK add an id to USA bean and use that if you want the USA.
If you want to extract a single file use:
gunzip file.gz
It will extract the file and remove .gz file.
To do this without any headache:
git status
, let's say branch "development".git clone
the project from repository.git checkout development
.rsync
, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1
. You don't have to do this with rsync
of course, but it does it so smooth.The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.
This looks confusing because you are taking long
as a datatype itself.
long
is nothing but just the shorthand for long int
when you are using it alone.
long
is a modifier, you can use it with double
also as long double
.
long
== long int
.
Both of them take 4 bytes.
var result = from x in entity
join y in entity2 on new { x.field1, x.field2 } equals new { y.field1, y.field2 }
If you want to do this by code, you can add the behavior like this:
serviceHost.Description.Behaviors.Remove(
typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });
Far as I know we can't instantiate an abstract class
There's your error right there. Of course you can instantiate an abstract class.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
There's an instance of Animal right there. You instantiate an abstract class by making a concrete class derived from it, and instantiating that. Remember, an instance of a derived concrete class is also an instance of its abstract base class. An instance of Giraffe is also an instance of Animal even if Animal is abstract.
Given that you can instantiate an abstract class, it needs to have a constructor like any other class, to ensure that its invariants are met.
Now, a static class is a class you actually cannot instantiate, and you'll notice that it is not legal to make an instance constructor in a static class.
NSString *string = [NSString stringWithUTF8String:[Data bytes]];
Try this.
SELECT
CASE
WHEN FRUIT = 'A' THEN 'APPLE'
WHEN FRUIT = 'B' THEN 'BANANA'
ELSE 'UNKNOWN FRUIT'
END AS FRUIT
FROM FRUIT_TABLE;
While installing SQL Server, it extracts contents to temp folder under C directory. You can copy that folder after extraction finishes and then use that one for browsing
PHP can be frustrating for this reason. The answers above using global
did not work for me, and it took me awhile to figure out the proper use of use
.
This is correct:
$functionName = function($stuff) use ($globalVar) {
//do stuff
}
$output = $functionName($stuff);
$otherOutput = $functionName($otherStuff);
This is incorrect:
function functionName($stuff) use ($globalVar) {
//do stuff
}
$output = functionName($stuff);
$otherOutput = functionName($otherStuff);
Using your specific example:
$data = 'My data';
$menugen = function() use ($data) {
echo "[" . $data . "]";
}
$menugen();
This deletes only files from ABC (sub-directories are untouched):
Arrays.stream(new File("C:/test/ABC/").listFiles()).forEach(File::delete);
This deletes only files from ABC (and sub-directories):
Files.walk(Paths.get("C:/test/ABC/"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.forEach(File::delete);
^ This version requires handling the IOException
Another way to find out if a program is installed is by using the which
command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:
$ which apache2ctl
/usr/sbin/apache2ctl
And if you searching for PHP try this:
$ which php
/usr/bin/php
If the which
command doesn't give any result it means the software is not installed (or is not in the current $PATH
):
$ which php
$
Just set the parent to display:flex;
and the child to margin-top:auto
. This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.
There is no need to try and calculate a value for margin-top
when you have a height on your parent element or another element greater than your child element of interest within your parent element.
Just wanted to add my 2 cents to this in case this helps anyone, I had a similar problem but needed to remove multiple elements from an array list while it was being iterated over. the highest upvoted answer did it for me for the most part until I ran into errors and realized that the index was greater than the size of the array list in some instances because multiple elements were being removed but the index of the loop didn't keep track of that. I fixed this with a simple check:
ArrayList place_holder = new ArrayList();
place_holder.Add("1");
place_holder.Add("2");
place_holder.Add("3");
place_holder.Add("4");
for(int i = place_holder.Count-1; i>= 0; i--){
if(i>= place_holder.Count){
i = place_holder.Count-1;
}
// some method that removes multiple elements here
}
The upcoming ECMAScript language specification, edition 6, includes Unicode-aware regular expressions. Support must be enabled with the u
modifier on the regex. See Unicode-aware regular expressions in ES6.
Until ES 6 is finished and widely adopted among browser vendors you're still on your own, though. Update: There is now a transpiler named regexpu that translates ES6 Unicode regular expressions into equivalent ES5. It can be used as part of your build process. Try it out online.
Even though JavaScript operates on Unicode strings, it does not implement Unicode-aware character classes and has no concept of POSIX character classes or Unicode blocks/sub-ranges.
Check your expectations here: Javascript RegExp Unicode Character Class tester (Edit: the original page is down, the Internet Archive still has a copy.)
Flagrant Badassery has an article on JavaScript, Regex, and Unicode that sheds some light on the matter.
Also read Regex and Unicode here on SO. Probably you have to build your own "punctuation character class".
Check out the Regular Expression: Match Unicode Block Range builder, which lets you build a JavaScript regular expression that matches characters that fall in any number of specified Unicode blocks.
I just did it for the "General Punctuation" and "Supplemental Punctuation" sub-ranges, and the result is as simple and straight-forward as I would have expected it:
[\u2000-\u206F\u2E00-\u2E7F]
There also is XRegExp, a project that brings Unicode support to JavaScript by offering an alternative regex engine with extended capabilities.
And of course, required reading: mathiasbynens.be - JavaScript has a Unicode problem:
Try adding a BindingResult parameter to methods annotated with @RequestMapping
which have a @ModelAttribute
annotated parameters. After each @ModelAttribute
parameter, Spring looks for a BindingResult in the next parameter position (order is important).
So try changing:
@RequestMapping(method = RequestMethod.POST)
public String loadCharts(HttpServletRequest request, ModelMap model, @ModelAttribute("sideForm") Chart chart)
...
To:
@RequestMapping(method = RequestMethod.POST)
public String loadCharts(@ModelAttribute("sideForm") Chart chart, BindingResult bindingResult, HttpServletRequest request, ModelMap model)
...
I came up with your case. This is how I sort it out
conda create -n tensor flow
Source activate tensorflow
pip
So then the next thing, when you launch it:
Source Activate Tensorflow
Inside the virtual environment just type:
pip install jupyter notebook
pip install pandas
Then you can launch jupyter notebook saying:
jupyter notebook
That's right, but it doesn't change it permanently, but just for current command prompt, if you wanna to change it permanently you have to use for example this:
setx ENV_VAR_NAME "DESIRED_PATH" /m
This will change it permanently and yes you can overwrite it by another batch script.
I am using Visual Studio 2013 Update 2. In my case, I have a web project and a Web Api project and unit test project and other class libraries in a single solution.
I've spent couple of days to solve the problem. Below is the step-by-step solution that I have found.
Newtonsoft.Json
packs from solution by using below query from Package Manager Console ( to get it View > Other Window > Package Manager Console ).uninstall-package newtonsoft.json -force
Newtonsoft.Json
from Package Manager Consoleinstall-package newtonsoft.json
Newtonsoft.Json
, I have encountered with the following error.The 'Newtonsoft.Json 10.0.3' package requires NuGet client version '2.12' or above, but the current NuGet version i s '2.8.50313.46'
Tools > Extensions and Updates... > In left pane.. select Updates > Visual Studio Gallery.
Update the NuGet Package Manager Extension. Follow the steps that are coming afterwards.
Visual Studio will take a restart after that.
Execute step 6 again.
After Installation packages.config will be added with this below line
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net451" />
After installation web.config will be added with this below lines
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
It will execute successfully, if there is no other error.
if you are trying to detect a samsung galaxy s3, then on the phone go to settings -> developer options -> make sure usb debugging is checked
Anyway, the documentation covers all the things.
Once the activity is created, the
onCreateOptionsMenu()
method is called only once, as described above. The system keeps and re-uses theMenu
you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override theonPrepareOptionsMenu()
method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.
E.g.
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if (isFinalized) {
menu.getItem(1).setEnabled(false);
// You can also use something like:
// menu.findItem(R.id.example_foobar).setEnabled(false);
}
return true;
}
On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu()
to request that the system call onPrepareOptionsMenu()
.
Have a look at this solution I came up with
Positioned( child: SizedBox( child: CircularProgressIndicator(), width: 50, height: 50,), left: MediaQuery.of(context).size.width / 2 - 25);
If you code your x axis text categories, list them in a single column, then in adjacent columns list plot points for respective variables against relevant text category code and just leave blank cells against non-relevant text category code, you can scatter plot and get the displayed result. Any questions let me know.
Multiprogramming - This term is used in the context of batch systems. You've got several programs in main memory concurrently. The CPU schedules a time for each one.
I.e. submitting multiple jobs and all of them are loaded into memory and executed according to a scheduling algorithm. Common batch system scheduling algorithms include: First-Come-First-Served, Shortest-Job-First, Shortest-Remaining-Time-Next.
Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.
Try This url with valid userid and access token:
https://graph.facebook.com/{userid}/photos?limit=20&access_token={access_token}
Remove constraint not null
to null
ALTER TABLE 'test' CHANGE COLUMN 'testColumn' 'testColumn' datatype NULL;
You don't tend to execute the make file itself, rather you execute make
, giving it the make file as an argument:
make -f pax.mk
If your make file is actually one of the standard names (like makefile
or Makefile
), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make
man page to see which takes precedence).
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
My suggestion:
$http({
method: 'DELETE',
url: '/roles/' + roleid,
data: {
user: userId
},
headers: {
'Content-type': 'application/json;charset=utf-8'
}
})
.then(function(response) {
console.log(response.data);
}, function(rejection) {
console.log(rejection.data);
});
To dynamically change the color of a text box goto properties, goto font/Color and set the following expression
=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)
Same way for tolerance
=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")
You should be able to override Equals on person to actually do Equals on Person.id. This ought to result in the behavior you're after.
Add .done() to your function
var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
$.ajax({
url: 'api.php',
data: 'id1='+q+'',
dataType: 'json',
async:false,
success: function(data)
{
id = data[0];
vname = data[1];
}
}).done(function(){
printWithAjax();
});
}//end of the for statement
}//end of ajax call function
Use Scalar::Util::looks_like_number()
which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this.
Note that the strings "inf" and "infinity" are treated as numbers.
#!/usr/bin/perl
use warnings;
use strict;
use Scalar::Util qw(looks_like_number);
my @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);
foreach my $expr (@exprs) {
print "$expr is", looks_like_number($expr) ? '' : ' not', " a number\n";
}
Gives this output:
1 is a number
5.25 is a number
0.001 is a number
1.3e8 is a number
foo is not a number
bar is not a number
1dd is not a number
inf is a number
infinity is a number
looks_like_number
This is a really late response, but I came up with this to solve a particular problem I had with DiskInternals LinuxReader appending '.efs_ntfs' to files that it saved to non-NTFS (FAT32) directories :
@echo off
REM %1 is the directory to recurse through and %2 is the file extension to remove
for /R "%1" %%f in (*.%2) do (
REM Path (sans drive) is given by %%~pf ; drive is given by %%~df
REM file name (sans ext) is given by %%~nf ; to 'rename' files, move them
copy "%%~df%%~pf%%~nf.%2" "%%~df%%~pf%%~nf"
echo "%%~df%%~pf%%~nf.%2" copied to "%%~df%%~pf%%~nf"
echo.
)
pause
If your goal is only to take the files and not the folder, the approach I made was to use the file size
as a filter. This property is the current size of the file hosted by AWS. All the folders return 0 in that property.
The following is a C# code using linq but it shouldn't be hard to translate to Java.
var amazonClient = new AmazonS3Client(key, secretKey, region);
var listObjectsRequest= new ListObjectsRequest
{
BucketName = 'someBucketName',
Delimiter = 'someDelimiter',
Prefix = 'somePrefix'
};
var objects = amazonClient.ListObjects(listObjectsRequest);
var objectsInFolder = objects.S3Objects.Where(file => file.Size > 0).ToList();
This is an old question with valuable answers, but I was still a bit confused until I found a real life example that shows the issue with 3NF. Maybe not suitable for an 8-year old child but hope it helps.
Tomorrow I'll meet the teachers of my eldest daughter in one of those quarterly parent/teachers meetings. Here's what my diary looks like (names and rooms have been changed):
Teacher | Date | Room
----------|------------------|-----
Mr Smith | 2018-12-18 18:15 | A12
Mr Jones | 2018-12-18 18:30 | B10
Ms Doe | 2018-12-18 18:45 | C21
Ms Rogers | 2018-12-18 19:00 | A08
There's only one teacher per room and they never move. If you have a look, you'll see that:
(1) for every attribute Teacher
, Date
, Room
, we have only one value per row.
(2) super-keys are: (Teacher, Date, Room)
, (Teacher, Date)
and (Date, Room)
and candidate keys are obviously (Teacher, Date)
and (Date, Room)
.
(Teacher, Room)
is not a superkey because I will complete the table next quarter and I may have a row like this one (Mr Smith did not move!):
Teacher | Date | Room
---------|------------------| ----
Mr Smith | 2019-03-19 18:15 | A12
What can we conclude? (1) is an informal but correct formulation of 1NF. From (2) we see that there is no "non prime attribute": 2NF and 3NF are given for free.
My diary is 3NF. Good! No. Not really because no data modeler would accept this in a DB schema. The Room
attribute is dependant on the Teacher
attribute (again: teachers do not move!) but the schema does not reflect this fact. What would a sane data modeler do? Split the table in two:
Teacher | Date
----------|-----------------
Mr Smith | 2018-12-18 18:15
Mr Jones | 2018-12-18 18:30
Ms Doe | 2018-12-18 18:45
Ms Rogers | 2018-12-18 19:00
And
Teacher | Room
----------|-----
Mr Smith | A12
Mr Jones | B10
Ms Doe | C21
Ms Rogers | A08
But 3NF does not deal with prime attributes dependencies. This is the issue: 3NF compliance is not enough to ensure a sound table schema design under some circumstances.
With BCNF, you don't care if the attribute is a prime attribute or not in 2NF and 3NF rules. For every non trivial dependency (subsets are obviously determined by their supersets), the determinant is a complete super key. In other words, nothing is determined by something else than a complete super key (excluding trivial FDs). (See other answers for formal definition).
As soon as Room
depends on Teacher
, Room
must be a subset of Teacher
(that's not the case) or Teacher
must be a super key (that's not the case in my diary, but thats the case when you split the table).
To summarize: BNCF is more strict, but in my opinion easier to grasp, than 3NF:
Here is my favorite way, which I think is a little less tedious than the "Select for Compare, then Compare With..." steps.
F1
Compare Active File With...This works with any arbitrary files, even ones that are not in the project dir. You can even just create 2 new Untitled files and copy/paste text in there too.
I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:
Your answer (assuming this works, I haven't tried this):
<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
Second option:
@if (Model.Details.Count > 0) {
<div class="details show">
}
else {
<div class="details hide">
}
Third option:
<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
The catch is that input elements are inline. We have to make it block (display:block) before positioning it to center : margin : 0 auto. Please see the code below :
<html>
<head>
<style>
div.wrapper {
width: 300px;
height:300px;
border:1px solid black;
}
input[type="text"] {
display: block;
margin : 0 auto;
}
</style>
</head>
<body>
<div class='wrapper'>
<input type='text' name='ok' value='ok'>
</div>
</body>
</html>
But if you have a div which is positioned = absolute then we need to do the things little bit differently.Now see this!
<html>
<head>
<style>
div.wrapper {
position: absolute;
top : 200px;
left: 300px;
width: 300px;
height:300px;
border:1px solid black;
}
input[type="text"] {
position: relative;
display: block;
margin : 0 auto;
}
</style>
</head>
<body>
<div class='wrapper'>
<input type='text' name='ok' value='ok'>
</div>
</body>
</html>
Hoping this can be helpful.Thank you.
I did all the stuff above mentioned for same problem but nothing worked. I tried below it worked 100%. Simple config changes.
user@ubuntu:~$ ulimit -n 65535
user@ubuntu:~$ ulimit -n
1024
user@ubuntu:~$ sudo nano /etc/sysctl.conf
fs.file-max = 65535
user@ubuntu:~$ sudo sysctl -p
user@ubuntu:~$ sudo vim /etc/security/limits.conf
root soft nproc 65535
root hard nproc 65535
root soft nofile 65535
root hard nofile 65535
user@ubuntu:~$ sudo vim /etc/pam.d/common-session
session required pam_limits.so
user@ubuntu:~$ ulimit -n
65535
DefaultLimitNOFILE=65535
to /etc/systemd/system.conf and /etc/systemd/user.conf
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
Use:
if [[ `command --help` ]]; then
echo "This command exists"
else
echo "This command does not exist";
fi
Put in a working switch, such as "--help" or "-v" in the if
check: if [[ command --help
]]; then
While using Spring Boot 2.2 I run into a similiar error message and while googling my error message
No converter for [class java.util.ArrayList] with preset Content-Type 'null'
this question here is on top, but all answers here did not work for me, so I think it's a good idea to add the answer I found myself:
I had to add the following dependencies to the pom.xml
:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.11.1</version>
</dependency>
After this I need to add the following to the WebApplication class:
@SpringBootApplication
public class WebApplication
{
// ...
@Bean
public HttpMessageConverter<Object> createXmlHttpMessageConverter()
{
final MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
final XStreamMarshaller xstreamMarshaller = new XStreamMarshaller();
xstreamMarshaller.setAutodetectAnnotations(true);
xmlConverter.setMarshaller(xstreamMarshaller);
xmlConverter.setUnmarshaller(xstreamMarshaller);
return xmlConverter;
}
}
Last but not least within my @Controller
I used:
@GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType. APPLICATION_JSON_VALUE})
@ResponseBody
public List<MeterTypeEntity> listXmlJson(final Model model)
{
return this.service.list();
}
So now I got JSON and XML return values depending on the requests Accept
header.
To make the XML output more readable (remove the complete package name from tag names) you could also add @XStreamAlias
the following to your entity class:
@Table("ExampleTypes")
@XStreamAlias("ExampleType")
public class ExampleTypeEntity
{
// ...
}
Hopefully this will help others with the same problem.
As mentioned here, there are possibilities to get the size of primitive types through their wrappers.
e.g. for a long
this could be Long.SIZE / Byte.SIZE
from java 1.5 (as mentioned by zeodtr already) or Long.BYTES
as from java 8
For some databases, you can just explicitly insert a NULL
into the auto_increment
column:
INSERT INTO table_name VALUES (NULL, 'my name', 'my group')
You can use SUMIFS
like this
=SUM(SUMIFS(Quote_Value,Salesman,"JBloggs",Days_To_Close,"<=90",Quote_Month,{"Oct-13","Nov-13","Dec-13"}))
The SUMIFS
function will return an "array" of 3 values (one total each for "Oct-13", "Nov-13" and "Dec-13"), so you need SUM
to sum that array and give you the final result.
Be careful with this syntax, you can only have at most two criteria within the formula with "OR" conditions...and if there are two then in one you must separate the criteria with commas, in the other with semi-colons.
If you need more you might use SUMPRODUCT
with MATCH
, e.g. in your case
=SUMPRODUCT(Quote_Value,(Salesman="JBloggs")*(Days_To_Close<=90)*ISNUMBER(MATCH(Quote_Month,{"Oct-13","Nov-13","Dec-13"},0)))
In that version you can add any number of "OR" criteria using ISNUMBER/MATCH
You need to use table-layout:fixed
in order for CSS ellipsis to work on the table cells.
.table {
table-layout:fixed;
}
.table td {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The question is simply asked wrong. You don't make an alias that takes parameters because alias
just adds a second name for something that already exists. The functionality the OP wants is the function
command to create a new function. You do not need to alias the function as the function already has a name.
I think you want something like this :
function trash() { mv "$@" ~/.Trash; }
That's it! You can use parameters $1, $2, $3, etc, or just stuff them all with $@
numba
module for speed up.On big datasets (500k >
) pd.cut
can be quite slow for binning data.
I wrote my own function in numba
with just in time compilation, which is roughly 16x
faster:
from numba import njit
@njit
def cut(arr):
bins = np.empty(arr.shape[0])
for idx, x in enumerate(arr):
if (x >= 0) & (x < 1):
bins[idx] = 1
elif (x >= 1) & (x < 5):
bins[idx] = 2
elif (x >= 5) & (x < 10):
bins[idx] = 3
elif (x >= 10) & (x < 25):
bins[idx] = 4
elif (x >= 25) & (x < 50):
bins[idx] = 5
elif (x >= 50) & (x < 100):
bins[idx] = 6
else:
bins[idx] = 7
return bins
cut(df['percentage'].to_numpy())
# array([5., 5., 7., 5.])
Optional: you can also map it to bins as strings:
a = cut(df['percentage'].to_numpy())
conversion_dict = {1: 'bin1',
2: 'bin2',
3: 'bin3',
4: 'bin4',
5: 'bin5',
6: 'bin6',
7: 'bin7'}
bins = list(map(conversion_dict.get, a))
# ['bin5', 'bin5', 'bin7', 'bin5']
Speed comparison:
# create dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)
dfbig.shape
# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())
# 38 ms ± 616 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)
# 215 ms ± 9.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Git just stores the contents of the link (i.e. the path of the file system object that it links to) in a 'blob' just like it would for a normal file. It then stores the name, mode and type (including the fact that it is a symlink) in the tree object that represents its containing directory.
When you checkout a tree containing the link, it restores the object as a symlink regardless of whether the target file system object exists or not.
If you delete the file that the symlink references it doesn't affect the Git-controlled symlink in any way. You will have a dangling reference. It is up to the user to either remove or change the link to point to something valid if needed.
Here's a video that will show you, step-by-step, how to export data to Excel. It's a great solution for 'one-off' problems where you need to export to Excel:
Ad-Hoc Reporting
Try this regexp
^\s*(for|while)\s*
\(
(?P<balanced>
[^()]*
|
(?P=balanced)
\)
\s*;\s
I removed the wrapping \( \)
around (?P=balanced)
and moved the *
to behind the any not paren sequence. I have had this work with boost xpressive, and rechecked that website (Xpressive) to refresh my memory.
Rename it to .zip, then extract it.
For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...
Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.
So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937
set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)
table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction
#Let's make a matrix with tons of columns
Data <- as.data.frame(
matrix(
sample(letters[1:3],2000,replace=T),
ncol=25
)
)
# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]
# say you need to know which ones are associated with each other.
out <- apply( combn(columns,2),2,function(x){
chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
})
out <- cbind(as.data.frame(t(combn(vars,2))),out)
Then you should get :
> out
V1 V2 out
1 V3 V7 0.8116733
2 V3 V11 0.1096903
3 V3 V24 0.1653670
4 V7 V11 0.3629871
5 V7 V24 0.4947797
6 V11 V24 0.7259321
Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
matrix.size
according to the numpy docs returns the Number of elements in the array.
Hope that helps.
Including this in the read.csv
command worked for me: strip.white = TRUE
(I found this solution here.)
Try $_SERVER['SERVER_NAME']
.
Tips: Create a PHP file that calls the function phpinfo()
and see the "PHP Variables" section. There are a bunch of useful variables we never think of there.
new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );
The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)
Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.
It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.
Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.
What about /disable
, and /enable
switch for a /change
command?
schtasks.exe /change /s <machine name> /tn <task name> /disable
schtasks.exe /change /s <machine name> /tn <task name> /enable
The best way is probably to use the list method .index.
For the objects in the list, you can do something like:
def __eq__(self, other):
return self.Value == other.Value
with any special processing you need.
You can also use a for/in statement with enumerate(arr)
Example of finding the index of an item that has value > 100.
for index, item in enumerate(arr):
if item > 100:
return index, item
In addition to all the answers above:
If you are on Android 6.0+ (API Level 23+) you have to explicitly ask for permission to access external storage. Simply having
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
in your manifest won't be enough. You also have actively request the permission in your activity:
//check for permission
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
//ask for permission
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMISSION_CODE);
}
I recommend reading this: http://developer.android.com/training/permissions/requesting.html#perm-request
Python 3: new exec (execfile dropped) !
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0's changelog and Hi-Angels comment suggest:
use
exec(open(<filename.py>).read())
instead of
execfile(<filename.py>)
This is an issue of selector specificity. (The selector .selected
is less specific than ul.nav li
.)
To fix, use as much specificity in the overriding rule as in the original:
ul.nav li {
background-color:blue;
}
ul.nav li.selected {
background-color:red;
}
You might also consider nixing the ul
, unless there will be other .nav
s. So:
.nav li {
background-color:blue;
}
.nav li.selected {
background-color:red;
}
That's a bit cleaner, less typing, and fewer bits.
I was able to achieve this with a nested mapping of the two arrays and updating the initial array:
member.map(mem => {
return memberInfo.map(info => {
if (info.id === mem.userId) {
mem.date = info.date;
return mem;
}
}
}
Working solution for heroku is here http://kennethjiang.blogspot.com/2014/07/set-up-cors-in-cloudfront-for-custom.html (quotes follow):
Below is exactly what you can do if you are running your Rails app in Heroku and using Cloudfront as your CDN. It was tested on Ruby 2.1 + Rails 4, Heroku Cedar stack.
font_assets
to Gemfile .bundle install
config.font_assets.origin = '*'
to config/application.rb
. If you want more granular control, you can add different origin values to different environment, e.g., config/config/environments/production.rb
curl -I http://localhost:3000/assets/your-custom-font.ttf
In Cloudfront, select your distribution, under "behavior" tab, select and edit the entry that controls your fonts delivery (for most simple Rails app you only have 1 entry here). Change Forward Headers from "None" to "Whilelist". And add the following headers to whitelist:
Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Max-Age
Save it and that's it!
Caveat: I found that sometimes Firefox wouldn't not refresh the fonts even if CORS error is gone. In this case keep refreshing the page a few times to convince Firefox that you are really determined.
If you want to select an individual hidden field, you can select it through the different selectors of jQuery :
<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/>
$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class
What i have also noticed is that you have to save the file as Unicode
, UTF-8
, no BOM
in an Windows format with CRLF
(Carriage Return, Line Feed). Because if you don't, the import will break. (Saying something about weird chars in the file)
Good luck :) Sid
Question is quite old, but I created some possible solution how to create abstract "class" and block creation of object that type.
//our Abstract class_x000D_
var Animal=function(){_x000D_
_x000D_
this.name="Animal";_x000D_
this.fullname=this.name;_x000D_
_x000D_
//check if we have abstract paramater in prototype_x000D_
if (Object.getPrototypeOf(this).hasOwnProperty("abstract")){_x000D_
_x000D_
throw new Error("Can't instantiate abstract class!");_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
};_x000D_
_x000D_
//very important - Animal prototype has property abstract_x000D_
Animal.prototype.abstract=true;_x000D_
_x000D_
Animal.prototype.hello=function(){_x000D_
_x000D_
console.log("Hello from "+this.name);_x000D_
};_x000D_
_x000D_
Animal.prototype.fullHello=function(){_x000D_
_x000D_
console.log("Hello from "+this.fullname);_x000D_
};_x000D_
_x000D_
//first inheritans_x000D_
var Cat=function(){_x000D_
_x000D_
Animal.call(this);//run constructor of animal_x000D_
_x000D_
this.name="Cat";_x000D_
_x000D_
this.fullname=this.fullname+" - "+this.name;_x000D_
_x000D_
};_x000D_
_x000D_
Cat.prototype=Object.create(Animal.prototype);_x000D_
_x000D_
//second inheritans_x000D_
var Tiger=function(){_x000D_
_x000D_
Cat.call(this);//run constructor of animal_x000D_
_x000D_
this.name="Tiger";_x000D_
_x000D_
this.fullname=this.fullname+" - "+this.name;_x000D_
_x000D_
};_x000D_
_x000D_
Tiger.prototype=Object.create(Cat.prototype);_x000D_
_x000D_
//cat can be used_x000D_
console.log("WE CREATE CAT:");_x000D_
var cat=new Cat();_x000D_
cat.hello();_x000D_
cat.fullHello();_x000D_
_x000D_
//tiger can be used_x000D_
_x000D_
console.log("WE CREATE TIGER:");_x000D_
var tiger=new Tiger();_x000D_
tiger.hello();_x000D_
tiger.fullHello();_x000D_
_x000D_
_x000D_
console.log("WE CREATE ANIMAL ( IT IS ABSTRACT ):");_x000D_
//animal is abstract, cannot be used - see error in console_x000D_
var animal=new Animal();_x000D_
animal=animal.fullHello();
_x000D_
As You can see last object give us error, it is because Animal in prototype has property abstract
. To be sure it is Animal not something which has Animal.prototype
in prototype chain I do:
Object.getPrototypeOf(this).hasOwnProperty("abstract")
So I check that my closest prototype object has abstract
property, only object created directly from Animal
prototype will have this condition on true. Function hasOwnProperty
checks only properties of current object not his prototypes, so this gives us 100% sure that property is declared here not in prototype chain.
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain. More about it:
In my proposition we not have to change constructor
every time after Object.create
like it is in current best answer by @Jordão.
Solution also enables to create many abstract classes in hierarchy, we need only to create abstract
property in prototype.
The second part of your question is answered well. Here is the answer for the first part: How to output multiple files with webpack:
entry: {
outputone: './source/fileone.jsx',
outputtwo: './source/filetwo.jsx'
},
output: {
path: path.resolve(__dirname, './wwwroot/js/dist'),
filename: '[name].js'
},
This will generate 2 files: outputone.js und outputtwo.js in the target folder.
Go to file "settings.json" and disable the Python pydocstyle
:
"python.linting.pydocstyleEnabled": false
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
A POCO follows the rules of OOP. It should (but doesn't have to) have state and behavior. POCO comes from POJO, coined by Martin Fowler [anecdote here]. He used the term POJO as a way to make it more sexy to reject the framework heavy EJB implementations. POCO should be used in the same context in .Net. Don't let frameworks dictate your object's design.
A DTO's only purpose is to transfer state, and should have no behavior. See Martin Fowler's explanation of a DTO for an example of the use of this pattern.
Here's the difference: POCO describes an approach to programming (good old fashioned object oriented programming), where DTO is a pattern that is used to "transfer data" using objects.
While you can treat POCOs like DTOs, you run the risk of creating an anemic domain model if you do so. Additionally, there's a mismatch in structure, since DTOs should be designed to transfer data, not to represent the true structure of the business domain. The result of this is that DTOs tend to be more flat than your actual domain.
In a domain of any reasonable complexity, you're almost always better off creating separate domain POCOs and translating them to DTOs. DDD (domain driven design) defines the anti-corruption layer (another link here, but best thing to do is buy the book), which is a good structure that makes the segregation clear.
GPS is generally more accurate than network but sometimes GPS is not available, therefore you might need to switch between the two.
A good start might be to look at the android dev site. They had a section dedicated to determining user location and it has all the code samples you need.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
The Content
table likely to have multiple duplicate Application
values that can't be mapped to Libraries
. Is it possible to drop the Application
column from the Libraries
Primary Key Index and add it as a Unique Key Index instead?
For those using objects that are not an Array
or even array-like, you can build your own iterable easily so you can still use for of
for things like localStorage
which really only have a length
:
function indexerator(length) {
var output = new Object();
var index = 0;
output[Symbol.iterator] = function() {
return {next:function() {
return (index < length) ? {value:index++} : {done:true};
}};
};
return output;
}
Then just feed it a number:
for (let index of indexerator(localStorage.length))
console.log(localStorage.key(index))
We've started to use Find Bugs to help identify some of the funk in our codebase's target-rich environment for refactorings. I would also consider Structure 101 to identify spots in your codebase's architecture that are too complicated, so you know where the real swamps are.
Here is some code:
private void dgvStandingOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvStandingOrder.Columns[e.ColumnIndex].Name == "IsSelected" && dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
bool isChecked = (bool)dgvStandingOrder[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
if (isChecked == false)
{
dgvStandingOrder.Rows[e.RowIndex].Cells["Status"].Value = "";
}
dgvStandingOrder.EndEdit();
}
}
private void dgvStandingOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgvStandingOrder_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
{
dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
Swapping the values from 1st position to till the end of the list, this code loops for ( n*n-1)/2 times. Each time it pushes the greater value to the greater index starting from Zero index.
list2 = [40,-5,10,2,0,-4,-10]
for l in range(len(list2)):
for k in range(l+1,len(list2)):
if list2[k] < list2[l]:
list2[k] , list2[l] = list2[l], list2[k]
print(list2)
Can't* believe this question has existed for 9 years without anyone suggesting a simple recursive function:
from datetime import datetime, timedelta
def walk_days(start_date, end_date):
if start_date <= end_date:
print(start_date.strftime("%Y-%m-%d"))
next_date = start_date + timedelta(days=1)
walk_days(next_date, end_date)
#demo
start_date = datetime(2009, 5, 30)
end_date = datetime(2009, 6, 9)
walk_days(start_date, end_date)
Output:
2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09
Edit: *Now I can believe it -- see Does Python optimize tail recursion? . Thank you Tim.
There are several key differences.
update
is used on a queryset, so it is possible to update multiple objects at once.
As @FallenAngel pointed out, there are differences in how custom save()
method triggers, but it is also important to keep in mind signals
and ModelManagers
. I have build a small testing app to show some valuable differencies. I am using Python 2.7.5, Django==1.7.7 and SQLite, note that the final SQLs may vary on different versions of Django and different database engines.
Ok, here's the example code.
models.py
:
from __future__ import print_function
from django.db import models
from django.db.models import signals
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
__author__ = 'sobolevn'
class CustomManager(models.Manager):
def get_queryset(self):
super_query = super(models.Manager, self).get_queryset()
print('Manager is called', super_query)
return super_query
class ExtraObject(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TestModel(models.Model):
name = models.CharField(max_length=30)
key = models.ForeignKey('ExtraObject')
many = models.ManyToManyField('ExtraObject', related_name='extras')
objects = CustomManager()
def save(self, *args, **kwargs):
print('save() is called.')
super(TestModel, self).save(*args, **kwargs)
def __unicode__(self):
# Never do such things (access by foreing key) in real life,
# because it hits the database.
return u'{} {} {}'.format(self.name, self.key.name, self.many.count())
@receiver(pre_save, sender=TestModel)
@receiver(post_save, sender=TestModel)
def reicever(*args, **kwargs):
print('signal dispatched')
views.py
:
def index(request):
if request and request.method == 'GET':
from models import ExtraObject, TestModel
# Create exmple data if table is empty:
if TestModel.objects.count() == 0:
for i in range(15):
extra = ExtraObject.objects.create(name=str(i))
test = TestModel.objects.create(key=extra, name='test_%d' % i)
test.many.add(test)
print test
to_edit = TestModel.objects.get(id=1)
to_edit.name = 'edited_test'
to_edit.key = ExtraObject.objects.create(name='new_for')
to_edit.save()
new_key = ExtraObject.objects.create(name='new_for_update')
to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key)
# return any kind of HttpResponse
That resuled in these SQL queries:
# to_edit = TestModel.objects.get(id=1):
QUERY = u'SELECT "main_testmodel"."id", "main_testmodel"."name", "main_testmodel"."key_id"
FROM "main_testmodel"
WHERE "main_testmodel"."id" = %s LIMIT 21'
- PARAMS = (u'1',)
# to_edit.save():
QUERY = u'UPDATE "main_testmodel" SET "name" = %s, "key_id" = %s
WHERE "main_testmodel"."id" = %s'
- PARAMS = (u"'edited_test'", u'2', u'1')
# to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key):
QUERY = u'UPDATE "main_testmodel" SET "name" = %s, "key_id" = %s
WHERE "main_testmodel"."id" = %s'
- PARAMS = (u"'updated_name'", u'3', u'2')
We have just one query for update()
and two for save()
.
Next, lets talk about overriding save()
method. It is called only once for save()
method obviously. It is worth mentioning, that .objects.create()
also calls save()
method.
But update()
does not call save()
on models. And if no save()
method is called for update()
, so the signals are not triggered either. Output:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
# TestModel.objects.get(id=1):
Manager is called [<TestModel: edited_test new_for 0>]
Manager is called [<TestModel: edited_test new_for 0>]
save() is called.
signal dispatched
signal dispatched
# to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key):
Manager is called [<TestModel: edited_test new_for 0>]
As you can see save()
triggers Manager
's get_queryset()
twice. When update()
only once.
Resolution. If you need to "silently" update your values, without save()
been called - use update
. Usecases: last_seen
user's field. When you need to update your model properly use save()
.
Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/
Usage:
$('selector').fixedHeaderTable({ fixedColumn: 1 });
Set the fixedColumn
option if you want any number of columns to be also fixed for horizontal scrolling.
EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.
EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)
For a field separator of any number 2
through 5
or letter a
or #
or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:
awk -F'[2-5a# ]{2,6}' ...
I am sure variations of this exist using ( ) and parameters
Try to use toISOString(). It returns string in ISO8601 format.
from javascript
$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
console.log(result);
});
from c#
[HttpGet]
public JsonResult DoGet(DateTime date)
{
return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
Not in the submit event handler itself, no.
But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.
Here's a full example (using jQuery for brevity)
<html>
<head>
<title>Test Page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(function($) {
var submitActor = null;
var $form = $('#test');
var $submitActors = $form.find('input[type=submit]');
$form.submit(function(event) {
if (null === submitActor) {
// If no actor is explicitly clicked, the browser will
// automatically choose the first in source-order
// so we do the same here
submitActor = $submitActors[0];
}
console.log(submitActor.name);
// alert(submitActor.name);
return false;
});
$submitActors.click(function(event) {
submitActor = this;
});
});
</script>
</head>
<body>
<form id="test">
<input type="text" />
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
</form>
</body>
</html>
This might be useful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS
Use hydrate.stringify
to serialize the object and hydrate.parse
to deserialize.
You need:
#include <string.h> /* memset */
#include <unistd.h> /* close */
in your code.
References: POSIX for close
, the C standard for memset
.
JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.
Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .
To stop this behaviour we need to return the function to onClick.
The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!
Use -
onClick={() => { this.props.removeTaskFunction(todo) }}
which means-
var onClick = function() {
return this.props.removeTaskFunction(todo);
}.bind(this);
It is an abbreviation for 'optional' , used for optional software in some distros.
Here is a solution where you set the ylabel of one of the plots and adjust the position of it so it is centered vertically. This way you avoid problems mentioned by KYC.
import numpy as np
import matplotlib.pyplot as plt
def set_shared_ylabel(a, ylabel, labelpad = 0.01):
"""Set a y label shared by multiple axes
Parameters
----------
a: list of axes
ylabel: string
labelpad: float
Sets the padding between ticklabels and axis label"""
f = a[0].get_figure()
f.canvas.draw() #sets f.canvas.renderer needed below
# get the center position for all plots
top = a[0].get_position().y1
bottom = a[-1].get_position().y0
# get the coordinates of the left side of the tick labels
x0 = 1
for at in a:
at.set_ylabel('') # just to make sure we don't and up with multiple labels
bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
bboxes = bboxes.inverse_transformed(f.transFigure)
xt = bboxes.x0
if xt < x0:
x0 = xt
tick_label_left = x0
# set position of label
a[-1].set_ylabel(ylabel)
a[-1].yaxis.set_label_coords(tick_label_left - labelpad,(bottom + top)/2, transform=f.transFigure)
length = 100
x = np.linspace(0,100, length)
y1 = np.random.random(length) * 1000
y2 = np.random.random(length)
f,a = plt.subplots(2, sharex=True, gridspec_kw={'hspace':0})
a[0].plot(x, y1)
a[1].plot(x, y2)
set_shared_ylabel(a, 'shared y label (a. u.)')
Python provides in-built functions for easily copying files using the Operating System Shell utilities.
Following command is used to Copy File
shutil.copy(src,dst)
Following command is used to Copy File with MetaData Information
shutil.copystat(src,dst)
I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too
var countries = ['Canada','Us','France','Italy'];
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});
Use the following:
new Date().toLocaleDateString();
Then as per your requirement just change locale for your application:
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);
//Provide the locale in any Module or Component by the LOCALE_ID token.
providers: [
{provide: LOCALE_ID, useValue: 'fr'}
]
What is the reason for getting each of them and any thought process on how to deal with such errors?
They're closely related. A ClassNotFoundException
is thrown when Java went looking for a particular class by name and could not successfully load it. A NoClassDefFoundError
is thrown when Java went looking for a class that was linked into some existing code, but couldn't find it for one reason or another (e.g., wrong classpath, wrong version of Java, wrong version of a library) and is thoroughly fatal as it indicates that something has gone Badly Wrong.
If you've got a C background, a CNFE is like a failure to dlopen()
/dlsym()
and an NCDFE is a problem with the linker; in the second case, the class files concerned should never have been actually compiled in the configuration you're trying to use them.
<textarea rows="4" cols="50"></textarea>
It is equivalent to:
textarea {
height: 4em;
width: 50em;
}
where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.
Tested on Android Studio 0.8.6 - 3.5
Using this method you can have Java modules and Android modules in the same project and also have the ability to compile and run Java modules as stand alone Java projects.
Now if you click run, this should compile and run your Java module.
If you get the error Error: Could not find or load main class...
, just enter your main class (as you've done in step 7) again even if the field is already filled in. Click Apply and then click Ok.
My usage case: My Android app relies on some precomputed files to function. These precomputed files are generated by some Java code. Since these two things go hand in hand, it makes the most sense to have both of these modules in the same project.
NEW - How to enable Kotlin in your standalone project
If you want to enable Kotlin inside your standalone project, do the following.
Continuing from the last step above, add the following code to your project level build.gradle
(lines to add are denoted by >>>):
buildscript {
>>> ext.kotlin_version = '1.2.51'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
>>> classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
...
Add the following code to your module level build.gradle
(lines to add are denoted by >>>):
apply plugin: 'java-library'
>>> apply plugin: 'kotlin'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
>>> implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
>>> runtimeClasspath files(compileKotlin.destinationDir)
}
...
Bonus step: Convert your main function to Kotlin! Simply change your main class to:
object Main {
...
@JvmStatic
fun main(args: Array<String>) {
// do something
}
...
}
The same issue with 7.1
apt-get install php7.1-json
sudo nano /etc/php/7.1/mods-available/json.ini
As far as I know there is no “native” PowerShell way of getting this information. And perhaps it is rather the .NET limitation than PowerShell.
Here is the suggestion to add this functionality to the version next:
The WMI workaround is also there, just in case. I use this WMI solution for my tasks and it works.
You can kill the process which is running the container.
With this command you can list the processes related with the docker container:
ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')
Now you have the process ids to kill with kill or kill -9.
When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]
You can create a new file, setenv.sh (or setenv.bat) inside tomcats bin directory and add following line there
export CLASSPATH=$CLASSPATH:/XX/xx/PATH_TO_DIR
In the second you can access the attributes of the exception object:
>>> def catch():
... try:
... asd()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)
But it doesn't catch BaseException
or the system-exiting exceptions SystemExit
, KeyboardInterrupt
and GeneratorExit
:
>>> def catch():
... try:
... raise BaseException()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch
BaseException
Which a bare except does:
>>> def catch():
... try:
... raise BaseException()
... except:
... pass
...
>>> catch()
>>>
See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.
Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.
Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:
/link/mybackend/?field1=value1&field2=value2&field3=value3
and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET
.
So your urlconf would be:
url(r'^link/(?P<backend>\w+?)/$', my_function)
and the view would look like:
def my_function(request, backend):
data = request.GET
and the reverse would be (after importing urllib
):
return "%s?%s" % (redirect('my_function', args=(backend,)),
urllib.urlencode(form.cleaned_data))
Edited after comment
The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.
If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.
That said, if all you want to do is store the data, then just put it in the session:
request.session['temp_data'] = form.cleaned_data
For Xamarin Developers, you can use:
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
With introduction of ContraintLayout, it's possible to implement with Guidelines:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.eugene.test1.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#AAA"
android:text="TextView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toTopOf="@+id/guideline" />
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
</android.support.constraint.ConstraintLayout>
You can read more in this article Building interfaces with ConstraintLayout.
On linux (Ubuntu in my case) just install gradle:
sudo apt-get install gradle
Edit: It seems as though ubuntu repo only has gradle 2.10, for newer versions: https://www.vultr.com/docs/how-to-install-gradle-on-ubuntu-16-10
>>> print "%r, %r" % (True, False)
True, False
This is not specific to boolean values - %r
calls the __repr__
method on the argument. %s
(for str
) should also work.
TIMESTAMP is four bytes vs eight bytes for DATETIME.
Timestamps are also lighter on the database and indexed faster.
The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is ’1000-01-01 00:00:00' to ’9999-12-31 23:59:59'.
The TIMESTAMP data type has a range of ’1970-01-01 00:00:01' UTC to ’2038-01-09 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in.
Using NetBeans 7.0:
If you fix imports before R.java has been generated for your project (before building it the first time) it will add the line:
import android.R;
which will override the local R.java that you are trying to reference.
Deleting that line resolved the errors for me.
As an addition to mklement0's excellent answer:
Almost all executables accept \"
as an escaped "
. Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal "
to some process, assign \"
to an environment variable, and then use that variable, whenever you need to pass a quote. Example:
SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"
Note SETLOCAL ENABLEDELAYEDEXPANSION
seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON
.
If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:
::region without DELAYEDEXPANSION
SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL
::region without DELAYEDEXPANSION
If you want to pass dynamic content from a variable that contains quotes that are escaped as ""
you can replace ""
with \"
on expansion:
SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL
This replacement is not safe with %...%
style expansion!
In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!"
is the safe version.
If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:
Using \"
from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)
To achieve this, one precedes any quote with a caret (^"
), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"
). ALL shell meta characters must be escaped with ^
as well, e.g. &
=> ^&
; |
=> ^|
; >
=> ^>
; etc.
Example:
child ^"malicious argument\^"^&whoami^"
Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"
To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe
(This is impossible if the variable can contain quotes - don't write %var:""=\"%
). To achieve this, the last "
before the variable and the first "
after the variable are not ^
-escaped. cmd-metacharacters between those two "
must not be escaped. Example:
foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"
This isn't safe, if %dynamic_content%
can contain unmatched quotes.
Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.
Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.
EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)
public class Job
{
public string id { get; set; }
public string position_title { get; set; }
public string organization_name { get; set; }
public string rate_interval_code { get; set; }
public int minimum { get; set; }
public int maximum { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public List<string> locations { get; set; }
public string url { get; set; }
}
And an edit to your code:
List<Job> model = null;
var client = new HttpClient();
var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);
});
task.Wait();
This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.
EDIT 2:
There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:
http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
On Salesforce platform this error is caused by /
, the solution is to escape these as //
.
find /path -type f \( -iname "*.jpg" -o -name "*.jpeg" -o -iname "*gif" \)
<html>
<head>
<title>Page</title>
</head>
<body>
<a href="./">Folder directory</a>
</body>
</html>
Run the JVM with -XX:MaxHeapSize=512m
(or any big number as you need) (or -Xmx512m
for short)
While loop is a bit faster than for loop.
var len = arr.length;
while (len--) {
// blah blah
}
Use while loop instead
If you're using HTML5, you should use the input type number
. If you are using xhtml or html 4, input type should be text
.
None of the above worked for me but the following did:
Disable the checkbox (Show plots in tool window) in pycharm settings > Tools > Python Scientific
.
I received the error No PyQt5 module found
. Went ahead with the installation of PyQt5
using :
sudo apt-get install python3-pyqt5
Beware that for some only first step is enough and works.
It's an asynchronous request, meaning once it's sent it's out there.
In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.
Otherwise, simply ignore the AJAX response.
in addition to UseSsl, you have to include smtp port 587 to make it work.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
For Tomcat v8.5.4 and above, the file <tomcat>/webapps/manager/META-INF/context.xml
has been adjusted:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
</Context>
Change this file to comment the Valve
:
<Context antiResourceLocking="false" privileged="true" >
<!--
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
-->
</Context>
After that, refresh your browser (not need to restart Tomcat), you can see the manager page.
If you have bg.png as your background image then simply:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"/>
</RelativeLayout>
$('#modal').modal('hide');
//hide the modal
$('body').removeClass('modal-open');
//modal-open class is added on body so it has to be removed
$('.modal-backdrop').remove();
//need to remove div with modal-backdrop class
The combined answer for writing to a file can be;
MemoryStream ms = new MemoryStream();
FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
Your app is crashing at:
welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");
because mPlayer=null
.
You forgot to initialize Player mPlayer
in your PlayGame Activity.
mPlayer = new Player(context,"");
Use /usr/libexec/java_home
; I found these alias and function to be pretty useful in my ~/.profile
:
alias java_ls='/usr/libexec/java_home -V 2>&1 | cut -s -d , -f 1 | cut -c 5-'
function java_use() {
export JAVA_HOME=$(/usr/libexec/java_home -v $1)
java -version
}
If you want to move a non-checked out branch to another commit, the easiest way is running the git branch command with -f option, which determines where the branch HEAD should be pointing to:
git branch -f
Be careful as this won't work if the branch you are trying to move is your current branch. To move a branch pointer, run the following command: git update-ref -m "reset: Reset to " refs/heads/
The git update-ref command updates the object name stored in a ref safely.
Hope, my answer helped you.The source of information is this snippet.
import Tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()
Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.
The wrapper classes in the Java API serve two primary purposes:
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd
, although in practice almost all browsers also support yyyy/mm/dd
as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy
, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split
splits a string on the given delimiter. Then we use parseInt
to convert the strings into numbers, and we use the new Date
constructor to build a Date
from those parts: The third part will be the year, the second part the month, and the first part the day. Date
uses zero-based month numbers, and so we have to subtract one from the month number.
Yes - just explicitly provide the path to java.exe. For instance:
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
The easiest way to do this for a running command shell is something like:
set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
For example, here's a complete session showing my default JVM, then the change to the path, then the new one:
c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)
c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%
c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)
This won't change programs which explicitly use JAVA_HOME though.
Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.
For posterity you might want to use regular expressions as an alternative. Pretty good browser support as well (ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Browser_compatibility)
Try this
if (foo.toString().match(/^(1|3|12)$/)) {
document.write('Regex me IN<br>');
} else {
document.write('Regex me OUT<br>');
}
It's mainly a matter of choice most of the time. It's a matter of preference.
Note however that if you have numeric keys for example, that you can't do:
mydict = dict(1="foo", 2="bar")
You have to do:
mydict = {"1":"foo", "2":"bar"}
With array_flip()
it could look like this:
$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);
With array_unique()
- like this:
$opts[] = $newValue;
$opts = array_values(array_unique($opts));
Notice that array_values(...)
— you need it if you're exporting array to JavaScript in JSON form. array_unique()
alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.
>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"
>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"
Environment: Django 2.2
from django.template.defaulttags import register
@register.filter(name='lookup')
def lookup(value, arg):
return value.get(arg)
I put this code in a file named template_filters.py in my project folder named portfoliomgr
No matter where you put your filter code, make sure you have __init__.py in that folder
Add that file to libraries section in templates section in your projectfolder/settings.py file. For me, it is portfoliomgr/settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries':{
'template_filters': 'portfoliomgr.template_filters',
}
},
},
]
In your html code load the library
{% load template_filters %}
LogisticRegression
is not for regression but classification !
The Y
variable must be the classification class,
(for example 0
or 1
)
And not a continuous
variable,
that would be a regression problem.
By default ls
sorts the names, which can take a while if there are a lot of them. Also there will be no output until all of the names are read and sorted. Use the ls -f
option to turn off sorting.
ls -f | wc -l
Note that this will also enable -a
, so .
, ..
, and other files starting with .
will be counted.
Mathematically, to get percentage from two numbers:
percentage = (yourNumber / totalNumber) * 100;
And also, to calculate from a percentage :
number = (percentage / 100) * totalNumber;
same issue:
os>kubectl get svc right-sabertooth-wordpress
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S)
right-sabertooth-wordpress LoadBalancer 10.97.130.7 "pending" 80:30454/TCP,443:30427/TCPos>minikube service list
|-------------|----------------------------|--------------------------------|
| NAMESPACE | NAME | URL |
|-------------|----------------------------|--------------------------------|
| default | kubernetes | No node port |
| default | right-sabertooth-mariadb | No node port |
| default | right-sabertooth-wordpress | http://192.168.99.100:30454 |
| | | http://192.168.99.100:30427 |
| kube-system | kube-dns | No node port |
| kube-system | tiller-deploy | No node port |
|-------------|----------------------------|--------------------------------|
It is, however,accesible via that http://192.168.99.100:30454.
Please check if the setting Generate Debug Info is Yes which under Project Propeties > Configuration Properties > Linker > Debugging tab. If not, try to change it to Yes.
Those perticular pdb's ( for ntdll.dll, mscoree.dll, kernel32.dll, etc ) are for the windows API and shouldn't be needed for simple apps. However, if you cannot find pdb's for your own compiled projects, I suggest making sure the Project Properties > Configuration Properties > Debugging > Working Directory uses the value from Project Properties > Configuration Properties > General > Output Directory .
You need to run Visual c++ in "Run as Administrator" mode.Right click on the executable and click "Run as Administrator"
Use a javascript constructor with a callback that fires when the image has finished loading in the background. Just used it and works great for me cross-browser. Here's the thread with the answer.
git status
output tells you three things by default:
When you did git commit
, it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.
If you find the output of git status verbose and difficult to comprehend, try using git status -sb
this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:
master...origin/master [ahead 1]
git status
is pretty useful, in the workflow you described do a git status -sb
: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.
Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.
For the record: I had this error trying to fill a subdocument in a wrong way:
{
[CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"]
message: 'Cast to ObjectId failed for value "[object Object]" at path "_id"',
name: 'CastError',
type: 'ObjectId',
path: '_id'
value:
[ { timestamp: '2014-07-03T00:23:45-04:00',
date_start: '2014-07-03T00:23:45-04:00',
date_end: '2014-07-03T00:23:45-04:00',
operation: 'Deactivation' } ],
}
look ^ value is an array containing an object: wrong!
Explanation: I was sending data from php to a node.js API in this way:
$history = json_encode(
array(
array(
'timestamp' => date('c', time()),
'date_start' => date('c', time()),
'date_end' => date('c', time()),
'operation' => 'Deactivation'
)));
As you can see $history is an array containing an array. That's why mongoose try to fill _id (or any other field) with an array instead than a Scheme.ObjectId (or any other data type). The following works:
$history = json_encode(
array(
'timestamp' => date('c', time()),
'date_start' => date('c', time()),
'date_end' => date('c', time()),
'operation' => 'Deactivation'
));
There are three main approaches:
String email = /* Your email address here */
String subject = /* Your subject here */
String body = /* Your body here */
String chooserTitle = /* Your chooser title here */
1. Custom Uri
:
Uri uri = Uri.parse("mailto:" + email)
.buildUpon()
.appendQueryParameter("subject", subject)
.appendQueryParameter("body", body)
.build();
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(Intent.createChooser(emailIntent, chooserTitle));
2. Using Intent
extras:
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
//emailIntent.putExtra(Intent.EXTRA_HTML_TEXT, body); //If you are using HTML in your body text
startActivity(Intent.createChooser(emailIntent, "Chooser Title"));
3. Support Library ShareCompat
:
Activity activity = /* Your activity here */
ShareCompat.IntentBuilder.from(activity)
.setType("message/rfc822")
.addEmailTo(email)
.setSubject(subject)
.setText(body)
//.setHtmlText(body) //If you are using HTML in your body text
.setChooserTitle(chooserTitle)
.startChooser();
Yield can be used as nameless block to return a value in the method. Consider the following code:
Def Up(anarg)
yield(anarg)
end
You can create a method "Up" which is assigned one argument. You can now assign this argument to yield which will call and execute an associated block. You can assign the block after the parameter list.
Up("Here is a string"){|x| x.reverse!; puts(x)}
When the Up method calls yield, with an argument, it is passed to the block variable to process the request.
org.openqa.selenium.remote.DesiredCapabilities
package.Example:
WebDriver driver;
String baseUrl , nodeUrl;
baseUrl = "https://www.facebook.com";
nodeUrl = "http://192.168.10.21:5568/wd/hub";
DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WIN8_1);
driver = new RemoteWebDriver(new URL(nodeUrl),capability);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
This question was already asked on https://tex.stackexchange.com/questions/10684/vertical-space-in-lists. The highest voted answer also mentioned the enumitem
package (here answered by Stefan), but I also like this one, which involves creating your own itemizing environment instead of loading a new package:
\newenvironment{myitemize}
{ \begin{itemize}
\setlength{\itemsep}{0pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt} }
{ \end{itemize} }
Which should be used like this:
\begin{myitemize}
\item one
\item two
\item three
\end{myitemize}
Buffer is an area of memory used to temporarily store data while it's being moved from one place to another.
Cache is a temporary storage area used to store frequently accessed data for rapid access. Once the data is stored in the cache, future use can be done by accessing the cached copy rather than re-fetching the original data, so that the average access time is shorter.
Note: buffer and cache can be allocated on disk as well
This is the simplest way you can have your own javascript function be called when an onSubmit
occurs.
HTML
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
JavaScript
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(event) {
event.preventDefault();
}
in my case was a wrong path in a config file: file was not found (path was wrong) and it came out with this exception:
Error configuring from input stream. Initial cause was The processing instruction target matching "[xX][mM][lL]" is not allowed.
See MSDN.
public static class Extensions
{
public static string SomeMethod(this Duration enumValue)
{
//Do something here
return enumValue.ToString("D");
}
}
In JUnit 4, another option for you may be to create an annotation to denote that the test needs to meet your custom criteria, then extend the default runner with your own and using reflection, base your decision on the custom criteria. It may look something like this:
public class CustomRunner extends BlockJUnit4ClassRunner {
public CTRunner(Class<?> klass) throws initializationError {
super(klass);
}
@Override
protected boolean isIgnored(FrameworkMethod child) {
if(shouldIgnore()) {
return true;
}
return super.isIgnored(child);
}
private boolean shouldIgnore(class) {
/* some custom criteria */
}
}
Add System.Configuration
as a reference then:
using System.Configuration;
...
string conn =
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
You can prints lines with multiple colors without HTML as:
TextView textView = (TextView) findViewById(R.id.mytextview01);
Spannable word = new SpannableString("Your message");
word.setSpan(new ForegroundColorSpan(Color.BLUE), 0, word.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(word);
Spannable wordTwo = new SpannableString("Your new message");
wordTwo.setSpan(new ForegroundColorSpan(Color.RED), 0, wordTwo.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.append(wordTwo);
$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';
// U+1F638
var_dump(
"cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
"cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);
function escape_sequence_decode($str) {
// [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
$regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
|\\\u([\da-fA-F]{4})/sx';
return preg_replace_callback($regex, function($matches) {
if (isset($matches[3])) {
$cp = hexdec($matches[3]);
} else {
$lead = hexdec($matches[1]);
$trail = hexdec($matches[2]);
// http://unicode.org/faq/utf_bom.html#utf16-4
$cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
}
// https://tools.ietf.org/html/rfc3629#section-3
// Characters between U+D800 and U+DFFF are not allowed in UTF-8
if ($cp > 0xD7FF && 0xE000 > $cp) {
$cp = 0xFFFD;
}
// https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
// php_utf32_utf8(unsigned char *buf, unsigned k)
if ($cp < 0x80) {
return chr($cp);
} else if ($cp < 0xA0) {
return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
}
return html_entity_decode('&#'.$cp.';');
}, $str);
}
You can get this in following way,
DateTimeFormatInfo mfi = new DateTimeFormatInfo();
string strMonthName = mfi.GetMonthName(8).ToString(); //August
Now, get first three characters
string shortMonthName = strMonthName.Substring(0, 3); //Aug
With numpy:
In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]
Out[130]: array([1, 4])
or see Alex Szatmary's answer if list_a can be a numpy array but not filter
Numpy usually gives you a big speed boost as well
In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)
In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop
In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop
Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
Another way:
export default class Archive extends React.Component {
saySomething = (something) => {
console.log(something);
}
handleClick = (e) => {
this.saySomething("element clicked");
}
componentDidMount() {
this.saySomething("component did mount");
}
render() {
return <button onClick={this.handleClick} value="Click me" />;
}
}
In this format you don't need to use bind
No, this is very incorrect.
HTTP is an application protocol. 200 implies that the response contains a payload that represents the status of the requested resource. An error message usually is not a representation of that resource.
If something goes wrong while processing GET, the right status code is 4xx ("you messed up") or 5xx ("I messed up").
select Country_id,country_title from(
select Country_id,country_title,row_number() over (partition by country_title
order by Country_id ) rn from country)a
where rn=1;
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
this is a follow up on the patricus [answer][1] above but for nested arrays:
$topLevelFields = ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];
return $onlineShoppers->map(function ($user) {
return collect($user)->only($topLevelFields)
->merge(collect($user['user'])->only($userFields))->all();
})->all();
Here is a first try that's easy on the coder but hard on the CPU which prepends a random number to each line, sorts them and then strips the random number from each line. In effect, the lines are sorted randomly:
cat myfile | awk 'BEGIN{srand();}{print rand()"\t"$0}' | sort -k1 -n | cut -f2- > myfile.shuffled
Paul's answer seems to defeat the purpose of bootstrap; that of being responsive to the viewport / screen size.
By nesting rows and columns you can achieve the same result, while retaining responsiveness.
Here is an up-to-date response to this problem;
<div class="container-fluid">_x000D_
<h1> Responsive Nested Bootstrap </h1> _x000D_
<div class="row">_x000D_
<div class="col-md-5" style="background-color:red;">Span 5</div>_x000D_
<div class="col-md-3" style="background-color:blue;">Span 3</div>_x000D_
<div class="col-md-2">_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:green;">Span 2</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:purple;">Span 2</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-2" style="background-color:yellow;">Span 2</div>_x000D_
</div>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-md-6">_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:yellow;">Span 6</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="container" style="background-color:green;">Span 6</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-6" style="background-color:red;">Span 6</div>_x000D_
</div>_x000D_
</div>
_x000D_
You can view the codepen here.
The pattern matching for "gone" in most of the other solutions was a little scary for me. To be safer, this uses the --format
flag to pull out each branch's upstream tracking status.
I needed a Windows-friendly version, so this deletes all branches that are listed as "gone" using Powershell:
git branch --list --format "%(if:equals=[gone])%(upstream:track)%(then)%(refname:short)%(end)" |
? { $_ -ne "" } |
% { git branch -D $_ }
The first line lists the name of local branches whose upstream branch is "gone". The next line removes blank lines (which are output for branches that aren't "gone"), then the branch name is passed to the command to delete the branch.
One downside of the solutions based on grid.arrange
is that they make it difficult to label the plots with letters (A, B, etc.), as most journals require.
I wrote the cowplot package to solve this (and a few other) issues, specifically the function plot_grid()
:
library(cowplot)
iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
geom_boxplot() + theme_bw()
iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha = 0.7) + theme_bw() +
theme(legend.position = c(0.8, 0.8))
plot_grid(iris1, iris2, labels = "AUTO")
The object that plot_grid()
returns is another ggplot2 object, and you can save it with ggsave()
as usual:
p <- plot_grid(iris1, iris2, labels = "AUTO")
ggsave("plot.pdf", p)
Alternatively, you can use the cowplot function save_plot()
, which is a thin wrapper around ggsave()
that makes it easy to get the correct dimensions for combined plots, e.g.:
p <- plot_grid(iris1, iris2, labels = "AUTO")
save_plot("plot.pdf", p, ncol = 2)
(The ncol = 2
argument tells save_plot()
that there are two plots side-by-side, and save_plot()
makes the saved image twice as wide.)
For a more in-depth description of how to arrange plots in a grid see this vignette. There is also a vignette explaining how to make plots with a shared legend.
One frequent point of confusion is that the cowplot package changes the default ggplot2 theme. The package behaves that way because it was originally written for internal lab uses, and we never use the default theme. If this causes problems, you can use one of the following three approaches to work around them:
1. Set the theme manually for every plot. I think it's good practice to always specify a particular theme for each plot, just like I did with + theme_bw()
in the example above. If you specify a particular theme, the default theme doesn't matter.
2. Revert the default theme back to the ggplot2 default. You can do this with one line of code:
theme_set(theme_gray())
3. Call cowplot functions without attaching the package. You can also not call library(cowplot)
or require(cowplot)
and instead call cowplot functions by prepending cowplot::
. E.g., the above example using the ggplot2 default theme would become:
## Commented out, we don't call this
# library(cowplot)
iris1 <- ggplot(iris, aes(x = Species, y = Sepal.Length)) +
geom_boxplot()
iris2 <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) +
geom_density(alpha = 0.7) +
theme(legend.position = c(0.8, 0.8))
cowplot::plot_grid(iris1, iris2, labels = "AUTO")
Updates:
Swift 5 and above
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
// code to execute
})
I needed this as well, and with the help of Bombe's answer + some fiddling around, I got it working. Here's the recipe:
1. cd /path/to/git/localrepo
2. svn mkdir --parents protocol:///path/to/repo/PROJECT/trunk -m "Importing git repo"
3. git svn init protocol:///path/to/repo/PROJECT -s
4. git svn fetch
5. git rebase origin/trunk
5.1. git status
5.2. git add (conflicted-files)
5.3. git rebase --continue
5.4. (repeat 5.1.)
6. git svn dcommit
After #3 you'll get a cryptic message like this:
Using higher level of URL:
protocol:///path/to/repo/PROJECT => protocol:///path/to/repo
Just ignore that.
When you run #5, you might get conflicts. Resolve these by adding files with state "unmerged" and resuming rebase. Eventually, you'll be done; then sync back to the SVN repository, using dcommit
. That's all.
You can now synchronise from SVN to Git, using the following commands:
git svn fetch
git rebase trunk
And to synchronise from Git to SVN, use:
git svn dcommit
You might want to try this out on a local copy, before applying to a live repository. You can make a copy of your Git repository to a temporary place; simply use cp -r
, as all data is in the repository itself. You can then set up a file-based testing repository, using:
svnadmin create /home/name/tmp/test-repo
And check a working copy out, using:
svn co file:///home/name/tmp/test-repo svn-working-copy
That'll allow you to play around with things before making any lasting changes.
git svn init
If you accidentally run git svn init
with the wrong URL, and you weren't smart enough to take a backup of your work (don't ask ...), you can't just run the same command again. You can however undo the changes by issuing:
rm -rf .git/svn
edit .git/config
And remove the section [svn-remote "svn"]
section.
You can then run git svn init
anew.
initialize the Session class in the constructor of controller using
$this->load->library('session');
for example :
function __construct()
{
parent::__construct();
$this->load->model('user','',TRUE);
$this->load->model('user_activity','',TRUE);
$this->load->library('session');
}
To install a specific python package version whether it is the first time, an upgrade or a downgrade use:
pip install --force-reinstall MySQL_python==1.2.4
MySQL_python version 1.2.2 is not available so I used a different version. To view all available package versions from an index exclude the version:
pip install MySQL_python==
The problem is probably somewhere else. Try this code for example:
Sub test()
origNum = "006260006"
creditOrDebit = "D"
If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
MsgBox "OK"
End If
End Sub
And you will see that your Or
works as expected. Are you sure that your ElseIf
statement is executed (it will not be executed if any of the if/elseif before is true)?
public static T Runner<T>(Func<T> funcToRun)
{
//Do stuff before running function as normal
return funcToRun();
}
Usage:
var ReturnValue = Runner(() => GetUser(99));
To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError
to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];
, instead we could do
byte[] bytearray = new byte[1024*16];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
OutputStream output= socket.getOututStream();
BufferedInputStream bis = new BufferedInputStream(fis);
int readLength = -1;
while ((readLength = bis.read(bytearray)) > 0) {
output.write(bytearray, 0, readLength);
}
bis.close();
output.close();
}
catch(Exception ex ){
ex.printStackTrace();
} //Excuse the poor exception handling...
To set a custom height locked to somewhere:
body, html {_x000D_
height: 100%;_x000D_
}_x000D_
#outerbox {_x000D_
width: 100%;_x000D_
position: absolute; /* to place it somewhere on the screen */_x000D_
top: 130px; /* free space at top */_x000D_
bottom: 0; /* makes it lock to the bottom */_x000D_
}_x000D_
#innerbox {_x000D_
width: 100%;_x000D_
position: absolute; _x000D_
min-height: 100% !important; /* browser fill */_x000D_
height: auto; /*content fill */_x000D_
}
_x000D_
<div id="outerbox">_x000D_
<div id="innerbox"></div>_x000D_
</div>
_x000D_
In management studio you can just right click to table and click to 'View Dependencies'
than you can see a list of Objects that have dependencies with your table :
You can make use of the plusMonths and minusDays methods in Java 8:
// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));
// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);
// Add one month, subtract one day
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31
Also note that the cached directory is located in ~/.yarn-cache/
:
yarn cache clean
: cleans that directory
yarn cache list
: shows the list of cached dependencies
yarn cache dir
: prints out the path of your cached directory
Try this using uniqid and hexdec,
echo hexdec(uniqid());
You can also drag and drop the folder from Windows Explorer onto your Visual Studio solution window.
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;