Spring Boot v2 Gradle plugin docs provide an answer:
6.1. Passing arguments to your application
Like all JavaExec tasks, arguments can be passed into bootRun from the command line using
--args='<arguments>'
when using Gradle 4.9 or later.
To run server with active profile set to dev:
$ ./gradlew bootRun --args='--spring.profiles.active=dev'
If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below.
Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.
Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.
public class SOAnswer {
@ToString @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static abstract class Animal {
private String name;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Dog extends Animal {
private String breed;
}
@ToString(callSuper = true) @Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public static class Cat extends Animal {
private String favoriteToy;
}
public static void main(String[] args) {
String json = "[{"
+ " \"name\": \"pluto\","
+ " \"breed\": \"dalmatian\""
+ "},{"
+ " \"name\": \"whiskers\","
+ " \"favoriteToy\": \"mouse\""
+ "}]";
// create a deserializer instance
DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
// runtime-configure deserialization rules;
// condition is bound to the existence of a field, but it could be any Predicate
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("breed"),
DeserializationActionFactory.objectToType(Dog.class)));
deserializer.addRule(DeserializationRuleFactory.newRule(1,
(e) -> e.getJsonNode().has("favoriteToy"),
DeserializationActionFactory.objectToType(Cat.class)));
List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
for (Animal animal : deserializedAnimals) {
System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
}
}
}
Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:
<dependency>
<groupId>com.pretius</groupId>
<artifactId>jddl</artifactId>
<version>1.0.0</version>
</dependency>
Update
Many issues relating to this feature in version 23.2.0 have been fixed in 23.2.1, update to that instead.
With the release of Support Library version 23.2, RecyclerView
now supports that!
Update build.gradle
to:
compile 'com.android.support:recyclerview-v7:23.2.1'
or any version beyond that.
This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.
This can be disabled via setAutoMeasurementEnabled()
if need be. Check in detail here.
This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:
Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
if (!rct3Features.ContainsKey(items[0]))
{
rct3Features.Add(items[0], items[1]);
}
////To print out the dictionary (to see if it works)
//foreach (KeyValuePair<string, string> item in rct3Features)
//{
// Console.WriteLine(item.Key + " " + item.Value);
//}
}
This simple if
statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]
) is not already present.
I think this is the most clear solution, using an extension method:
public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}
So just use it like:
var ipAddress = request.GetClientIpAddress();
We use this in our projects.
Source/Reference: Retrieving the client’s IP address in ASP.NET Web API
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
I solved it using a different method. All you have to do is check if the width is greater than height
Matrix rotationMatrix = new Matrix();
if(finalBitmap.getWidth() >= finalBitmap.getHeight())
{
rotationMatrix.setRotate(-90);
}
else
{
rotationMatrix.setRotate(0);
}
Bitmap rotatedBitmap = Bitmap.createBitmap(finalBitmap,0,0,finalBitmap.getWidth(),finalBitmap.getHeight(),rotationMatrix,true);
There is a ToObject method now.
var obj = jsonObject["date_joined"];
var result = obj.ToObject<DateTime>();
It also works with any complex type, and obey to JsonPropertyAttribute rules
var result = obj.ToObject<MyClass>();
public class MyClass
{
[JsonProperty("date_field")]
public DateTime MyDate {get;set;}
}
The first form, when used with an API that returns Boolean
and compared against Boolean.FALSE, will never throw a NullPointerException
.
The second form, when used with the java.util.Map
interface, also, will never throw a NullPointerException
because it returns a boolean
and not a Boolean
.
If you aren't concerned about consistent coding idioms, then you can pick the one you like, and in this concrete case it really doesn't matter. If you do care about consistent coding, then consider what you want to do when you check a Boolean
that may be NULL
.
In my case, I was defining a bean and autowiring it in the constructor of the same class file.
@SpringBootApplication
public class MyApplication {
private MyBean myBean;
public MyApplication(MyBean myBean) {
this.myBean = myBean;
}
@Bean
public MyBean myBean() {
return new MyBean();
}
}
My solution was to move the bean definition to another class file.
@Configuration
public CustomConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
In VB it's:
if not MyNameValueCollection(Key) is Nothing then
.......
end if
In C# should just be:
if (MyNameValueCollection(Key) != null) { }
Not sure if it should be null
or ""
but this should help.
Since people don't tend to read comments, here is an answer that mostly duplicates what I wrote here:
the root cause of the issue is the fact that android system does not call getItem
to obtain fragments that are actually displayed, but instantiateItem
. This method first tries to lookup and reuse a fragment instance for a given tab in FragmentManager
. Only if this lookup fails (which happens only the first time when FragmentManager
is newly created) then getItem
is called. It is for obvious reasons not to recreate fragments (that may be heavy) for example each time a user rotates his device.
To solve this, instead of creating fragments with Fragment.instantiate
in your activity, you should do it with pagerAdapter.instantiateItem
and all these calls should be surrounded by startUpdate/finishUpdate
method calls that start/commit fragment transaction respectively. getItem
should be the place where fragments are really created using their respective constructors.
List<Fragment> fragments = new Vector<Fragment>();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
((TabLayout) findViewById(R.id.tabs)).setupWithViewPager(viewPager);
adapter.startUpdate(viewPager);
fragments.add(adapter.instantiateItem(viewPager, 0));
fragments.add(adapter.instantiateItem(viewPager, 1));
// and so on if you have more tabs...
adapter.finishUpdate(viewPager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager manager) {super(manager);}
@Override public int getCount() {return 2;}
@Override public Fragment getItem(int position) {
if (position == 0) return new Fragment0();
if (position == 1) return new Fragment1();
return null; // or throw some exception
}
@Override public CharSequence getPageTitle(int position) {
if (position == 0) return getString(R.string.tab0);
if (position == 1) return getString(R.string.tab1);
return null; // or throw some exception
}
}
I suspect the error is caused by this:
foreach (KeyValuePair<int, int> kvp in rankings)
rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.
But you're modifying the dictionary inside your loop:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
which isn't allowed...so you get the exception.
You could simply do this
foreach (KeyValuePair<int, int> kvp in rankings.ToArray())
The question how do I convert an object to a String
, despite the several answers you see here, and despite the existence of the Object.toString
method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.
Before code can be written to convert an object to a String
, you must decide on the language/format to be used.
Old question but i feel i should add the following, even more because .net 4.0 had already launched at the time the question was written.
Starting with .net 4.0 there is the namespace System.Collections.Concurrent
which includes collections that are thread-safe.
The collection System.Collections.Concurrent.ConcurrentDictionary<>
does exactly what you want. It has the AddOrUpdate()
method with the added advantage of being thread-safe.
If you're in a high-performance scenario and not handling multiple threads the already given answers of map[key] = value
are faster.
In most scenarios this performance benefit is insignificant. If so i'd advise to use the ConcurrentDictionary because:
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
I know this is an old post and I do favor extension methods, but here's a simple class I use from time to time to handle dictionaries when I need default values.
I wish this were just part of the base Dictionary class.
public class DictionaryWithDefault<TKey, TValue> : Dictionary<TKey, TValue>
{
TValue _default;
public TValue DefaultValue {
get { return _default; }
set { _default = value; }
}
public DictionaryWithDefault() : base() { }
public DictionaryWithDefault(TValue defaultValue) : base() {
_default = defaultValue;
}
public new TValue this[TKey key]
{
get {
TValue t;
return base.TryGetValue(key, out t) ? t : _default;
}
set { base[key] = value; }
}
}
Beware, however. By subclassing and using new
(since override
is not available on the native Dictionary
type), if a DictionaryWithDefault
object is upcast to a plain Dictionary
, calling the indexer will use the base Dictionary
implementation (throwing an exception if missing) rather than the subclass's implementation.
No, it will not be evaluated. And this is very useful. For example, if you need to test whether a String is not null or empty, you can write:
if (str != null && !str.isEmpty()) {
doSomethingWith(str.charAt(0));
}
or, the other way around
if (str == null || str.isEmpty()) {
complainAboutUnusableString();
} else {
doSomethingWith(str.charAt(0));
}
If we didn't have 'short-circuits' in Java, we'd receive a lot of NullPointerExceptions in the above lines of code.
Use
table.put(key, val);
to add a new key/value pair or overwrite an existing key's value.
From the Javadocs:
V put(K key, V value): Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
How is the HashMap declaration expressed in that scope? It should be:
HashMap<String, ArrayList> dictMap
If not, it is assumed to be Objects.
For instance, if your code is:
HashMap dictMap = new HashMap<String, ArrayList>();
...
ArrayList current = dictMap.get(dictCode);
that will not work. Instead you want:
HashMap<String, ArrayList> dictMap = new HashMap<String, Arraylist>();
...
ArrayList current = dictMap.get(dictCode);
The way generics work is that the type information is available to the compiler, but is not available at runtime. This is called type erasure. The implementation of HashMap (or any other generics implementation) is dealing with Object. The type information is there for type safety checks during compile time. See the Generics documentation.
Also note that ArrayList
is also implemented as a generic class, and thus you might want to specify a type there as well. Assuming your ArrayList
contains your class MyClass
, the line above might be:
HashMap<String, ArrayList<MyClass>> dictMap
Presumably you want the key to the map to match on the value of the elements instead of the identity of the array. In that case you want some kind of object that defines equals
and hashCode
as you would expect. Easiest is to convert to a List<Integer>
, either an ArrayList
or better use Arrays.asList
. Better than that you can introduce a class that represents the data (similar to java.awt.Rectangle
but I recommend making the variables private final, and the class final too).
Sounds like your solution is quite plausible for this need, I honestly don't see a problem with it if your two key types are really distinct. Just makes ure you write your own implementation for this and deal with synchronization issues if needed.
var a;
typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true
You would have to assign such an identifier yourself, manually - either inside the instance, or externally.
For records related to a database, the primary key may be useful (but you can still get duplicates). Alternatively, either use a Guid
, or keep your own counter, allocating using Interlocked.Increment
(and make it large enough that it isn't likely to overflow).
That looks correct to me. If I were to change anything, I would stop using the Collections.synchronizedMap() and synchronize everything the same way, just to make it clearer.
Also, I'd replace
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
with
List<String> valuesList = synchronziedMap.get(key);
if (valuesList == null)
{
valuesList = new ArrayList<String>();
synchronziedMap.put(key, valuesList);
}
valuesList.add(value);
Google Collections HashMultiset :
- quite elegant to use
- but consume CPU and memory
Best would be to have a method like : Entry<K,V> getOrPut(K);
(elegant, and low cost)
Such a method will compute hash and index only once, and then we could do what we want with the entry (either replace or update the value).
More elegant:
- take a HashSet<Entry>
- extend it so that get(K)
put a new Entry if needed
- Entry could be your own object.
--> (new MyHashSet()).get(k).increment();
for (int i = 0; i < 6; i++)
{
test.ColumnDefinitions.Add(new ColumnDefinition());
Label t1 = new Label();
t1.Content = "Test" + i;
Grid.SetColumn(t1, i);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
}
It's the other way around: B.class.isInstance(view)
In your xyz.DAOImpl.java
Do the following steps:
//Step-1: Set session factory
@Resource(name="sessionFactory")
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf)
{
this.sessionFactory = sf;
}
//Step-2: Try to get the current session, and catch the HibernateException exception.
//Step-3: If there are any HibernateException exception, then true to get openSession.
try
{
//Step-2: Implementation
session = sessionFactory.getCurrentSession();
}
catch (HibernateException e)
{
//Step-3: Implementation
session = sessionFactory.openSession();
}
you need object notation
<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" >
ref: NgClass
You can create button in a simple way, such as:
Button button = new Button();
button.Click += new EventHandler(button_Click);
protected void button_Click (object sender, EventArgs e)
{
Button button = sender as Button;
// identify which button was clicked and perform necessary actions
}
But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.
I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,
for example, imagine you create your button on an event click:
protected void Button_Click(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
CreateDynamicElements();
}
}
on postback, for example on page load, you should do this:
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true") {
CreateDynamicElements();
}
}
In CreateDynamicElements() you can put all the elements you need, such as your button.
This worked very well for me.
public void CreateDynamicElements(){
Button button = new Button();
button.Click += new EventHandler(button_Click);
}
For those who stuck at this error as me and nothing helped from above: check if problem folder from error.log actually exists on your server. Mine was generated automatically by Django in wrong place (was messed with static root, then manage.py collectstatic
). Have no idea why one can not name errors correctly.
3 options, same result:
1. All steps:
$ rake db:drop # deletes the database for the current env
$ rake db:create # creates the database for the current env
$ rake db:schema:load # loads the schema already generated from schema.rb / erases data
$ rake db:seed # seed with initial data
2. Reset:
$ rake db:reset # drop / schema:load / seed
3. Migrate:reset:
$ rake db:migrate:reset # drop / create / migrate
$ rake db:seed
Notes:
Instead of strtotime
you should use DateTime
with PHP. You can also regard the timezone this way:
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();
$mysqltime
is of type MySQL Datetime, e. g. 2018-02-26 07:53:00
.
Those extensions aren't really new, they are old. :-)
When C++ was new, some people wanted to have a .c++ extension for the source files, but that didn't work on most file systems. So they tried something close to that, like .cxx, or .cpp instead.
Others thought about the language name, and "incrementing" .c to get .cc or even .C in some cases. Didn't catch on that much.
Some believed that if the source is .cpp, the headers ought to be .hpp to match. Moderately successful.
HTML
<input [(ngModel)] = "searchTerm" (ngModelChange) = "search()"/>
<div *ngFor = "let item of items">{{item.name}}</div>
Component
search(): void {
let term = this.searchTerm;
this.items = this.itemsCopy.filter(function(tag) {
return tag.name.indexOf(term) >= 0;
});
}
Note that this.itemsCopy is equal to this.items and should be set before doing the search.
I'm surprised no one has mentioned using regular expressions via re.sub()
:
import re
print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\"
print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\"
Important things to note:
\
as well as the character(s) you're looking for.
You're going to be using \
to escape your characters, so you need to escape
that as well.([\"])
, so that the substitution
pattern can use the found character when it adds \
in front of it. (That's what
\1
does: uses the value of the first parenthesized group.)r
in front of r'([\"])'
means it's a raw string. Raw strings use different
rules for escaping backslashes. To write ([\"])
as a plain string, you'd need to
double all the backslashes and write '([\\"])'
. Raw strings are friendlier when
you're writing regular expressions.\
to distinguish it from a
backslash that precedes a substitution group, e.g. \1
, hence r'\\\1'
. To write
that as a plain string, you'd need '\\\\\\1'
— and nobody wants that.Modernizr is also a great option for giving IE HTML5 rendering capabilities.
The setting for the list throttle
For addtional reading: http://blogs.msdn.com/b/dinaayoub/archive/2010/04/22/sharepoint-2010-how-to-change-the-list-view-threshold.aspx
There's also Hypothesis which adds fuzz or property based testing.
This is a very powerful testing method.
I propose to use
SET time_zone = 'proper timezone';
being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.
exec sp_lock
This query should give you existing locks.
exec sp_who SPID -- will give you some info
Having spids, you could check activity monitor(processes tab) to find out what processes are locking the tables ("details" for more info and "kill process" to kill it).
You can do it without forcing html
and body
to me 100% height. Use view port height instead. And with mouse wheel control too.
function debounce(func, wait, immediate) {_x000D_
var timeout;_x000D_
return function() {_x000D_
var context = this,_x000D_
args = arguments;_x000D_
var later = function() {_x000D_
timeout = null;_x000D_
if (!immediate) func.apply(context, args);_x000D_
};_x000D_
var callNow = immediate && !timeout;_x000D_
clearTimeout(timeout);_x000D_
timeout = setTimeout(later, wait);_x000D_
if (callNow) func.apply(context, args);_x000D_
};_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
//console.log(direction);_x000D_
if (direction == false) {_x000D_
$('.carousel-control-next').click();_x000D_
} else {_x000D_
$('.carousel-control-prev').click();_x000D_
}_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
e.preventDefault();_x000D_
var delta;_x000D_
if (event.wheelDelta) {_x000D_
delta = event.wheelDelta;_x000D_
} else {_x000D_
delta = -1 * event.deltaY;_x000D_
}_x000D_
_x000D_
onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
height: 100vh;_x000D_
background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
display: flex !important;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
color: #fff;_x000D_
font-size: 72px;_x000D_
padding: 0 10%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
<!-- The slideshow -->_x000D_
<div class="carousel-inner">_x000D_
<div class="carousel-item active">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
</div>_x000D_
<div class="carousel-item">_x000D_
<h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<!-- Left and right controls -->_x000D_
<a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
<span class="carousel-control-prev-icon"></span>_x000D_
</a>_x000D_
<a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
<span class="carousel-control-next-icon"></span>_x000D_
</a>_x000D_
_x000D_
</div>
_x000D_
I had the same issue. Solved it simply; I have (2) google accounts linked to my Play Store. It just so happens that I installed "an" app from "account B", and I was trying to rate it from "account A". So, switched accounts, and voilá.
Associative array in PHP actually considered as a dictionary.
An array in PHP is actually an ordered map. A map is a type that associates values to keys. it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
An array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index.
this
refers to a reference of the current class.
super
refers to the parent of the current class (which called the super
keyword).
By doing this
, it allows you to access methods/attributes of the current class (including its own private methods/attributes).
super
allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.
Try this:
$(function() {
$("#type").change(function() {
if ($(this).val() === 'parcel') $("#row_dim").show();
else $("#row_dim").hide();
}
}
I try with http servlet and I find this issue when I write duplicated @WebServlet ,I encountered with this issue.After I remove or change @WebServlet value it is working.
1.Class
@WebServlet("/display")
public class MyFirst extends HttpServlet {
2.Class
@WebServlet("/display")
public class MySecond extends HttpServlet {
Visual summary of options for spinning icons. Recorded using Screen To Gif.
Install via NuGet:
PM> Install-Package FontAwesome.WPF
Looks like this:
XAML:
<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />
Icons pictured are Spinner
, CircleOutlineNotch
, Refresh
and Cog
. There are many others.
XAML copy/paste.
Enable mod_headers in Apache2 to be able to use Header directive :
a2enmod headers
Combined with Mike McMaster's answer, you might want to do something like:
[myTextView setDelegate: self];
...
- (void)textViewDidChange:(UITextView *)textView {
if (myTextView == textView) {
// it changed. Do resizing here.
}
}
Use RelativeLayout (container) and android:layout_centerHorizontal="true" ,my sample:
<RelativeLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:button="@drawable/bg_fav_detail"
android:drawablePadding="5dp"
android:text=" Favorite" />
</RelativeLayout>
For those who have a file from an input control, don't know what its orientation is, are a bit lazy and don't want to include a large library below is the code provided by @WunderBart melded with the answer he links to (https://stackoverflow.com/a/32490603) that finds the orientation.
function getDataUrl(file, callback2) {
var callback = function (srcOrientation) {
var reader2 = new FileReader();
reader2.onload = function (e) {
var srcBase64 = e.target.result;
var img = new Image();
img.onload = function () {
var width = img.width,
height = img.height,
canvas = document.createElement('canvas'),
ctx = canvas.getContext("2d");
// set proper canvas dimensions before transform & export
if (4 < srcOrientation && srcOrientation < 9) {
canvas.width = height;
canvas.height = width;
} else {
canvas.width = width;
canvas.height = height;
}
// transform context before drawing image
switch (srcOrientation) {
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
default: break;
}
// draw image
ctx.drawImage(img, 0, 0);
// export base64
callback2(canvas.toDataURL());
};
img.src = srcBase64;
}
reader2.readAsDataURL(file);
}
var reader = new FileReader();
reader.onload = function (e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112)
return callback(view.getUint16(offset + (i * 12) + 8, little));
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
return callback(-1);
};
reader.readAsArrayBuffer(file);
}
which can easily be called like such
getDataUrl(input.files[0], function (imgBase64) {
vm.user.BioPhoto = imgBase64;
});
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
The correct way to do it is to create a UITableViewCell subclass implementation, header, and XIB. In the XIB remove any views and just add a table cell. Set the class as the name of the UITableViewCell subclass. For file owner, make it the UITableViewController subclass class name. Connect the file owner to the cell using the tableViewCell outlet.
In the header file:
UITableViewCell *_tableViewCell;
@property (assign) IBOutlet UITableViewCell *tableViewCell;
In the implementation file:
@synthesize tableViewCell = _tableViewCell;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kCellIdentifier = @"reusableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:kCellIdentifier owner:self options:nil];
cell = _tableViewCell;
self.tableViewCell = nil;
}
return cell;
}
Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:
public static class Retry
{
public static void Do(
Action action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, maxAttemptCount);
}
public static T Do<T>(
Func<T> action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
var exceptions = new List<Exception>();
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
Thread.Sleep(retryInterval);
}
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}
You can now use this utility method to perform retry logic:
Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
or:
Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));
or:
int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);
Or you could even make an async
overload.
Now has a new nuget package, try use it: https://www.nuget.org/packages/Oracle.ManagedDataAccess.EntityFramework/
Quite a few of these solutions suggest referencing the public_path() of the Laravel application in order to locate the file. Sometimes you'll want to control access to the file or offer real-time monitoring of the file. In this case, you'll want to keep the directory private and limit access by a method in a controller class. The following method should help with this:
public function show(Request $request, File $file) {
// Perform validation/authentication/auditing logic on the request
// Fire off any events or notifiations (if applicable)
return response()->download(storage_path('app/' . $file->location));
}
There are other paths that you could use as well, described on Laravel's helper functions documentation
Unfortunately, there isn't a TryParse() equivalent. If you create a new instance of a System.Guid and pass the string value in, you can catch the three possible exceptions it would throw if it is invalid.
Those are:
I have seen some implementations where you can do a regex on the string prior to creating the instance, if you are just trying to validate it and not create it.
User Defined Class Array List Example
import java.util.*;
public class UserDefinedClassInArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Program Output:
1 AAA 13
2 BBB 14
3 CCC 15
Suppose you are going to create a test-context.xml which is independent from app-context.xml for testing, put test-context.xml under /src/test/resources. In the test class, have the @ContextConfiguration annotation on top of the class definition.
@ContextConfiguration(locations = "/test-context.xml")
public class MyTests {
...
}
Spring document Context management
It is not possible yet to search for content using multiple tags, for now only single tags are supported.
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:
https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey
Also note that the username is not the user-id. You can look up user-Id`s here.
A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.
It is debatable as to whether you should use String or use Char[] for this purpose because both have their advantages and disadvantages. It depends on what the user needs.
Since Strings in Java are immutable, whenever some tries to manipulate your string it creates a new Object and the existing String remains unaffected. This could be seen as an advantage for storing a password as a String, but the object remains in memory even after use. So if anyone somehow got the memory location of the object, that person can easily trace your password stored at that location.
Char[] is mutable, but it has the advantage that after its usage the programmer can explicitly clean the array or override values. So when it's done being used it is cleaned and no one could ever know about the information you had stored.
Based on the above circumstances, one can get an idea whether to go with String or to go with Char[] for their requirements.
The main issue is that the inner query cannot be related to your where
clause on the outer update
statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.
Update
Competition as C
inner join (
select CompetitionId, count(*) as NumberOfTeams
from PicksPoints as p
where UserCompetitionID is not NULL
group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams
Your query translates to:
SELECT name FROM users WHERE id IN ('Array');
Or something to that affect.
Try using prepared queries instead, something like:
$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
$ints = array_map(function(){ return 'i'; }, $numbers);
call_user_func_array("mysqli_stmt_bind_param", array_merge(
array($statement, implode('', $ints)), $numbers
));
$results = mysqli_stmt_execute($statement);
// do something with results
// ...
}
A reproducible example:
the_plot <- function()
{
x <- seq(0, 1, length.out = 100)
y <- pbeta(x, 1, 10)
plot(
x,
y,
xlab = "False Positive Rate",
ylab = "Average true positive rate",
type = "l"
)
}
James's suggestion of using pointsize
, in combination with the various cex
parameters, can produce reasonable results.
png(
"test.png",
width = 3.25,
height = 3.25,
units = "in",
res = 1200,
pointsize = 4
)
par(
mar = c(5, 5, 2, 2),
xaxs = "i",
yaxs = "i",
cex.axis = 2,
cex.lab = 2
)
the_plot()
dev.off()
Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,
library(ggplot2)
ggplot_alternative <- function()
{
the_data <- data.frame(
x <- seq(0, 1, length.out = 100),
y = pbeta(x, 1, 10)
)
ggplot(the_data, aes(x, y)) +
geom_line() +
xlab("False Positive Rate") +
ylab("Average true positive rate") +
coord_cartesian(0:1, 0:1)
}
ggsave(
"ggtest.png",
ggplot_alternative(),
width = 3.25,
height = 3.25,
dpi = 1200
)
To enable the standard copy/paste for TextView, U can choose one of the following:
Change in layout file: add below property to your TextView
android:textIsSelectable="true"
In your Java class write this line two set the grammatically.
myTextView.setTextIsSelectable(true);
And long press on the TextView you can see copy/paste action bar.
If you have a String object you want to tokenize, favor using String's split method over a StringTokenizer. If you're parsing text data from a source outside your program, like from a file, or from the user, that's where a Scanner comes in handy.
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}
Emacs takes many launch options. The one that you are looking for is
emacs -nw
. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set.
The long form of this flag is emacs --no-window-system
.
More information about Emacs launch options can be found in the manual.
shutil.copy
and shutil.copy2
are copying files.
shutil.copytree
copies a folder with all the files and all subfolders. shutil.copytree
is using shutil.copy2
to copy the files.
So the analog to cp -r
you are saying is the shutil.copytree
because cp -r
targets and copies a folder and its files/subfolders like shutil.copytree
. Without the -r
cp
copies files like shutil.copy
and shutil.copy2
do.
I plan on releasing this code in the next version of jPaq, but until then, you can use this if your goal is to do a deep copy of arrays:
Array.prototype.clone = function(doDeepCopy) {
if(doDeepCopy) {
var encountered = [{
a : this,
b : []
}];
var item,
levels = [{a:this, b:encountered[0].b, i:0}],
level = 0,
i = 0,
len = this.length;
while(i < len) {
item = levels[level].a[i];
if(Object.prototype.toString.call(item) === "[object Array]") {
for(var j = encountered.length - 1; j >= 0; j--) {
if(encountered[j].a === item) {
levels[level].b.push(encountered[j].b);
break;
}
}
if(j < 0) {
encountered.push(j = {
a : item,
b : []
});
levels[level].b.push(j.b);
levels[level].i = i + 1;
levels[++level] = {a:item, b:j.b, i:0};
i = -1;
len = item.length;
}
}
else {
levels[level].b.push(item);
}
if(++i == len && level > 0) {
levels.pop();
i = levels[--level].i;
len = levels[level].a.length;
}
}
return encountered[0].b;
}
else {
return this.slice(0);
}
};
The following is an example of how to call this function to do a deep copy of a recursive array:
// Create a recursive array to prove that the cloning function can handle it.
var arrOriginal = [1,2,3];
arrOriginal.push(arrOriginal);
// Make a shallow copy of the recursive array.
var arrShallowCopy = arrOriginal.clone();
// Prove that the shallow copy isn't the same as a deep copy by showing that
// arrShallowCopy contains arrOriginal.
alert("It is " + (arrShallowCopy[3] === arrOriginal)
+ " that arrShallowCopy contains arrOriginal.");
// Make a deep copy of the recursive array.
var arrDeepCopy = arrOriginal.clone(true);
// Prove that the deep copy really works by showing that the original array is
// not the fourth item in arrDeepCopy but that this new array is.
alert("It is "
+ (arrDeepCopy[3] !== arrOriginal && arrDeepCopy === arrDeepCopy[3])
+ " that arrDeepCopy contains itself and not arrOriginal.");
You can play around with this code here at JS Bin.
According to Swift 4 Documentation, String values can be added together (or concatenated) with the addition operator (+) to create a new String value:
let string1 = "hello"
let string2 = " there"
var welcome = string1 + string2
// welcome now equals "hello there"
You can also append a String value to an existing String variable with the addition assignment operator (+=):
var instruction = "look over"
instruction += string2
// instruction now equals "look over there"
You can append a Character value to a String variable with the String type’s append() method:
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome now equals "hello there!"
(Posting in case someone might have a use of it).
I was looking for a solution for a problem a bit more sophisticated than OP - replacing EVERY occurrence of something with the number by same thing with incremented number
E.g. Replacing something like this:
<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />
By this:
<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />
Couldnt find the solution online so I wrote my own script in groovy (a bit ugly but does the job):
/**
* <p> Finds words that matches template and increases them by 1.
* '_' in word template represents number.
*
* <p> E.g. if template equals 'Row="_"', then:
* ALL Row=0 will be replaced by Row="1"
* All Row=1 will be replaced by Row="2"
* <p> Warning - your find template might not work properly if _ is the last character of it
* etc.
* <p> Requirments:
* - Original text does not contain tepmlate string
* - Only numbers in non-disrupted sequence are incremented and replaced
* (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be
* replaced by Row=5)
*/
def replace_inc(String text, int startingIndex, String findTemplate) {
assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
while (true) {
findString = findTemplate.replace("_",(startingIndex).toString())
if (!text.contains(findString)) break;
replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
text = text.replaceAll(findString, replaceString)
}
return text.replaceAll("_____","") // get rid of '_____' character
}
// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0
// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"
Maybe use LaTeX and try something like this
\documentclass[a4paper]{article}
\usepackage[3D]{movie15}
\usepackage{hyperref}
\begin{document}
\includemovie[
poster,
toolbar,
3Daac=60.000000, 3Droll=0.000000, 3Dc2c=0.000000 2.483000 0.000000, 3Droo=2.483000, 3Dcoo=0.000000 0.000000 0.000000,
3Dlights=CAD,
]{\linewidth}{\linewidth}{Bob.u3d}
\end{document}
where Bob3d.u3d is a sample virtual reality file I had. This works (or did) for movies, and I expect it might work for gifs too.
p_value is among f statistics. if you want to get the value, simply use this few lines of code:
import statsmodels.api as sm
from scipy import stats
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
print(est.fit().f_pvalue)
One other way would be to use 4 letter commands to validate if zookeeper service is healthy or not
echo stat | nc <zookeeper ip> 2181
echo mntr | nc <zookeeper ip> 2181
echo isro | nc <zookeeper ip> 2181
More details on the documentation link below https://zookeeper.apache.org/doc/r3.1.2/zookeeperAdmin.html#sc_zkCommands
You can only do this with an abstract class, not with an interface.
Declare Rectangle
as an abstract class
instead of an interface
and declare the methods that must be implemented by the sub-class as public abstract
. Then class Tile
extends class Rectangle
and must implement the abstract methods from Rectangle
.
For same error code i had quite different reason, I'm sharing here to help
I had web api action like below
public IHttpActionResult GetBooks (int id)
I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]
public IHttpActionResult GetBooks (int category, int author)
I also changed ajax options like below and at this point i start getting error 405 method not allowed
var options = {
url: '/api/books/GetBooks',
type: 'POST',
dataType: 'json',
cache: false,
traditional: true,
data: {
category: 1,
author: 15
}
}
When i created class for web api action parameters like below error was gone
public class BookParam
{
public int Category { get; set; }
public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)
==
is used to check if two variables are equal i.e
2 == 2
. But in case of ===
it stands for equality i.e if two instances referring to the same object example in case of classes a reference is created which is held by many other instances.
When you visited https://localhost previously at some point it not only visited this over a secure channel (https rather than http), it also told your browser, using a special HTTP header: Strict-Transport-Security (often abbreviated to HSTS), that it should ONLY use https for all future visits.
This is a security feature web servers can use to prevent people being downgraded to http (either intentionally or by some evil party).
However if you then then turn off your https server, and just want to browse http you can't (by design - that's the point of this security feature).
HSTS also does prevents you from accepting and skipping past certificate errors.
To reset this, so HSTS is no longer set for localhost, type the following in your Chrome address bar:
chrome://net-internals/#hsts
Where you will be able to delete this setting for "localhost".
You might also want to find out what was setting this to avoid this problem in future!
Note that for other sites (e.g. www.google.com) these are "preloaded" into the Chrome code and so cannot be removed. When you query them at chrome://net-internals/#hsts you will see them listed as static
HSTS entries.
And finally note that Google has started preloading HSTS for the entire .dev domain: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/
If you give your table a unique id, its easier:
<div id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a"
onmouseup="checkMultipleSelection(this,event);">
<table id="ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table"
cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:50px; text-align:left;">09:15 AM</td>
<td style="width:50px; text-align:left;">Item001</td>
<td style="width:50px; text-align:left;">10</td>
<td style="width:50px; text-align:left;">Address1</td>
<td style="width:50px; text-align:left;">46545465</td>
<td style="width:50px; text-align:left;">ref1</td>
</tr>
</table>
</div>
var multiselect =
document.getElementById(
'ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a_table'
).rows[0].cells,
timeXaddr = [multiselect[0].innerHTML, multiselect[2].innerHTML];
//=> timeXaddr now an array containing ['09:15 AM', 'Address1'];
I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.
When you find the line such as "Hello <? //code for showing username?>"
, just copy that line and show it where you need to
The answer to your problem is easy: replace the current Fragment
with the new Fragment
and push transaction onto the backstack. This preserves back button behaviour...
Creating a new Activity
really defeats the whole purpose to use fragments anyway...very counter productive.
@Override
public void onClick(View v) {
// Create new fragment and transaction
Fragment newFragment = new chartsFragment();
// consider using Java coding conventions (upper first char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
http://developer.android.com/guide/components/fragments.html#Transactions
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
You have to mention the width of the h1 tag..
your css will be like this
h1 {
text-align: center;
background-color: green;
width: 600px;
}
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
Specifically: ((depth))
. By example, the following prints 1
.
declare -i x=0
((x)) && echo $x
x=1
((x)) && echo $x
As for me issue was that the first line in the build.gradle
file of the OpenCV library.
It was something like this:
apply plugin: 'com.android.application'
This refers to the fact that the imported OpenCV is an application and not a library. It exists for OpenCV above 4.1.0. So change it to:
Something like this:
apply plugin: 'com.android.library'
.
You might get an error in ApplicationId, comment it out in the gradle file.
Comparable
is Fegan
.The method compareTo
you are overidding in it should have a Fegan
object as a parameter whereas you are casting it to a FoodItems
. Your compareTo
implementation should describe how a Fegan
compare to another Fegan
.
FoodItems
implement Comparable
aswell and copy paste your actual compareTo
logic in it.There are several possible catches. I think that the most common error is in this part of the connection string:
res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;
This is no magic. Once you understand what is stands for you'll get the connection string right.
First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.
Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.
Your final EF connection string may look like this:
res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;
try this one :),
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
I'm actually having a trouble with similar behaviour, I render a video element in a Component with it's id attribute so when RenderDOM.render() ends it loads a plugin that needs the id to find the placeholder and it fails to find it.
The setTimeout with 0ms inside the componentDidMount() fixed it :)
componentDidMount() {
if (this.props.onDidMount instanceof Function) {
setTimeout(() => {
this.props.onDidMount();
}, 0);
}
}
You should also be aware of the fact, that with utf8_general_ci when using a varchar field as unique or primary index inserting 2 values like 'a' and 'á' would give a duplicate key error.
Another possibility is to do something like:
#ifndef _STACK_HPP
#define _STACK_HPP
template <typename Type>
class stack {
public:
stack();
~stack();
};
#include "stack.cpp" // Note the include. The inclusion
// of stack.h in stack.cpp must be
// removed to avoid a circular include.
#endif
I dislike this suggestion as a matter of style, but it may suit you.
Quickest way to convert .ui to .py is from terminal:
pyuic4 -x input.ui -o output.py
Make sure you have pyqt4-dev-tools installed.
If triangle.lborderA
is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.
However, if triangle.lborderA
is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300)
does return true.
public static boolean isBiggerThanMaxLong(double in){
return in > Long.MAX_VALUE;
}
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
Another difference is that when using new Array()
you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array()
because you can prevent the overflow from happening.
As pointed out in this answer, new Array(5)
will not actually add five undefined
items to the array. It simply adds space for five items. Be aware that using Array
this way makes it difficult to rely on array.length
for calculations.
Some advantages to the second option:
You can use this
inside onclick
to reference the anchor itself (doing the same in option 1 will give you window
instead).
You can set the href
to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();"
and return false
from inside the function or onclick="return someFunction(); return false;"
to prevent default action).
I've seen weird stuff happen when using href="javascript:someFunction()"
and the function returns a value; the whole page would get replaced by just that value.
Pitfalls
Inline code:
Runs in document
scope as opposed to code defined inside <script>
tags which runs in window
scope; therefore, symbols may be resolved based on an element's name
or id
attribute, causing the unintended effect of attempting to treat an element as a function.
Is harder to reuse; delicate copy-paste is required to move it from one project to another.
Adds weight to your pages, whereas external code files can be cached by the browser.
Turns out the docs tell you the answer! The UIButton will ignore the title change if it already has an Attributed String to use (with seems to be the default you get when using Xcode interface builder).
I used the following:
[self.loginButton
setAttributedTitle:[[NSAttributedString alloc] initWithString:@"Error !!!" attributes:nil]
forState:UIControlStateDisabled];
[self.loginButton setEnabled:NO];
The simplest way to do this is as follows:
save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)
The image is going to be saved in the save_results_to
directory with name image.png
I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.
You can also consider using Record
, like this:
const someArray: Record<string, string>[] = [
{'first': 'one'},
{'second': 'two'}
];
Or write something like this:
const someArray: {key: string, value: string}[] = [
{key: 'first', value: 'one'},
{key: 'second', value: 'two'}
];
Use of Lazy quantifiers ?
with no global flag is the answer.
Eg,
If you had global flag /g
then, it would have matched all the lowest length matches as below.
You mean you want to do "aabbab".toCharArray(); ? Which will return an array of chars. Or do you actually want the resulting array to contain single character string objects?
You could use grep
as well:
grep('2', strsplit(string, '')[[1]])
#4 24
From cppreference, one of the std::unique_ptr
constructors is
explicit unique_ptr( pointer p ) noexcept;
So to create a new std::unique_ptr
is to pass a pointer to its constructor.
unique_ptr<int> uptr (new int(3));
Or it is the same as
int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);
The different is you don't have to clean up after using it. If you don't use std::unique_ptr
(smart pointer), you will have to delete it like this
delete int_ptr;
when you no longer need it or it will cause a memory leak.
Just in case you are working on php less then 5.2 you can use this resourse.
http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])
#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)
#legend
cbar = plt.colorbar(heatmap)
cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()
#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.
To get every part of the URL except for the query:
var url = (location.origin).concat(location.pathname).concat(location.hash);
Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash)
.
It's better practice to use concat
to join Javascript strings together (rather than +
): in some situations it avoids problems such as type confusion.
public static void copyInputStreamToFile(InputStream input, File file) {
try (OutputStream output = new FileOutputStream(file)) {
input.transferTo(output);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
java.io.InputStream#transferTo is available since Java 9.
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
I've managed a project that does this with sockets for years. Zebra's typically use port 6101. I'll look through the code and post what I can.
public void SendData(string zpl)
{
NetworkStream ns = null;
Socket socket = null;
try
{
if (printerIP == null)
{
/* IP is a string property for the printer's IP address. */
/* 6101 is the common port of all our Zebra printers. */
printerIP = new IPEndPoint(IPAddress.Parse(IP), 6101);
}
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
socket.Connect(printerIP);
ns = new NetworkStream(socket);
byte[] toSend = Encoding.ASCII.GetBytes(zpl);
ns.Write(toSend, 0, toSend.Length);
}
finally
{
if (ns != null)
ns.Close();
if (socket != null && socket.Connected)
socket.Close();
}
}
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
It looks like sklearn requires the data shape of (row number, column number).
If your data shape is (row number, ) like (999, )
, it does not work.
By using numpy.reshape()
, you should change the shape of the array to (999, 1)
, e.g. using
data=data.reshape((999,1))
In my case, it worked with that.
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:@"123.45"];
NSLog(@"My Number : %@",myNumber);
Dim array As String() = Array.Empty(Of String)
You can create the single value array key-value as
$new_row = array($row["datasource_id"]=>$row["title"]);
inside while loop, and then use array_merge
function in loop to combine the each new $new_row
array.
Although the previous answers are all valid answers - it might be advisable to append all these to a documentFragmnet first, then append that document fragment as an element after...
See John Resig's thoughts on the matter...
Something along the lines of:
var frag = document.createDocumentFragment();
for(item in data.Events)
{
var option = document.createElement("option");
option.setAttribute("value", data.Events[item].Key);
option.innerText = data.Events[item].Value;
frag.appendChild(option);
}
eventDrop.empty();
eventDrop.append(frag);
You can try finishAffinity()
, it closes all current activities and works on and above Android 4.1
As of 2020, the correct answer is :
driver.maximize_window()
There is now a much better solution, a lot more elegant, based on fenced div
, which have been implemented in pandoc
, as explained here:
::: {.center data-latex=""}
Some text here...
:::
All you need to do is to change your css
file accordingly. The following chunk for instance does the job:
```{cat, engine.opts = list(file = "style.css")}
.center {
text-align: center;
}
```
(Obviously, you can also directly type the content of the chunk into your .css
file...).
The tex
file includes the proper centering commands.
The crucial advantage of this method is that it allows writing markdown
code inside the block.
In my previous answer, r ctrFmt("Centered **text** in html and pdf!")
does not bold for the word "text", but it would if inside a fenced div
.
For images, etc... the lua
filter is available here
Using java 8 LocalDateTime
and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Are you sure that floated block-level elements are the best solution to this problem?
Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.
I think important to emphasize - using Except method will return you items who are in the first without the items in the second one only. It does not return those elements in second that do not appear in first.
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2).ToList(); //list3 contains only 1, 2
But if you want get real difference between two lists:
Items who are in the first without the items in the second one and items who are in the second without the items in the first one.
You need using Except twice:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list3 = list1.Except(list2); //list3 contains only 1, 2
var list4 = list2.Except(list1); //list4 contains only 6, 7
var resultList = list3.Concat(list4).ToList(); //resultList contains 1, 2, 6, 7
Or you can use SymmetricExceptWith method of HashSet. But it changes the set on which called:
var list1 = new List<int> { 1, 2, 3, 4, 5};
var list2 = new List<int> { 3, 4, 5, 6, 7 };
var list1Set = list1.ToHashSet(); //.net framework 4.7.2 and .net core 2.0 and above otherwise new HashSet(list1)
list1Set.SymmetricExceptWith(list2);
var resultList = list1Set.ToList(); //resultList contains 1, 2, 6, 7
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
$utfEncodedArray = array_map("utf8_encode", $inputArray );
Does the job and returns a serialized array with numeric keys (not an assoc).
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}
This worked for me:
$ sudo apt-get -y install php5.6-pgsql
$ sudo service apache2 restart
I am working with 32bit Ubuntu 14
ID is used to uniquely identify an element.
Name is used in forms.Although you submit a form, if you dont give any name, nothing will will be submitted. Hence form elements need a name to get identified by form methods like "get or push".
And the ones only with name attribute will go out.
If you want this in ASP.NET MVC Controller, use
using Microsoft.AspNet.Identity;
User.Identity.GetUserId();
You need to add using
statement because GetUserId()
won't be there without it.
time = Time.zone.now()
It will work as
irb> Time.zone.now
=> 2017-12-02 12:06:41 UTC
// On the state
constructor() {
this.state = {
email: ''
}
}
// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}
<Input
value={this.state.email ? this.state.email : ''}
onChange={event => this.setState({ email: event.target.value)}
type="text"
name="emailAddress"
placeholder="[email protected]" />
I haven't done any benchmarks, but this recipe "works for me".
The short version: use '%x' % val
, then unhexlify
the result. The devil is in the details, though, as unhexlify
requires an even number of hex digits, which %x
doesn't guarantee. See the docstring, and the liberal inline comments for details.
from binascii import unhexlify
def long_to_bytes (val, endianness='big'):
"""
Use :ref:`string formatting` and :func:`~binascii.unhexlify` to
convert ``val``, a :func:`long`, to a byte :func:`str`.
:param long val: The value to pack
:param str endianness: The endianness of the result. ``'big'`` for
big-endian, ``'little'`` for little-endian.
If you want byte- and word-ordering to differ, you're on your own.
Using :ref:`string formatting` lets us use Python's C innards.
"""
# one (1) hex digit per four (4) bits
width = val.bit_length()
# unhexlify wants an even multiple of eight (8) bits, but we don't
# want more digits than we need (hence the ternary-ish 'or')
width += 8 - ((width % 8) or 8)
# format width specifier: four (4) bits per hex digit
fmt = '%%0%dx' % (width // 4)
# prepend zero (0) to the width, to zero-pad the output
s = unhexlify(fmt % val)
if endianness == 'little':
# see http://stackoverflow.com/a/931095/309233
s = s[::-1]
return s
...and my nosetest unit tests ;-)
class TestHelpers (object):
def test_long_to_bytes_big_endian_small_even (self):
s = long_to_bytes(0x42)
assert s == '\x42'
s = long_to_bytes(0xFF)
assert s == '\xff'
def test_long_to_bytes_big_endian_small_odd (self):
s = long_to_bytes(0x1FF)
assert s == '\x01\xff'
s = long_to_bytes(0x201FF)
assert s == '\x02\x01\xff'
def test_long_to_bytes_big_endian_large_even (self):
s = long_to_bytes(0xab23456c8901234567)
assert s == '\xab\x23\x45\x6c\x89\x01\x23\x45\x67'
def test_long_to_bytes_big_endian_large_odd (self):
s = long_to_bytes(0x12345678901234567)
assert s == '\x01\x23\x45\x67\x89\x01\x23\x45\x67'
def test_long_to_bytes_little_endian_small_even (self):
s = long_to_bytes(0x42, 'little')
assert s == '\x42'
s = long_to_bytes(0xFF, 'little')
assert s == '\xff'
def test_long_to_bytes_little_endian_small_odd (self):
s = long_to_bytes(0x1FF, 'little')
assert s == '\xff\x01'
s = long_to_bytes(0x201FF, 'little')
assert s == '\xff\x01\x02'
def test_long_to_bytes_little_endian_large_even (self):
s = long_to_bytes(0xab23456c8901234567, 'little')
assert s == '\x67\x45\x23\x01\x89\x6c\x45\x23\xab'
def test_long_to_bytes_little_endian_large_odd (self):
s = long_to_bytes(0x12345678901234567, 'little')
assert s == '\x67\x45\x23\x01\x89\x67\x45\x23\x01'
From what I understand, you struggle with what to put into your template.
I'll show an example:
<ul>
{% for guest in guests %}
<li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
{% endfor %}
</ul>
Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.
If you are looking for a JavaScript solution, here's my gist:
https://gist.github.com/sillicon/4abcd9079a7d29cbb53ebee547b55fba
The basic idea is the same, take the screen shot first, then crop it. However, my solution will not require other libraries, just pure WebDriver API code. However, the side effect is that it may increase the load of your testing browser.
You can use this simple ES6 method
const lastChar = (str) => str.split('').reverse().join(',').replace(',', '')[str.length === str.length + 1 ? 1 : 0];_x000D_
_x000D_
_x000D_
// example_x000D_
console.log(lastChar("linto.yahoo.com."));
_x000D_
This will work in every browsers.
You can still get not-a-number (NaN) values from simple arithmetic involving inf
:
>>> 0 * float("inf")
nan
Note that you will normally not get an inf
value through usual arithmetic calculations:
>>> 2.0**2
4.0
>>> _**2
16.0
>>> _**2
256.0
>>> _**2
65536.0
>>> _**2
4294967296.0
>>> _**2
1.8446744073709552e+19
>>> _**2
3.4028236692093846e+38
>>> _**2
1.157920892373162e+77
>>> _**2
1.3407807929942597e+154
>>> _**2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
OverflowError: (34, 'Numerical result out of range')
The inf
value is considered a very special value with unusual semantics, so it's better to know about an OverflowError
straight away through an exception, rather than having an inf
value silently injected into your calculations.
Request-scoped beans can be autowired with the request object.
private @Autowired HttpServletRequest request;
On any other element, I would use the scrollHeight
of the DOM object and set the height accordingly. I don't know if this would work on an iframe (because they're a bit kooky about everything) but it's certainly worth a try.
Edit: Having had a look around, the popular consensus is setting the height from within the iframe using the offsetHeight
:
function setHeight() {
parent.document.getElementById('the-iframe-id').style.height = document['body'].offsetHeight + 'px';
}
And attach that to run with the iframe-body's onLoad
event.
Ben Swinburne answer was so helpful.
The code below is for those who have their PDF
file in database like me.
$pdf = DB::table('exportfiles')->select('pdf')->where('user_id', $user_id)->first();
return Response::make(base64_decode( $pdf->pdf), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"',
]);
Where $pdf->pdf
is the file column in database.
Simply use this function and pass the count of number you want to generate
Code:
function randomFix($length)
{
$random= "";
srand((double)microtime()*1000000);
$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
$data .= "0FGH45OP89";
for($i = 0; $i < $length; $i++)
{
$random .= substr($data, (rand()%(strlen($data))), 1);
}
return $random;}
In case of this similar error Warning: Error in $: object of type 'closure' is not subsettable [No stack trace available]
Just add corresponding package name using :: e.g.
instead of tags(....)
write shiny::tags(....)
For Abbreviated Month Names : "Aug"
DateTimeFormatInfo.GetAbbreviatedMonthName Method (Int32)
Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(8)
For Full Month Names : "August"
DateTimeFormatInfo.GetMonthName Method (Int32)
Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object.
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(8);
Well, WelcomeMessage is just a variable name for message (actual model with data). Basically, you are binding the model with the welcomePage here. The Model (message) will be available in welcomePage.jsp as WelcomeMessage. Here is a simpler example:
ModelAndView("hello","myVar", "Hello World!");
In this case, my model is a simple string (In applications this will be a POJO with data fetched for DB or other sources.). I am assigning it to myVar and my view is hello.jsp. Now, myVar is available for me in hello.jsp and I can use it for display.
In the view, you can access the data though:
${myVar}
Similarly, You will be able to access the model through WelcomeMessage variable.
SOLUTION OF Regsvr32: DllRegisterServer entry point was not found,
<meta name="viewport" content="width=320, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
Also making sure height=device-height
is not present in this meta tag helps prevent additional footer padding that normally would not exist on the page. The menubar height adds to the viewport height causing a fixed background to become scrollable.
Unlike the solutions here, I needed to convert to/from UTF-8 data. For this purpose, I coded the following two functions, using the (un)escape/(en)decodeURIComponent trick. They're pretty wasteful of memory, allocating 9 times the length of the encoded utf8-string, though those should be recovered by gc. Just don't use them for 100mb text.
function utf8AbFromStr(str) {
var strUtf8 = unescape(encodeURIComponent(str));
var ab = new Uint8Array(strUtf8.length);
for (var i = 0; i < strUtf8.length; i++) {
ab[i] = strUtf8.charCodeAt(i);
}
return ab;
}
function strFromUtf8Ab(ab) {
return decodeURIComponent(escape(String.fromCharCode.apply(null, ab)));
}
Checking that it works:
strFromUtf8Ab(utf8AbFromStr('latin????????aß?de???????'))
-> "latin????????aß?de???????"
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
from StringIO import StringIO
out = StringIO()
out = tree.export_graphviz(clf, out_file=out)
print out.getvalue()
You can see a digraph Tree. Then, clf.tree_.feature
and clf.tree_.value
are array of nodes splitting feature and array of nodes values respectively. You can refer to more details from this github source.
If anyone is including a custom argLine argument, you must reconsider because it is likely the source of your issues with the memory allocation.
For Example (I used to have):
<argLine>XX:MaxPermSize=4096m ${argLine}</argLine>
Now I use hard specified values:
<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
For whatever reason, Applications that integrate with Surefire such as Jacoco, dont request enough memory to coexist with the testing that happens at build time.
In my case, I draw my canvas into linearlayout. To clean and redraw again:
LinearLayout linearLayout = findViewById(R.id.myCanvas);
linearLayout.removeAllViews();
and then, I call the class with the new values:
Lienzo fondo = new Lienzo(this,items);
linearLayout.addView(fondo);
This is the class Lienzo:
class Lienzo extends View {
Paint paint;
RectF contenedor;
Path path;
ArrayList<Items>elementos;
public Lienzo(Context context,ArrayList<Items> elementos) {
super(context);
this.elementos=elementos;
init();
}
private void init() {
path=new Path();
paint = new Paint();
contenedor = new RectF();
paint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
contenedor.left = oneValue;
contenedor.top = anotherValue;
contenedor.right = anotherValue;
contenedor.bottom = anotherValue;
float angulo = -90; //starts drawing at 12 o'clock
//total= sum of all element values
for (int i=0;i<elementos.size();i++){
if (elementos.get(i).angulo!=0 && elementos.get(i).visible){
paint.setColor(elementos.get(i).backColor);
canvas.drawArc(contenedor,angulo,(float)(elementos.get(i).value*360)/total,true,paint);
angulo+=(float)(elementos.get(i).value*360)/total;
}
} //for example
}
}
Could you add z-index style to the two sections so that the one you want appears on top?
Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).
$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});
You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:
$(window).unload(function () { debugger; console.log("window unloaded");});
And you will see what I mean.
` Please include either of these:
`#include<sstream>`
using std::istringstream;
app.use()
is intended for binding middleware to your application. The path
is a "mount" or "prefix" path and limits the middleware to only apply to any paths requested that begin with it. It can even be used to embed another application:
// subapp.js
var express = require('express');
var app = modules.exports = express();
// ...
// server.js
var express = require('express');
var app = express();
app.use('/subapp', require('./subapp'));
// ...
By specifying /
as a "mount" path, app.use()
will respond to any path that starts with /
, which are all of them and regardless of HTTP verb used:
GET /
PUT /foo
POST /foo/bar
app.get()
, on the other hand, is part of Express' application routing and is intended for matching and handling a specific route when requested with the GET
HTTP verb:
GET /
And, the equivalent routing for your example of app.use()
would actually be:
app.all(/^\/.*/, function (req, res) {
res.send('Hello');
});
(Update: Attempting to better demonstrate the differences.)
The routing methods, including app.get()
, are convenience methods that help you align responses to requests more precisely. They also add in support for features like parameters and next('route')
.
Within each app.get()
is a call to app.use()
, so you can certainly do all of this with app.use()
directly. But, doing so will often require (probably unnecessarily) reimplementing various amounts of boilerplate code.
Examples:
For simple, static routes:
app.get('/', function (req, res) {
// ...
});
vs.
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
// ...
});
With multiple handlers for the same route:
app.get('/', authorize('ADMIN'), function (req, res) {
// ...
});
vs.
const authorizeAdmin = authorize('ADMIN');
app.use('/', function (req, res, next) {
if (req.method !== 'GET' || req.url !== '/')
return next();
authorizeAdmin(req, res, function (err) {
if (err) return next(err);
// ...
});
});
With parameters:
app.get('/item/:id', function (req, res) {
let id = req.params.id;
// ...
});
vs.
const pathToRegExp = require('path-to-regexp');
function prepareParams(matches, pathKeys, previousParams) {
var params = previousParams || {};
// TODO: support repeating keys...
matches.slice(1).forEach(function (segment, index) {
let { name } = pathKeys[index];
params[name] = segment;
});
return params;
}
const itemIdKeys = [];
const itemIdPattern = pathToRegExp('/item/:id', itemIdKeys);
app.use('/', function (req, res, next) {
if (req.method !== 'GET') return next();
var urlMatch = itemIdPattern.exec(req.url);
if (!urlMatch) return next();
if (itemIdKeys && itemIdKeys.length)
req.params = prepareParams(urlMatch, itemIdKeys, req.params);
let id = req.params.id;
// ...
});
Note: Express' implementation of these features are contained in its
Router
,Layer
, andRoute
.
Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.
Use return
statement at end of function to return value.
e.g.:
Return None value.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
this works with "NA"
not for NA
comments = c("no","yes","NA")
for (l in 1:length(comments)) {
#if (!is.na(comments[l])) print(comments[l])
if (comments[l] != "NA") print(comments[l])
}
This works well
Given that the only logical difference between the handlers is the value of the button clicked, you can use the this
keyword to refer to the element which raised the event and get the val()
from that. Try this:
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/test/",
data: {
id: $(this).val(), // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
});
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results
field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
To makes an "empty" all-0 guid like 00000000-0000-0000-0000-000000000000
.
var makeAllZeroGuID = new System.Guid();
or
var makeAllZeroGuID = System.Guid.Empty;
To makes an actual guid with a unique value, what you probably want.
var uniqueGuID = System.Guid.NewGuid();
Additional Solution: use Restul api wrapper libraries written in Java
/ python
/ Ruby
- An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.
For documentation and links: Remote Access API
char(13)
is CR
. For DOS-/Windows-style CRLF
linebreaks, you want char(13)+char(10)
, like:
'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
The simplest way is to drop the user that owns the objects with the cascade command.
DROP USER username CASCADE
As already mentioned, this is caused by a circular dependency. What has not been mentioned is that when you're using Python typing module and you import a class only to be used to annotate Types, you can use Forward references:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
and remove the dependency (the import), e.g. instead of
from my_module import Tree
def func(arg: Tree):
# code
do:
def func(arg: 'Tree'):
# code
(note the removed import
statement)
Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.
Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:
# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')
# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']
# Setup the ordering
df.zipcode_ordered.cat.set_categories(
new_categories = [90211, 90210], ordered = True, inplace = True
)
# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
# zipcode_category zipcode_ordered zipcode_ordered_id
# 90210 90210 1
# 90211 90211 0
More details on setting ordered categories can be found at the pandas website:
https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order
A simplified way to compare 2 directories using the DIFF command
diff filename.1 filename.2 > filename.dat >>Enter
open filename.dat after the run is complete
and you will see: Only in filename.1: filename.2 Only in: directory_name: name_of_file1 Only in: directory_Name: name_of_file2
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
it means pointer you can use this link to get more info about pointer http://www.cprogramming.com/tutorial/c/lesson6.html
It depends what is the character and what encoding it is in:
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.
An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).
A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.
A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).
An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.
The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.
That would mean that there are between 0.03125 and 0.125 characters in a bit.
<a href="javascript:
console.dir(Object.getOwnPropertyDescriptors(HTMLDivElement))">
1. Direct Action Without Following href Link
</a>
<br><br>
<a href="javascript:my_func('http://diasmath.blogg.org')">
2. Indirect Action (Function Call) Without Following Normal href Link
</a>
<br><br>
<!-- Avec « return false » l'action par défaut de l'élément
// <a></a> (ouverture de l'URL pointée par
// « href="http://www.centerblog.net/gha" »)
// ne s'exécute pas.
-->
<a target=_new href="http://www.centerblog.net/gha"
onclick="my_func('http://diasmath.blogg.org');
return false">
3. Suivi par défaut du Lien Normal href Désactivé avec
« return false »
</a>
<br><br>
<!-- Avec ou sans « return true » l'action par défaut de l'élément
// s'exécute pas.
-->
<a target=_new href="http://gha.centerblog.net"
onclick="my_func('http://diasmath.blogg.org');">
4. Suivi par défaut du Lien Normal href Conservé avec ou sans
« return true » qui est la valeur retournée par défaut.
</a>
<br><br>
<!-- Le diese tout seul ne suit pas le lien href. -->
<a href="#" onclick="my_func('http://diasmath.blogg.org')">
5. Lien Dièse en Singleton (pas de suivi href)
</a>
<script language="JavaScript">
function my_func(s) {
console.dir(Object.getOwnPropertyDescriptors(Document));
window.open(s)
}
</script>
<br>
<br>
<!-- Avec GESTION D'ÉVÉNEMENT.
// Événement (event) = click du lien
// Event Listener = "click"
// my_func2 = gestionnaire d'événement
-->
<script language="JavaScript">
function my_func2(event) {
console.dir(event);
window.open(event.originalTarget["href"])
}
</script>
<a target=_blank href="http://dmedit.centerblog.net"
id="newel" onclick="return false">
6. By specifying another eventlistener
(and deactivating the default).
</a>
<script language="JavaScript">
let a=document.getElementById("newel");
a.addEventListener("click",my_func2)
</script>
My bet is that you have a package called org.ivec.eresearch.knowledgeportal.model.category (small c
) and are running on a non-case sensitive filesystem like Windows or Mac. It seems that the compiler gets confused when a class and package exist.
You can either renamed the class "Category" or the package "category" and this error will go away. Unfortunately I'm not sure if this is a Tomcat or ECJ bug.
None of the answers or work-arounds helped me. Most were dealing with the tableView itself. What was causing the issue for me was the view I was adding the tableView or collectionView onto. This is what fixed it for me:
SWIFT 5
edgesForExtendedLayout = []
I put that in my viewDidLoad and the annoying gap went away. Hope this helps.
This lists all the files (and only the files) in the current directory:
for /r %i in (*) do echo %i
Also if you run that command in a batch file you need to double the % signs.
for /r %%i in (*) do echo %%i
(thanks @agnul)
Existing answers are all talking about removing the unwanted files from the last commit.
If you want to remove unwanted files from an old commit (even pushed) and don't want to create a new commit, which is unnecessary, because of the action:
1.
Find the commit that you want the file to conform to.
git checkout <commit_id> <path_to_file>
you can do this multiple times if you want to remove many files.
2.
git commit -am "remove unwanted files"
3.
Find the commit_id of the commit on which the files were added mistakenly, let's say "35c23c2" here
git rebase 35c23c2~1 -i // notice: "~1" is necessary
This command opens the editor according to your settings. The default one is vim.
Move the last commit, which should be "remove unwanted files", to the next line of the incorrect commit("35c23c2" in our case), and set the command as fixup
:
pick 35c23c2 the first commit
fixup 0d78b28 remove unwanted files
You should be good after saving the file.
To finish :
git push -f
If you unfortunately get conflicts, you have to solve them manually.
Is this what you're asking for?
int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));
Use net time
net time \\timesrv /set /yes
after your comment try this one in evelated prompt :
w32tm /config /update /manualpeerlist:yourtimerserver
<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />
Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/
I did below and it works like charm.
<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>
The following statement causes a user's password to expire:
ALTER USER user PASSWORD EXPIRE;
If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.
ALTER USER scott IDENTIFIED BY password;
Will set/reset the users password.
See the alter user doc for more info
No need to calculate the actual height of the contents; you can just scroll down a lot:
$(function () {
$('.messageScrollArea').scrollTop(1E10);
});
Such as:
DROP TRIGGER IF EXISTS `update_tablename_trigger`;
DELIMITER //
CREATE TRIGGER `update_tablename_trigger` BEFORE UPDATE ON `tablename`
FOR EACH ROW SET NEW.`column_name` = NOW()
//
DELIMITER ;
axios.post('url', {"body":data}, {
headers: {
'Content-Type': 'application/json'
}
}
)
_x000D_
You can escape the apostrophe with a \
character as well:
mystring.replace('\'', '')
Using true
/false
as the value will have the field pre-filled if the model passed to the form has this attribute already filled:
= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)
There is no work-around for this aside from ditching the select
element.
Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
the only thing you can do is to change your signature to
public static <E> E[] appendToArray(E[] array, E item)
Important details:
Generic expressions preceding the return value always introduce (declare) a new generic type variable.
Additionally, type variables between types (ArrayUtils
) and static methods (appendToArray
) never interfere with each other.
So, what does this mean:
In my answer <E>
would hide the E
from ArrayUtils<E>
if the method wouldn't be static
. AND <E>
has nothing to do with the E
from ArrayUtils<E>
.
To reflect this fact better, a more correct answer would be:
public static <I> I[] appendToArray(I[] array, I item)
querySelector()
matched the id in document. You must write id of password in .html
Then pass it to querySelector()
with #symbol & .value property
.
Example:
let myVal = document.querySelector('#pwd').value
I had drawn a splash screen (32bpp BGRA) with "transparent" background color in VS2013 and put a pictureBox in a form for display. For me a combination of above answers worked:
public Form1()
{
InitializeComponent();
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = this.pictureBox1.BackColor;
this.TransparencyKey = this.pictureBox1.BackColor;
}
So make sure you use the same BackColor everywhere and set that color as the TransparencyKey.
If you just want the list, then you should ask here: http://unix.stackexchange.com
The answer is: cd / && find -name *.js
If you want to implement this, you have to specify the language.
You'll have to use a favicon for your page.
put this in the head-tag:
<link rel="shortcut icon" href="/favicon.png" type="image/png">
where favicon.png is preferably a 16x16 png image.
getClass()
function using constructor.prototype.nameI found a way to access the class
that is much cleaner than some of the solutions above; here it is.
function getClass(obj) {
// if the type is not an object return the type
if((let type = typeof obj) !== 'object') return type;
//otherwise, access the class using obj.constructor.name
else return obj.constructor.name;
}
the constructor has a property called name
accessing that will give you the class name.
cleaner version of the code:
function getClass(obj) {
// if the type is not an object return the type
let type = typeof obj
if((type !== 'object')) {
return type;
} else { //otherwise, access the class using obj.constructor.name
return obj.constructor.name;
}
}
plt.imshow
displays the image on the axes, but if you need to display multiple images you use show()
to finish the figure. The next example shows two figures:
import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()
In Google Colab, if you comment out the show()
method from previous example just a single image will display (the later one connected with X_train[1]
).
Here is the content from the help:
plt.show(*args, **kw)
Display a figure.
When running in ipython with its pylab mode, display all
figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until
the figures have been closed; in interactive mode it has no
effect unless figures were created prior to a change from
non-interactive to interactive mode (not recommended). In
that case it displays the figures but does not block.
A single experimental keyword argument, *block*, may be
set to True or False to override the blocking behavior
described above.
plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
Display an image on the axes.
Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
Display the image in `X` to current axes. `X` may be an
array or a PIL image. If `X` is an array, it
can have the following shapes and types:
- MxN -- values to be mapped (float or int)
- MxNx3 -- RGB (float or uint8)
- MxNx4 -- RGBA (float or uint8)
The value for each component of MxNx3 and MxNx4 float arrays
should be in the range 0.0 to 1.0. MxN arrays are mapped
to colors based on the `norm` (mapping scalar to scalar)
and the `cmap` (mapping the normed scalar to a color).
This occurred to me when I applied the 2017 Fall Creator Update. I was able to resolve by repairing IIS 10.0 Express (I do not have IIS installed on my box.)
Note: As a user pointed out in the comments,
Repair can be found in "Programs and Features" - the "classic" control panel.
Ignacio Vazquez-Abrams' approved answer is quite right. It is, however, from the Python 2 generation. An update for the now-current Python 3 would be:
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(object, metaclass=MC):
pass
print(C)
If you want code that runs across both Python 2 and Python 3, the six module has you covered:
from __future__ import print_function
from six import with_metaclass
class MC(type):
def __repr__(self):
return 'Wahaha!'
class C(with_metaclass(MC)):
pass
print(C)
Finally, if you have one class that you want to have a custom static repr, the class-based approach above works great. But if you have several, you'd have to generate a metaclass similar to MC
for each, and that can get tiresome. In that case, taking your metaprogramming one step further and creating a metaclass factory makes things a bit cleaner:
from __future__ import print_function
from six import with_metaclass
def custom_class_repr(name):
"""
Factory that returns custom metaclass with a class ``__repr__`` that
returns ``name``.
"""
return type('whatever', (type,), {'__repr__': lambda self: name})
class C(with_metaclass(custom_class_repr('Wahaha!'))): pass
class D(with_metaclass(custom_class_repr('Booyah!'))): pass
class E(with_metaclass(custom_class_repr('Gotcha!'))): pass
print(C, D, E)
prints:
Wahaha! Booyah! Gotcha!
Metaprogramming isn't something you generally need everyday—but when you need it, it really hits the spot!
This should disconnect everyone else, and leave you as the only user:
alter database YourDb set single_user with rollback immediate
Note: Don't forget
alter database YourDb set MULTI_USER
after you're done!
The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits>
<headerLimits>
<add header="Content-type" sizeLimit="100" />
</headerLimits>
</requestLimits>
</requestFiltering>
</security>
</system.webServer>
</configuration>
Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
If you use a context manager, the file is closed automatically for you
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
If you're using Python2.6 or higher, it's preferred to use str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
For python2.7 and higher you can use {}
instead of {0}
In Python3, there is an optional file
parameter to the print
function
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Python3.6 introduced f-strings for another alternative
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
v-bind
and v-on
are two frequently used directives in vuejs html template.
So they provided a shorthand notation for the both of them as follows:
You can replace v-on:
with @
v-on:click='someFunction'
as:
@click='someFunction'
Another example:
v-on:keyup='someKeyUpFunction'
as:
@keyup='someKeyUpFunction'
Similarly, v-bind
with :
v-bind:href='var1'
Can be written as:
:href='var1'
Hope it helps!
There are many ways, one is to use a counter:
$i = 0;
foreach ($arr as $k => $v) {
/* Do stuff */
if (++$i == 2) break;
}
Other way would be to slice the first 2 elements, this isn't as efficient though:
foreach (array_slice($arr, 0, 2) as $k => $v) {
/* Do stuff */
}
You could also do something like this (basically the same as the first foreach, but with for):
for ($i = 0, reset($arr); list($k,$v) = each($arr) && $i < 2; $i++) {
}
I suspect you are running Android 6.0 Marshmallow (API 23) or later. If this is the case, you must implement runtime permissions before you try to read/write external storage.
A DataFrame
is defined well with a google search for "DataFrame definition":
A data frame is a table, or two-dimensional array-like structure, in which each column contains measurements on one variable, and each row contains one case.
So, a DataFrame
has additional metadata due to its tabular format, which allows Spark to run certain optimizations on the finalized query.
An RDD
, on the other hand, is merely a Resilient Distributed Dataset that is more of a blackbox of data that cannot be optimized as the operations that can be performed against it, are not as constrained.
However, you can go from a DataFrame to an RDD
via its rdd
method, and you can go from an RDD
to a DataFrame
(if the RDD is in a tabular format) via the toDF
method
In general it is recommended to use a DataFrame
where possible due to the built in query optimization.
By looping it can be done the following way :)
num1= int(input('Enter the number'))
sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
y = [] #making a list
while True:
if(sum1==0):#checking if the number is not zero so it can break if it is
break
d = sum1%10 #last number of your integer is saved in d
sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
y.append(d) # appending the last number in the first place
y.reverse()#as last is in first , reversing the number to orginal form
print(y)
Answer becomes
Enter the number2342
[2, 3, 4, 2]
You're looking for the SyndicationFeed
class, which does exactly that.
Unzip the github project to a folder. Open Android Studio. Go to File -> New -> Import Project. Then choose the specific project you want to import and then click Next->Finish. It will build the Gradle automatically and'll be ready for you to use.
P.S: In some versions of Android Studio a certain error occurs-
error:package android.support.v4.app does not exist.
To fix it go to Gradle Scripts->build.gradle(Module:app) and the add the dependecies:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
Enjoy working in Android Studio
If you are using Spring MVC or Spring Boot try to avoid: @ModelAttribute("user") in one controoler, and in other controller model.addAttribute("user", userRepository.findOne(someId);
This situation can produce such error.
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
What you want to do is fetch the value from the input and assign it to a new Date instance.
let date = document.getElementById('dateInput');
let formattedDate = new Date(date.value);
console.log(formattedDate);
Try this for match condition if scroll to bottom end
if ($(this)[0].scrollHeight - $(this).scrollTop() ==
$(this).outerHeight()) {
//code for your custom logic
}
For everyone coming to this site having the same problem with commata instead, change:
$num = number_format($value, 1, ',', '');
to:
$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100
If there are two zeros to be removed, then change to:
$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100
I'd like to add this because I spent some time solving the issue and did not find an answer here for combination of variables usage in cron and virtualenv. So maybe it'll help someone.
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DIR_SMTH="cd /smth"
VENV=". venv/bin/activate"
CMD="some_python_bin do_something"
# m h dom mon dow command
0 * * * * $DIR_SMTH && $VENV && $CMD -k2 some_target >> /tmp/crontest.log 2>&1
It did not work well when it was configured like
DIR_SMTH="cd /smth && . venv/bin/activate"
Thanks @davidwinterbottom, @reed-sandberg and @mkb for giving the right direction. The accepted answer actually works fine until your python need to run a script which have to run another python binary from venv/bin directory.
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
You're not going to "simply" understand something complex.
WSDL is an XML-based language for describing a web service. It describes the messages, operations, and network transport information used by the service. These web services usually use SOAP, but may use other protocols.
A WSDL is readable by a program, and so may be used to generate all, or part of the client code necessary to call the web service. This is what it means to call SOAP-based web services "self-describing".
REST is not related to WSDL at all.
Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.
Source: iTunes Connect Developer Guide - Transferring and Deleting Apps
You should not place an using
directive in an header file, it creates unnecessary headaches.
Also you need an include guard in your header.
EDIT: of course, after having fixed the include guard issue, you also need a complete declaration of student in the header file. As pointed out by others the forward declaration is not sufficient in your case.
You can make function getStyles
that'll take an element and other arguments are properties that's values you want.
const convertRestArgsIntoStylesArr = ([...args]) => {
return args.slice(1);
}
const getStyles = function () {
const args = [...arguments];
const [element] = args;
let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);
const styles = window.getComputedStyle(element);
const stylesObj = stylesProps.reduce((acc, v) => {
acc[v] = styles.getPropertyValue(v);
return acc;
}, {});
return stylesObj;
};
Now, you can use this function like this:
const styles = getStyles(document.body, "height", "width");
OR
const styles = getStyles(document.body, ["height", "width"]);
We just ran into this same issue. Our Cpanel has expanded from PHP only to PHP and .NET and defaulted to .NET.
Log in to you Cpanel and make sure you don’t have the same issue.