preg_replace("/[[:blank:]]+/"," ",$input)
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax
kwarg to tell fig.colorbar
to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
You can use InlineComparer
public class InlineComparer<T> : IEqualityComparer<T>
{
//private readonly Func<T, T, bool> equalsMethod;
//private readonly Func<T, int> getHashCodeMethod;
public Func<T, T, bool> EqualsMethod { get; private set; }
public Func<T, int> GetHashCodeMethod { get; private set; }
public InlineComparer(Func<T, T, bool> equals, Func<T, int> hashCode)
{
if (equals == null) throw new ArgumentNullException("equals", "Equals parameter is required for all InlineComparer instances");
EqualsMethod = equals;
GetHashCodeMethod = hashCode;
}
public bool Equals(T x, T y)
{
return EqualsMethod(x, y);
}
public int GetHashCode(T obj)
{
if (GetHashCodeMethod == null) return obj.GetHashCode();
return GetHashCodeMethod(obj);
}
}
Usage sample:
var comparer = new InlineComparer<DetalleLog>((i1, i2) => i1.PeticionEV == i2.PeticionEV && i1.Etiqueta == i2.Etiqueta, i => i.PeticionEV.GetHashCode() + i.Etiqueta.GetHashCode());
var peticionesEV = listaLogs.Distinct(comparer).ToList();
Assert.IsNotNull(peticionesEV);
Assert.AreNotEqual(0, peticionesEV.Count);
Source:
https://stackoverflow.com/a/5969691/206730
Using IEqualityComparer for Union
Can I specify my explicit type comparator inline?
There are multiple issues with the MMC however as on almost every PC in my business the ask scheduler API will not open and has somehow been corrupted. So you cannot edit, delete or otherwise modify tasks that were developed before the API decided not to run anymore. The only way we have found to fix that issue is to totally wipe away a persons profile under the C:\Users\ area and force the system to recreate the log in once the person logs back in. This seems to fix the API issue and it works again, however the tasks are often not visible anymore to that user since the tasks developed are specific to the user and not the machine in Windows 7. The other odd thing is that sometimes, although not with any frequency that can be analyzed, the tasks still run even though the API is corrupted and will not open. The cause of this issue is apparently not known but there are many "fixes" described on various websites, but the user profile deletion and adding anew seems to work every time for at least a little while. The tasks are saved as XML now in WIN 7, so if you do find them in the system32/tasks folder you can delete them, or copy them to a new drive and then import them back into task scheduler. We went with the system scheduler software from Splinterware though since we had the same corruption issue multiple times even with the fix that does not seem to be permanent.
To complement @tyczj answer:
Generic Adapter Pseido code:
public abstract class GenericRecycleAdapter<T, K extends RecyclerView.ViewHolder> extends RecyclerView.Adapter{
private List<T> mList;
//default implementation code
public abstract int getLayout();
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(getLayout(), parent, false);
return getCustomHolder(v);
}
public Holders.TextImageHolder getCustomHolder(View v) {
return new Holders.TextImageHolder(v){
@Override
public void onClick(View v) {
onItem(mList.get(this.getAdapterPosition()));
}
};
}
abstract void onItem(T t);
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
onSet(mList.get(position), (K) holder);
}
public abstract void onSet(T item, K holder);
}
ViewHolder:
public class Holders {
public static class TextImageHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView text;
public TextImageHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
text.setOnClickListener(this);
}
@Override
public void onClick(View v) {
}
}
}
Adapter usage:
public class CategoriesAdapter extends GenericRecycleAdapter<Category, Holders.TextImageHolder> {
public CategoriesAdapter(List<Category> list, Context context) {
super(list, context);
}
@Override
void onItem(Category category) {
}
@Override
public int getLayout() {
return R.layout.categories_row;
}
@Override
public void onSet(Category item, Holders.TextImageHolder holder) {
}
}
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
There are 3 ways:
First way
You need specify the directory to store mysql data on your host machine. You can then remove the data container. Your mysql data will be saved on you local filesystem.
Mysql container definition must look like this:
mysql:
container_name: flask_mysql
restart: always
image: mysql:latest
environment:
MYSQL_ROOT_PASSWORD: 'test_pass' # TODO: Change this
MYSQL_USER: 'test'
MYSQL_PASS: 'pass'
volumes:
- /opt/mysql_data:/var/lib/mysql
ports:
- "3306:3306"
Second way
Would be to commit the data container before typing docker-compose down
:
docker commit my_data_container
docker-compose down
Third way
Also you can use docker-compose stop
instead of docker-compose down
(then you don't need to commit the container)
Here's one way to do it:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value. If you don't provide a default value, None
is returned.
if not any(d.get('main_color', default_value) == 'red' for d in a):
# does not exist
I was working on a dataframe and having no luck with the provided answers, it always returned 0 rows, so I found and used grepl:
df = df[grepl("downlink",df$Transmit.direction),]
Which basically trimmed my dataframe to only the rows that contained "downlink" in the Transmit direction column. P.S. If anyone can guess as to why I'm not seeing the expected behavior, please leave a comment.
Specifically to the original question:
expr[grepl("hesc",expr$cell_type),]
expr[grepl("bj fibroblast|hesc",expr$cell_type),]
Not sure what you meant with "Can I increase the size of this variable without worrying about the SQL limit?". As long you do not try to insert a more than 4000 VARCHAR2 into a VARCHAR2 SQL column there is nothing to worry about.
Here is the exact reference (this is 11g but true also for 10g)
http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm
VARCHAR2 Maximum Size in PL/SQL: 32,767 bytes Maximum Size in SQL 4,000 bytes
From the docs:
$ celery -A proj purge
or
from proj.celery import app
app.control.purge()
(EDIT: Updated with current method.)
Just use this website: http://ticons.fokkezb.nl :)
It makes it easier for you, and generates the correct sizes directly
Swift 4 example:
var filePath: String {
//manager lets you examine contents of a files and folders in your app.
let manager = FileManager.default
//returns an array of urls from our documentDirectory and we take the first
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
//print("this is the url path in the document directory \(String(describing: url))")
//creates a new path component and creates a new file called "Data" where we store our data array
return(url!.appendingPathComponent("Data").path)
}
I put the check in my loadData function which I called in viewDidLoad.
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
Then I defined loadData below.
func loadData() {
let manager = FileManager.default
if manager.fileExists(atPath: filePath) {
print("The file exists!")
//Do what you need with the file.
ourData = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as! Array<DataObject>
} else {
print("The file DOES NOT exist! Mournful trumpets sound...")
}
}
SQL Developer has a built-in reset password option that may work for your situation. It requires adding Oracle Instant Client to the workstation as well. When instant client is in the path when SQL developer launches you will get the following option enabled:
Oracle Instant Client does not need admin privileges to install, just the ability to write to a directory and add that directory to the users path. Most users have the privileges to do this.
Recap: In order to use Reset Password on Oracle SQL Developer:
At this point you can right click a data source and reset your password.
See http://www.thatjeffsmith.com/archive/2012/11/resetting-your-oracle-user-password-with-sql-developer/ for a complete walk-through
Also see the comment in the oracle docs: http://docs.oracle.com/cd/E35137_01/appdev.32/e35117/dialogs.htm#RPTUG41808
An alternative configuration to have SQL Developer (tested on version 4.0.1) recognize and use the Instant Client on OS X is:
(OS X) Refer to this question to resolve issues related to DYLD_LIBRARY_PATH environment variable. I used the following command and then restarted SQL Developer to pick up the change:
$ launchctl setenv DYLD_LIBRARY_PATH /path/to/oracle/instantclient_11_2
I came here and looking how to get the number of elements inside a JSONArray
. From your question i used length()
like that:
JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());
and it worked as expected. On the other hand jar.size();
(as proposed in the other answer) is not working for me.
So for future users searching (like me) how to get the size of a JSONArray
, length()
works just fine.
Why should I use it instead of optparse? Are their new features I should know about?
@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:
Why has yet another command-line parsing module been created?
That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?
Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email
package vs the myriad old ways to deal with similar issues isn't too far away either;-).
You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.
(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).
I had the same warning in VS 2017. As it turned out in my case I had added a unit test project and needed to set a dependency for the unit test on the DLL it was testing.
Install package : Microsoft.AspNet.WebApi.Cors
go to : App_Start --> WebApiConfig
Add :
var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);
Note : If you add '/' as end of the particular url not worked for me.
Try the following-sibling
axis (following-sibling::td
).
If your context allows it (technical constraints, etc.), use the JsonConvert.SerializeObject
method from Newtonsoft.Json : it will make your life easier.
Dictionary<string, string> localizedWelcomeLabels = new Dictionary<string, string>();
localizedWelcomeLabels.Add("en", "Welcome");
localizedWelcomeLabels.Add("fr", "Bienvenue");
localizedWelcomeLabels.Add("de", "Willkommen");
Console.WriteLine(JsonConvert.SerializeObject(localizedWelcomeLabels));
// Outputs : {"en":"Welcome","fr":"Bienvenue","de":"Willkommen"}
Place this at the top of your script. It will cause the script to prompt the user for a password. The resulting password can then be used elsewhere in your script via $pw.
Param(
[Parameter(Mandatory=$true, Position=0, HelpMessage="Password?")]
[SecureString]$password
)
$pw = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
If you want to debug and see the value of the password you just read, use:
write-host $pw
Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
startActivity(i);
}
});
Instead of using the placeholder text, you'll want to set the actual text
property of the field to MM/YYYY, set the delegate of the text field and listen for this method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // update the text of the label }
Inside that method, you can figure out what the user has typed as they type, which will allow you to update the label accordingly.
A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.
Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.
n = new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
I suggest you look at the article called "Short Introduction to log4j". It contains a short explanation of log levels and demonstrates how they can be used in practice. The basic idea of log levels is that you want to be able to configure how much detail the logs contain depending on the situation. For example, if you are trying to troubleshoot an issue, you would want the logs to be very verbose. In production, you might only want to see warnings and errors.
The log level for each component of your system is usually controlled through a parameter in a configuration file, so it's easy to change. Your code would contain various logging statements with different levels. When responding to an Exception
, you might call Logger.error
. If you want to print the value of a variable at any given point, you might call Logger.debug
. This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.
In the case of log4j at least, the ordering of log levels is:
DEBUG < INFO < WARN < ERROR < FATAL
Here is a short example from that article demonstrating how log levels work.
// get a logger instance named "com.foo"
Logger logger = Logger.getLogger("com.foo");
// Now set its level. Normally you do not need to set the
// level of a logger programmatically. This is usually done
// in configuration files.
logger.setLevel(Level.INFO);
Logger barlogger = Logger.getLogger("com.foo.Bar");
// This request is enabled, because WARN >= INFO.
logger.warn("Low fuel level.");
// This request is disabled, because DEBUG < INFO.
logger.debug("Starting search for nearest gas station.");
// The logger instance barlogger, named "com.foo.Bar",
// will inherit its level from the logger named
// "com.foo" Thus, the following request is enabled
// because INFO >= INFO.
barlogger.info("Located nearest gas station.");
// This request is disabled, because DEBUG < INFO.
barlogger.debug("Exiting gas station search");
Yes; copy the string to a char array, sort the char array, then copy that back into a string.
static string SortString(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}
Efficient way to iterate your ArrayList
followed by this link. This type will improve the performance of looping during iteration
int size = list.size();
for(int j = 0; j < size; j++) {
System.out.println(list.get(i));
}
Maybe it's the comma in your if
condition.
function answers() {
var answer=document.getElementById("mySelect");
if(answer[answer.selectedIndex].value == "To measure time.") {
alert("That's correct!");
}
}
You can also write it like this.
function answers(){
document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}
In the 'old days' you'd use a table and your menu items would be evenly spaced without having to explicitly state the width for the number of items.
If it wasn't for IE 6 and 7 (if that is of concern) then you can do the same in CSS.
<div class="demo">
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
CSS:
div.demo {
display: table;
width: 100%;
table-layout: fixed; /* For cells of equal size */
}
div.demo span {
display: table-cell;
text-align: center;
}
Without having to adjust for the number of items.
Example without table-layout:fixed
- the cells are evenly distributed across the full width, but they are not necessarily of equal size since their width is determined by their contents.
Example with table-layout:fixed
- the cells are of equal size, regardless of their contents. (Thanks to @DavidHerse in comments for this addition.)
If you want the first and last menu elements to be left and right justified, then you can add the following CSS:
div.demo span:first-child {
text-align: left;
}
div.demo span:last-child {
text-align: right;
}
If you add some debug after your call to latch.countDown(), this may help you understand its behaviour better.
latch.countDown();
System.out.println("DONE "+this.latch); // Add this debug
The output will show the Count being decremented. This 'count' is effectively the number of Runnable tasks (Processor objects) you've started against which countDown() has not been invoked and hence is blocked the main thread on its call to latch.await().
DONE java.util.concurrent.CountDownLatch@70e69696[Count = 2]
DONE java.util.concurrent.CountDownLatch@70e69696[Count = 1]
DONE java.util.concurrent.CountDownLatch@70e69696[Count = 0]
Resizing the default widget doesn’t work in all browsers, but you can make custom radio buttons with JavaScript. One of the ways is to create hidden radio buttons and then place your own images on your page. Clicking on these images changes the images (replaces the clicked image with an image with a radio button in a selected state and replaces the other images with radio buttons in an unselected state) and selects the new radio button.
Anyway, there is documentation on this subject. For example, read this: Styling Checkboxes and Radio Buttons with CSS and JavaScript.
Your error shows you are not compiling file with the definition of the insert
function. Update your command to include the file which contains the definition of that function and it should work.
In case you're already using the transform property for positioning your element (as I currently am), you can also animate the top margin:
.ball {
animation: bounce 1s infinite alternate;
-webkit-animation: bounce 1s infinite alternate;
}
@keyframes bounce {
from {
margin-top: 0;
}
to {
margin-top: -15px;
}
}
Based on the doc
<div class="row">
<div class="span4 collapse-group">
<h2>Heading</h2>
<p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
<p><a class="btn" href="#">View details »</a></p>
</div>
</div>
$('.row .btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $collapse = $this.closest('.collapse-group').find('.collapse');
$collapse.collapse('toggle');
});
I was on the GM seed of Xcode 5.0 and I couldn't get any of these answers to work. I tried every single answer on SO on multiple different questions about header imports w/ cocoapods.
FINALLY I found a solution that worked for me: I upgraded to Xcode 5.0 via the Mac AppStore (installed on top of the GM seed) and now the header imports are working as expected.
I also still had a beta version of Xcode 5 on my system and I deleted that as well. Maybe it was a combination of the two things, but hopefully this helps someone else.
You can use isset
function:
if(isset($_GET['id'])) {
// id index exists
}
You can create a handy function to return default value if index doesn't exist:
function Get($index, $defaultValue) {
return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}
// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');
You can also try to validate it at the same time:
function GetInt($index, $defaultValue) {
return isset($_GET[$index]) && ctype_digit($_GET[$index])
? (int)$_GET[$index]
: $defaultValue;
}
// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);
Lets say we have a variable called x, as below:
var x;
following statement is valid,
x = 10;
x = "a";
x = 0;
x = undefined;
x = null;
1. Number:
x = 10;
if(x){
//True
}
and for x = undefined
or x = 0
(be careful here)
if(x){
//False
}
2. String x = null
, x = undefined
or x = ""
if(x){
//False
}
3 Boolean x = false
and x = undefined
,
if(x){
//False
}
By keeping above in mind we can easily check, whether variable is empty, null, 0 or undefined in Angular js. Angular js doest provide separate API to check variable values emptiness.
ASPX code:
<asp:LinkButton ID="someID" runat="server" Text="clicky"></asp:LinkButton>
Code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
someID.Attributes.Add("onClick", "return false;");
}
}
What renders as HTML is:
<a onclick="return false;" id="someID" href="javascript:__doPostBack('someID','')">clicky</a>
In this case, what happens is the onclick functionality becomes your validator. If it is false, the "href" link is not executed; however, if it is true the href will get executed. This eliminates your post back.
To complete oscarbranson's answer: it's possible to automatically pick console or notebook versions of progress bar depending on where it's being run from:
from tqdm.autonotebook import tqdm
More info can be found here
This is not an ideal solution as you have to manage two ini files however, I managed to work around this on windows by copying the php ini file in mamp from the conf folder to your active php version in the bin folder.
[MAMP INSTALL]\conf\[ACTIVE PHP VERSION]\php.ini
copy to
[MAMP INSTALL]\bin\php\[ACTIVE PHP VERSION]
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
Your example would be:
int num1 = 1;
int num2 = 1;
num1 = num2 = 5;
WhatsApp is now providing a much simpler API https://wa.me/
This isn't introducing any new features, just a simpler way to execute things. There's no need to check for user agent while implementing this API as it will also work with native apps as well as the web interface of whatsapp (web.whatsapp.com) on desktop.
This can be used in multiple use cases
A Click to chat button : Use https://wa.me/whatsappphonenumber
to open a chat dialog with the specified whatsapp user. Please note that the whatsappphonenumber
should be a valid whatsapp number in international format without leading zeros, '+', '-' and spaces. e.g. 15551234567
<a href="https://wa.me/15551234567">Whatsapp Me</a>
A Share this on whatsapp button : Use https://wa.me/?text=urlencodedtext
to open a whatsapp contact selection dialog with a preset text. e.g.
<a href="https://wa.me/?text=I%20found%20a%20great%20website.%20Check%20out%20this%20link%20https%3A%2F%2Fwww.example.com%2F">Share on WhatsApp</a>
A Contact me button with prefilled text : A combination of the above two, Might be useful if you want to get a prefilled custom message from users landing on a particular page. Use format https://wa.me/whatsappphonenumber/?text=urlencodedtext
<a href="https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20services.%20How%20to%20get%20started%3F">I am interested</a>
For official documentation visit https://faq.whatsapp.com/en/general/26000030
From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection
:
library(devtools)
install_github("twitter/AnomalyDetection")
does the trick.
Have you set the appId property to your current application ID?
If you have strange errors with downloading background images use W3C Link checker: https://validator.w3.org/checklink
Here are modern mixins that I use (credits: PSA: don't use gradient generators):
.buttonAkc
{
.gradientBackground(@imageName: 'accept.png');
background-repeat: no-repeat !important;
background-position: center right, top left !important;
}
.buttonAkc:hover
{
.gradientBackgroundHover('accept.png');
}
.gradientBackground(@startColor: #fdfdfd, @endColor: #d9d9db, @imageName)
{
background-color: mix(@startColor, @endColor, 60%); // fallback
background-image: url("@{img-folder}/@{imageName}?v=@{version}"); // fallback
background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, -webkit-linear-gradient(top, @startColor 0%, @endColor 100%) no-repeat scroll left top; // Chrome 10-25, Safari 5.1-6
background: url("@{img-folder}/@{imageName}?v=@{version}") no-repeat scroll right center, linear-gradient(to bottom, @startColor 0%, @endColor 100%) no-repeat scroll left top;
}
.gradientBackgroundHover(@imageName)
{
.gradientBackground(#fdfdfd, #b5b6b9, @imageName);
}
Some things to think about when choosing between these mechanisms are:
You may need anything from simple backticks (``), system()
, and IO.popen
to full-blown Kernel.fork
/Kernel.exec
with IO.pipe
and IO.select
.
You may also want to throw timeouts into the mix if a sub-process takes too long to execute.
Unfortunately, it very much depends.
Try to remove multidex from default config and check the build error log. If that log is some relatable with INotification class. Use this in android{}
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
}
This helps me.
Have a look at Wikipedia:
Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A). These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.
For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan
Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log
,
" to the respective app.log created by you.
After this go to your index.js and include the following code in it.
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');
User Endless is right,
$.browser.chrome = (typeof window.chrome === "object");
code is best to detect Chrome browser using jQuery.
If you using IE and added GoogleFrame as plugin then
var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.
Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.
Dim cell As Range
Dim address As String
Set cell = Worksheets(1).Cells.Range("A1")
address = cell.address(External:=True)
address = Right(address, Len(address) - InStr(1, address, "]"))
As Kaboing mentioned, MAXDOP(n)
actually controls the number of CPU cores that are being used in the query processor.
On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER)
which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN)
reduce a query from 26 seconds to 1 second of execution time.
Books Online goes on to say that possible values for MAXDOP
are:
0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.
1 - Suppresses parallel plan generation. The operation will be executed serially.
2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.
I'm not sure what the best usage of MAXDOP
is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8)
due to I/O limitations, but I could be wrong.
Here are a few quick links I found about MAXDOP
:
To get the build in classes (like Array and Hash) to support as_json
and to_json
, you need to require 'json/add/core'
(see the readme for details)
As of RC6 you can do the following to change URL without change state and thereby keeping your route history
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
// If you dont import this angular will import the wrong "Location"
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit {
constructor( private location: Location )
{}
ngOnInit() {
this.location.replaceState("/some/newstate/");
}
}
If compiled with STL compatibility, QString
has a static method to convert a std::string
to a QString
:
std::string str = "abc";
QString qstr = QString::fromStdString(str);
Coming back to this one after a long time...
Given the demise of ConfigurationManager, for anyone still looking for an answer to this try (for example):
AppSettingsReader appsettingsreader = new AppSettingsReader();
string timeAsString = (string)(new AppSettingsReader().GetValue("Service.Instance.Trigger.Time", typeof(string)));
Requires System.Configuration of course.
(Editted the code to something that actually works and is simpler to read)
Some of the key differences are in the complexity requirements.
A map
requires O(log(N))
time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.
An unordered_map
requires an 'average' time of O(1)
for inserts and finds, but is allowed to have a worst-case time of O(N)
. This is because it's implemented using Hash Table data structure.
So, usually, unordered_map
will be faster, but depending on the keys and the hash function you store, can become much worse.
In my case, this error was due to special characters what I was considering double quotes as I copied the command from a web page.
For openSUSE 42.1 Leap Linux use this
sudo zypper install python3-devel
In my case with Eclipse IDE, I had the same problem and the solution was:
1- Install the latest available API (SDK Platform & Google APIs)
2- Create the project with the following settings:
If you want window handles for ALL of your application's Window
s for some reason, you can use the Application.Windows
property to get at all the Windows and then use WindowInteropHandler
to get at their handles as you have already demonstrated.
Another way is to use the object tag. This works on Chrome, IE, Firefox, Safari and Opera.
<object data="html/stuff_to_include.html">
Your browser doesn’t support the object tag.
</object>
more info at http://www.w3schools.com/tags/tag_object.asp
This is very possible. It just takes a little CSS trickery!
div.border {_x000D_
border: 1px solid #000;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
div.border:before {_x000D_
position: absolute;_x000D_
display: block;_x000D_
content: '';_x000D_
border: 1px solid red;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
-webkit-box-sizing: border-box;_x000D_
}
_x000D_
<div class="border">Hi I have two border colors<br />I am also Fluid</div>
_x000D_
Is that what you are looking for?
By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection
Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)
Simply add default 0
at the end of your ALTER TABLE <table> ADD COLUMN <column> <type>
statement
You need to change your code as below:-
<html>
<body>
<span id="span_Id">Click the button to display the content.</span>
<button onclick="displayDate()">Click Me</button>
<script>
function displayDate() {
var span_Text = document.getElementById("span_Id").innerText;
alert (span_Text);
}
</script>
</body>
</html>
After doing this you will get the tag value in alert.
(Another solution using pivot_longer
& pivot_wider
from latest Tidyr
update)
You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (https://tidyr.tidyverse.org/articles/pivot.html)
library(tidyverse)
C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)
Output here
ID mean
<fct> <dbl>
1 A 3.67
2 B 4.33
3 C 3.33
4 D 4.67
5 E 4.33
It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.
See the HttpSessionState.Timeout property; default value is 20 minutes.
You can access this propery in ASP.NET via HttpContext:
this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere
I have wrapped it in my date time helper class here
https://github.com/normandqq/Date-Time-Helper
using
$dateLastDay = Model_DTHpr::getLastDayOfTheMonth();
And it is done
Refresh gradle project on Eclipse solved this problem for me
Without repeating the same thing in previous answers,
I'm writing this answer for the people who are looking to starting a new project and don't know which is the best framework to startup your project.
If you are a beginner to this framework the best thing I prefer is Use spring boot(with STS /Spring Tool Suite). Because it helps a lot. Its do all configurations on its own. Additionally, use Hibernate with spring-boot as a database framework. With this combination, your application will be the best. I can guarantee that with my experiences.
Even this is one of the best frameworks for JEE(in present) this is gonna die in the near future. There are lightweight alternatives coming up. So keep updated with your experience don't stick to one particular framework. The best thing is being fluent in concepts, not in the frameworks.
I wanted "key" & "value" pair of a first dictionary item. I used the following code.
key, val = next(iter(my_dict.items()))
IPython comes with some automatic reloading magic:
%load_ext autoreload
%autoreload 2
It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload
. Some caveats apply, type %autoreload?
to see what can go wrong.
If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py
[1] and appending:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
Credit to @Kos via a comment below.
[1]
If you don't have the file ~/.ipython/profile_default/ipython_config.py
, you need to call ipython profile create
first. Or the file may be located at $IPYTHONDIR
.
<br>
is an HTML element. There isn't any ASCII code for it.
But, for line break sometimes 
is used as the text code.
Or <br>
You can check the text code here.
In my very specific case, I just wanted to execute a command in a remote host, inside a specific directory from a Jenkins slave machine:
ssh myuser@mydomain
cd /home/myuser/somedir
./commandThatMustBeRunInside_somedir
exit
But my machine couldn't perform the ssh (it couldn't allocate a pseudo-tty I suppose) and kept me giving the following error:
Pseudo-terminal will not be allocated because stdin is not a terminal
I could get around this issue passing "cd to dir + my command" as a parameter of the ssh command (to not have to allocate a Pseudo-terminal) and by passing the option -T to explicitly tell to the ssh command that I didn't need pseudo-terminal allocation.
ssh -T myuser@mydomain "cd /home/myuser/somedir; ./commandThatMustBeRunInside_somedir"
Just to add a different approach - you can simply cast your ref, something like:
let myInputElement: Element = this.refs["myInput"] as Element
Elliot Beach is correct. Thanks Elliot.
Here is the code from my gist.
sudo apt-get remove docker docker-engine docker.io
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
xenial \
stable"
sudo apt-get update
sudo apt-get install docker-ce
sudo docker run hello-world
When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.
As mentioned previously, a function needs to be passed to toThrow
as it is the function you're describing in your test: "I expect this function to throw x"
expect(() => parser.parse(raw))
.toThrow(new Error('Parsing is not possible'));
If using Jasmine-Matchers you can also use one of the following when they suit the situation;
// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
.toThrowAnyError();
or
// I just want to know that an error of
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
.toThrowErrorOfType(TypeError);
You misspelled permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In my case I didn't have an OracleService
(OracleServiceORCL) in Windows Services.msc
as described in Bharathi's answer.
I executed this command:
C:\> ORADIM -NEW -SID ORCL
and then the OracleService
called OracleServiceORCL just showed up and got started in Services.msc. Really nice.
Source: https://forums.oracle.com/forums/message.jspa?messageID=4044655#4044655
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse
would be necessary as well.
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
Try this:
var res = list.ToDictionary(x => x, x => x);
The first lambda lets you pick the key, the second one picks the value.
You can play with it and make values differ from the keys, like this:
var res = list.ToDictionary(x => x, x => string.Format("Val: {0}", x));
If your list contains duplicates, add Distinct()
like this:
var res = list.Distinct().ToDictionary(x => x, x => x);
EDIT To comment on the valid reason, I think the only reason that could be valid for conversions like this is that at some point the keys and the values in the resultant dictionary are going to diverge. For example, you would do an initial conversion, and then replace some of the values with something else. If the keys and the values are always going to be the same, HashSet<String>
would provide a much better fit for your situation:
var res = new HashSet<string>(list);
if (res.Contains("string1")) ...
Maybe a good starting point:
isChecked = driver.findElement((By.id("idOftheElement"))).getAttribute("name");
if(!isChecked.contains("chkOptions$1"))
{
driver.FindElement(By.Id("idOfTheElement")).Click();
}
After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want
You can use the ID
field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.
<select
ng-model="Choice.SelectedOption.ID"
ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
In addition to those comments that mention the IPet/PetBase implementation, there are also cases where providing an accessor helper class can be very valuable.
The IPet/PetBase style assumes that you have multiple implementations thus increasing the value of PetBase since it simplifies implementation. However, if you have the reverse or a blend of the two where you have multiple clients, providing a class help assist in the usage of the interface can reduce cost by making it easier to use an interface.
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
I have seen the error trying to run VC++ debug executable on a machine which did not have Visual C++ installed. Building a release version and using that fixed it.
^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$ # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.
Swift 3 solution based on Ramis' answer:
extension String {
func withReplacedCharacters(_ characters: String, by separator: String) -> String {
let characterSet = CharacterSet(charactersIn: characters)
return components(separatedBy: characterSet).joined(separator: separator)
}
}
Tried to come up with an appropriate function name according to Swift 3 naming convention.
You can change the height or width of the Before or After element like this:
.element:after {
display: block;
content: url('your-image.png');
height: 50px; //add any value you need for height or width
width: 50px;
}
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
I faced the same issue. I had missed the forms module import tag in the app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule,
FormsModule
],
At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:
IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END
Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.
If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.
IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012')
AND userName = 'test')
BEGIN
INSERT INTO Clock(clockDate, userName, breakOut)
VALUES(GetDate(), 'test', GetDate())
END
ELSE
BEGIN
UPDATE Clock
SET breakOut = GetDate()
WHERE clockDate = '08/10/2012' AND userName = 'test'
END
As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.
Just is case somebody asks (like I did), this is also possible when one uses subplot2grid. For example:
import matplotlib.pyplot as plt
plt.subplot2grid((3,2), (0,1), rowspan=3)
plt.plot([2,3,4,5])
plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
plt.show()
It will show this:
You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a
.
To remove go to the subdirectory and rm .git -rf
.
Public SUB test()
Dim mdate As Date
mdate = now()
MsgBox (Round(CDbl(mdate), 0))
End SUB
This is an example of forEach usage:
let arr = [];
this.myArray.forEach((value, index) => {
arr.push(value);
console.log(value);
console.log(index);
});
In this case, "myArray" is an array on my data.
You can also loop through an array using filter, but this one should be used if you want to get a new list with filtered elements of your array.
Something like this:
const newArray = this.myArray.filter((value, index) => {
console.log(value);
console.log(index);
if (value > 5) return true;
});
and the same can be written as:
const newArray = this.myArray.filter((value, index) => value > 5);
Both filter and forEach are javascript methods and will work just fine with VueJs. Also, it might be interesting taking a look at this:
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:
def addstudent():
print("Student Added.")
then called by writing addstudent()
.
I would recommend using a while
loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked)
, then put the if statements after the while. Or you can do a while
loop and continue
the loop if a valid option is not selected.
Additionally, a dictionary is defined in the following way:
my_dict = {key:definition,...}
You can install and use the pip-autoremove utility to remove a package plus unused dependencies.
# install pip-autoremove
pip install pip-autoremove
# remove "somepackage" plus its dependencies:
pip-autoremove somepackage -y
Basically "ANSI" refers to the legacy codepage on Windows. See also an article by Raymond Chen on this topic:
The source of this comes from the fact that the Windows code page 1252 was originally based on an ANSI draft, which became ISO Standard 8859-1.
The first 127 characters are identical to ASCII in most code pages, the upper characters vary, though.
However, ANSI does not automatically mean CP1252 or Latin 1.
All confusion notwithstanding you should simply avoid such issues nowadays and use Unicode.
The initial source cause can also be an out of memory.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
You could do this:
SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;
Reference:
If you're using expo just place an 1024 x 1024 png file in your project and add an icon property to your app.json i.e. "icon": "./src/assets/icon.png"
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script>
tags at the end of the document body so they don't block rendering of the page.
But there are some newer approaches that offer better performance, as described in this answer about the load time of the Google Analytics JavaScript file:
There are some great slides by Steve Souders (client-side performance expert) about:
- Different techniques to load external JavaScript files in parallel
- their effect on loading time and page rendering
- what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
One who has tried all other answers and had no luck the please check this check box, hope it'll help (did the trick for me xcode 6.0.1)
<div class="foo">Foo Bar</div>
and in your CSS file:
.foo {
background-image: url("images/foo.png");
}
We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.
// const objectScan = require('object-scan');
const tool = (() => {
const scanner = objectScan(['[*]'], {
abort: true,
rtn: 'bool',
filterFn: ({
value, parent, property, context
}) => {
if (value.id === context.id) {
context.fn({ value, parent, property });
return true;
}
return false;
}
});
return {
add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
mod: (data, id, prop, v = undefined) => scanner(data, {
id,
fn: ({ value }) => {
if (value !== undefined) {
value[prop] = v;
} else {
delete value[prop];
}
}
})
};
})();
// -------------------------------
const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };
const exec = (fn) => {
console.log('---------------');
console.log(fn.toString());
console.log(fn());
console.log(data);
};
exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));
// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.
I did it a different way, without using VBA, by using a table containing the query parameters.
E.g:
SELECT a_table.a_field
FROM QueryParameters, a_table
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min
AND QueryParameters.a_field_max
Where QueryParameters
is a table with two fields, a_field_min
and a_field_max
It can even be used with GROUP BY
, if you include the query parameter fields in the GROUP BY
clause, and the FIRST
operator on the parameter fields in the HAVING
clause.
Just Close()
all active/existing forms and the application should exit.
In case you are looking to include the font awesome library without having to do module imports and npm installs, put this in the head section of your React index.html page:
public/index.html (in head section)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
Then in your component (such as App.js) just use standard font awesome class convention. Just remember to use className instead of class:
<button className='btn'><i className='fa fa-home'></i></button>
Try adding this to your where
clause:
dateadd(day, -30, getdate())
I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader
In Linux you can do like this
pg_dump -U postgres -s postgres > exportFile.dmp
Maybe it can work in Windows too, if not try the same with pg_dump.exe
pg_dump.exe -U postgres -s postgres > exportFile.dmp
Your mistake is using the datetime
module instead of the date
module. You meant to do this:
from datetime import date
date = models.DateField(_("Date"), default=date.today)
If you only want to capture the current date the proper way to handle this is to use the auto_now_add
parameter:
date = models.DateField(_("Date"), auto_now_add=True)
However, the modelfield docs clearly state that auto_now_add
and auto_now
will always use the current date and are not a default value that you can override.
I use:
if exists (select *
from sys.tables
where name = 'tableName'
and schema_id = schema_id('dbo'))
begin
drop table dbo.tableName
end
I have just tested the following pipeline and it works
parallel firstBranch: {
stage ('Starting Test')
{
build job: 'test1', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}, secondBranch: {
stage ('Starting Test2')
{
build job: 'test2', parameters: [string(name: 'Environment', value: "$env.Environment")]
}
}
This Job named 'trigger-test' accepts one parameter named 'Environment'
Job 'test1' and 'test2' are simple jobs:
Example for 'test1'
On execution, I am able to see both stages running in the same time
The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email
Use console.log(JSON.stringify(result))
to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty
and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
I considered giving a comment under the answer by taggon to this very question, but well, i felt it owed more explanation for those interested in details.
Uncaught TypeError: Cannot read property 'value' of undefined is strictly a JavaScript error.
(Note that value can be anything, but for this question value is 'map')
It's critical to understand that point, just so you avoid endless debugging cycles.
This error is common especially if just starting out in JavaScript (and it's libraries/frameworks).
For React
, this has a lot to do with understanding the component lifecycle methods.
// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children
import React, { useEffect } from 'react'
// Main component
const ShowList = () => {
// Similar to componentDidMount and componentDidUpdate
useEffect(() => {// dispatch call to fetch items, populate the redux-store})
return <div><MyItems items={movies} /></div>
}
// other component
const MyItems = props =>
<ul>
{props.items.map((item, i) => <li key={i}>item</li>)}
</ul>
/**
The above code should work fine, except for one problem.
When compiling <ShowList/>,
React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
And since `items={movies}`, 'props.items' is 'undefined' at that point.
Thus the error message 'Cannot read property map of undefined'
*/
As a way to tackle this problem, @taggon gave a solution (see first anwser or link).
Solution: Set an initial/default value.
In our example, we can avoiditems
being 'undefined' by declaring adefault
value of an empty array.
Why? This allows React-DOM to render an empty list initially.
And when theuseEffect
orcomponentDid...
method is executed, the component is re-rendered with a populated list of items.
// Let's update our 'other' component
// destructure the `items` and initialize it as an array
const MyItems = ({items = []}) =>
<ul>
{items.map((item, i) => <li key={i}>item</li>)}
</ul>
I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.
For example, consider a generic Field
class that has an ID number, a type code and a field name. If I want to search a vector
of these Field
s by either ID number or name, I might construct a functor to do so:
class Field
{
public:
unsigned id_;
string name_;
unsigned type_;
class match : public std::unary_function<bool, Field>
{
public:
match(const string& name) : name_(name), has_name_(true) {};
match(unsigned id) : id_(id), has_id_(true) {};
bool operator()(const Field& rhs) const
{
bool ret = true;
if( ret && has_id_ ) ret = id_ == rhs.id_;
if( ret && has_name_ ) ret = name_ == rhs.name_;
return ret;
};
private:
unsigned id_;
bool has_id_;
string name_;
bool has_name_;
};
};
Then code that needs to search for these Field
s can use the match
scoped within the Field
class itself:
vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));
There are other options for you to benchmark:
1.) A window function will return the actual size directly (tested in MariaDB):
SELECT
`mytable`.*,
COUNT(*) OVER() AS `total_count`
FROM `mytable`
ORDER BY `mycol`
LIMIT 10, 20
2.) Thinking out of the box, most of the time users don't need to know the EXACT size of the table, an approximate is often good enough.
SELECT `TABLE_ROWS` AS `rows_approx`
FROM `INFORMATION_SCHEMA`.`TABLES`
WHERE `TABLE_SCHEMA` = DATABASE()
AND `TABLE_TYPE` = "BASE TABLE"
AND `TABLE_NAME` = ?
The most recent way of overcoming the same-origin policy that I've found is http://anyorigin.com/
The site's made so that you just give it any url and it generates javascript/jquery code for you that lets you get the html/data, regardless of it's origin. In other words, it makes any url or webpage a JSONP request.
I've found it pretty useful :)
Here's some example javascript code from anyorigin:
$.getJSON('http://anyorigin.com/get?url=google.com&callback=?', function(data){
$('#output').html(data.contents);
});
Loop invariant is a mathematical formula such as (x=y+1)
. In that example, x
and y
represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible to x
and y
values and see if they produce any bug. Lets say x
is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables.
After all, we just try to understand the behavior of the program.
Assuming you want to get columns 1 and 9 with that code snippet, it should be:
extractedData = data[:,[1,9]]
With VSTS the url is, When you copy git clone url from vsts you always get
https://orgname@dev.azure.com/org/project/_git/repo
Replace orgname@ with your alternate username that you would have created in VSTS -> profile -> Security.
final git url -
https://alternateusername@dev.azure.com/org/project/_git/repo
On Mac (on french keyboard its) cmd + shift + F
Thanks to codaddict for suggesting the -i
option.
The following command solves the problem on Snow Leopard
sed -i '' -e's/[ \t]*$//' "$1"
It looks like the best solution for you is actually a directive. This allows you to still have your controller, but define custom properties for it.
Use this if you need access to variables in the wrapping scope:
angular.module('myModule').directive('user', function ($filter) {
return {
link: function (scope, element, attrs) {
$scope.connection = $resource('api.com/user/' + attrs.userId);
}
};
});
<user user-id="{% id %}"></user>
Use this if you don't need access to variables in the wrapping scope:
angular.module('myModule').directive('user', function ($filter) {
return {
scope: {
userId: '@'
},
link: function (scope, element, attrs) {
$scope.connection = $resource('api.com/user/' + scope.userId);
}
};
});
<user user-id="{% id %}"></user>
I'm sure you'll get a ton of "don't do this" answers, and I must say, there is good reason. This isn't an ideal solution....
That being said, I've gone down this road (and similar ones) before, mostly because the job specified it as a hard requirement and I couldn't talk around it.
Here are a few things to consider with this:
How easy is it to link to Access from Excel using ADO / DAO? Is it quite limited in terms of functionality or can I get creative?
It's fairly straitforward. You're more limited than you would be doing things using other tools, since VBA and Excel forms is a bit more limiting than most full programming languages, but there isn't anything that will be a show stopper. It works - sometimes its a bit ugly, but it does work. In my last company, I often had to do this - and occasionally was pulling data from Access and Oracle via VBA in Excel.
Do I pay a performance penalty (vs.using forms in Access as the UI)?
My experience is that there is definitely a perf. penalty in doing this. I never cared (in my use case, things were small enough that it was reasonable), but going Excel<->Access is a lot slower than just working in Access directly. Part of it depends on what you want to do....
In my case, the thing that seemed to be the absolute slowest (and most painful) was trying to fill in Excel spreadsheets based on Access data. This wasn't fun, and was often very slow. If you have to go down this road, make sure to do everything with Excel hidden/invisible, or the redrawing will absolutely kill you.
Assuming that the database will always be updated using ADO / DAO commands from within Excel VBA, does that mean I can have multiple Excel users using that one single Access database and not run into any concurrency issues etc.?
You're pretty much using Excel as a client - the same way you would use a WinForms application or any other tool. The ADO/DAO clients for Access are pretty good, so you probably won't run into any concurrency issues.
That being said, Access does NOT scale well. This works great if you have 2 or 3 (or even 10) users. If you are going to have 100, you'll probably run into problems. Also, I tended to find that Access needed regular maintenance in order to not have corruption issues. Regular backups of the Access DB are a must. Compacting the access database on a regular basis will help prevent database corruption, in my experience.
Any other things I should be aware of?
You're doing this the hard way. Using Excel to hit Access is going to be a lot more work than just using Access directly.
I'd recommend looking into the Access VBA API - most of it is the same as Excel, so you'll have a small learning curve. The parts that are different just make this easier. You'll also have all of the advantages of Access reporting and Forms, which are much more data-oriented than the ones in Excel. The reporting can be great for things like this, and having the Macros and Reports will make life easier in the long run. If the user's going to be using forms to manage everything, doing the forms in Access will be very, very similar to doing them in Excel, and will look nearly identical, but will make everything faster and smoother.
You can simulate capturing in vanilla awk too, without extensions. Its not intuitive though:
step 1. use gensub to surround matches with some character that doesnt appear in your string. step 2. Use split against the character. step 3. Every other element in the splitted array is your capture group.
$ echo 'ab cb ad' | awk '{ split(gensub(/a./,SUBSEP"&"SUBSEP,"g",$0),cap,SUBSEP); print cap[2]"|" cap[4] ; }' ab|ad
You can use PATINDEX to find the first index of the pattern (string's) occurrence. Then use STUFF to stuff another string into the pattern(string) matched.
Loop through each row. Replace each illegal characters with what you want. In your case replace non numeric with blank. The inner loop is if you have more than one illegal character in a current cell that of the loop.
DECLARE @counter int
SET @counter = 0
WHILE(@counter < (SELECT MAX(ID_COLUMN) FROM Table))
BEGIN
WHILE 1 = 1
BEGIN
DECLARE @RetVal varchar(50)
SET @RetVal = (SELECT Column = STUFF(Column, PATINDEX('%[^0-9.]%', Column),1, '')
FROM Table
WHERE ID_COLUMN = @counter)
IF(@RetVal IS NOT NULL)
UPDATE Table SET
Column = @RetVal
WHERE ID_COLUMN = @counter
ELSE
break
END
SET @counter = @counter + 1
END
Caution: This is slow though! Having a varchar column may impact. So using LTRIM RTRIM may help a bit. Regardless, it is slow.
Credit goes to this StackOverFlow answer.
EDIT Credit also goes to @srutzky
Edit (by @Tmdean) Instead of doing one row at a time, this answer can be adapted to a more set-based solution. It still iterates the max of the number of non-numeric characters in a single row, so it's not ideal, but I think it should be acceptable in most situations.
WHILE 1 = 1 BEGIN
WITH q AS
(SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
FROM Table)
UPDATE Table
SET Column = STUFF(Column, q.n, 1, '')
FROM q
WHERE Table.ID_Column = q.ID_Column AND q.n != 0;
IF @@ROWCOUNT = 0 BREAK;
END;
You can also improve efficiency quite a lot if you maintain a bit column in the table that indicates whether the field has been scrubbed yet. (NULL represents "Unknown" in my example and should be the column default.)
DECLARE @done bit = 0;
WHILE @done = 0 BEGIN
WITH q AS
(SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
FROM Table
WHERE COALESCE(Scrubbed_Column, 0) = 0)
UPDATE Table
SET Column = STUFF(Column, q.n, 1, ''),
Scrubbed_Column = 0
FROM q
WHERE Table.ID_Column = q.ID_Column AND q.n != 0;
IF @@ROWCOUNT = 0 SET @done = 1;
-- if Scrubbed_Column is still NULL, then the PATINDEX
-- must have given 0
UPDATE table
SET Scrubbed_Column = CASE
WHEN Scrubbed_Column IS NULL THEN 1
ELSE NULLIF(Scrubbed_Column, 0)
END;
END;
If you don't want to change your schema, this is easy to adapt to store intermediate results in a table valued variable which gets applied to the actual table at the end.
There are multiple ways:
String.valueOf(number)
(my preference)"" + number
(I don't know how the compiler handles it, perhaps it is as efficient as the above)Integer.toString(number)
On my blog, the reason of this error is a plugin named Broken Link checker. This plugin has high resource usage from hosting, resulting in this error.
Check if a plugin on your installation is behaving similarly like this.
data.sort(function(a,b)
{
return a.val - b.val;
});
If you are working on windows, you can use pywin32
(old link: see update below).
I found an example here:
import win32com.client
wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
print usb.DeviceID
Update Apr 2020:
'pywin32' release versions from 218 and up can be found here at github. Current version 227.
Here is a simple one
this.$children[indexOfComponent].childsMethodName();
I think these are two really different cases. In the first case memory is allocated and initialized in compile-time. In the second - in runtime.
Fold All:
0
0
Unfold All:
To see all available shortcuts in the editor:
All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts
Laravel now supports this feature out-of-the-box! (I believe since 5.5 or earlier).
Add a __construct()
method to your Controller
as shown below:
public function __construct()
{
$this->middleware('auth');
}
After login, your users will then be redirected to the page they intended to visit initially.
You can also add Laravel's email verification feature as required by your application logic:
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
The documentation contains a very brief example:
It's also possible to choose which controller's methods the middleware applies to by using except
or only
options.
Example with except
:
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
Example with only
:
public function __construct()
{
$this->middleware('auth', ['only' => ['index', 'show']]);
}
More information about except
and only
middleware options:
I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:
This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.
Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".
So in your case the JSTL code should look like the following, note the capital 'P':
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
ES6 of the day here;
const json_getAllKeys = data => (
data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
)
And yes it can be written in very long one line;
const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])
EDIT: Returns all first order keys if the input is of type array of objects
Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog
instead.
new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
According to @Abhishek Singh's you need to understand the problem:
What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure
and you can not refer to it anymore (imagine what element's ID has changed).
Follow the code:
class TogglingPage {
@FindBy(...)
private WebElement btnTurnOff;
@FindBy(...)
private WebElement btnTurnOn;
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click(); // when clicked, button should swap into btnTurnOn
this.btnTurnOn.isDisplayed();
this.btnTurnOn.click(); // when clicked, button should swap into btnTurnOff
this.btnTurnOff.isDisplayed(); // throws an exception
return new TogglingPage();
}
}
Now, let us wonder why?
btnTurnOff
was found by a driver - okbtnTurnOff
was replaced by btnTurnOn
- okbtnTurnOn
was found by a driver. - okbtnTurnOn
was replaced by btnTurnOff
- okthis.btnTurnOff.isDisplayed();
on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button. Possible fix:
TogglingPage turnOff() {
this.btnTurnOff.isDisplayed();
this.btnTurnOff.click();
TogglingPage newPage = new TogglingPage();
newPage.btnTurnOn.isDisplayed();
newPage.btnTurnOn.click();
TogglingPage newerPage = new TogglingPage();
newerPage.btnTurnOff.isDisplayed(); // ok
return newerPage;
}
To serialize an object, do:
using (StreamWriter myWriter = new StreamWriter(path, false))
{
XmlSerializer mySerializer = new XmlSerializer(typeof(your_object_type));
mySerializer.Serialize(myWriter, objectToSerialize);
}
Also remember that for XmlSerializer to work, you need a parameterless constructor.
Spring boot doc 'was' wrong (they have since fixed it) :
To switch it off you can set error.whitelabel.enabled=false
should be
To switch it off you can set server.error.whitelabel.enabled=false
More Swift-like version:
override func shouldAutorotate() -> Bool {
switch UIDevice.currentDevice().orientation {
case .Portrait, .PortraitUpsideDown, .Unknown:
return true
default:
return false
}
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue) | Int(UIInterfaceOrientationMask.PortraitUpsideDown.rawValue)
}
UINavigationController
from Vivek Parihar
extension UINavigationController {
public override func shouldAutorotate() -> Bool {
return visibleViewController.shouldAutorotate()
}
}
Actually the Read
method iterating over records in a result set. In your case - over table rows. So you still can use it.
I've a way and work like this:
<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>
Why not simply try this:
var promise = $http.get(url, {
params: query
}).then(function(response) {
console.log('Content-Range: ' + response.headers('Content-Range'));
return response.data;
});
Especially if you want to return the promise
so it could be a part of a promises chain.
Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.
Adjusting the Stack Sizes (Xss and Xmso) options...
I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....
str_replace($sub_str, $insert_str.$sub_str, $org_str);
It's rather safe to add @SafeVarargs
annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.
If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>
) input instead of varargs (Type1<Type2>...
).
As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.
It is because you haven't qualified Cells(1, 1)
with a worksheet object, and the same holds true for Cells(10, 2)
. For the code to work, it should look something like this:
Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
Alternately:
With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range
also, like so:
ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
or
With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
For Postgresql you can use PERFORM. PERFORM is only valid within PL/PgSQL procedure language.
DO $$ BEGIN
PERFORM "saveUser"(3, 'asd','asd','asd','asd','asd');
END $$;
The suggestion from the postgres team:
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
There are mainly two ways to generate new component in Angular,
using ng g c <component_name>
, another way is that using ng generate component <component_name>
. using one of these commands new component can be generated.
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
You can also unconditionally add the delimiter string, and after the loop remove the extra delimiter at the end. Then an "if list is empty then return this string" at the beginning will allow you to avoid the check at the end (as you cannot remove characters from an empty list)
So the question really is:
"Given a loop and an if, what do you think is the clearest way to have these together?"
Technically speaking, the C standard only guarantees that sizeof(char) == 1, and the rest is up to the implementation. But on modern x86 architectures (e.g. Intel/AMD chips) it's fairly predictable.
You've probably heard processors described as being 16-bit, 32-bit, 64-bit, etc. This usually means that the processor uses N-bits for integers. Since pointers store memory addresses, and memory addresses are integers, this effectively tells you how many bits are going to be used for pointers. sizeof is usually measured in bytes, so code compiled for 32-bit processors will report the size of pointers to be 4 (32 bits / 8 bits per byte), and code for 64-bit processors will report the size of pointers to be 8 (64 bits / 8 bits per byte). This is where the limitation of 4GB of RAM for 32-bit processors comes from -- if each memory address corresponds to a byte, to address more memory you need integers larger than 32-bits.
From man githooks
:
pre-commit
This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes no parameter, and is invoked before obtaining the proposed commit log message and making a commit. Exiting with non-zero status from this script causes the git commit to abort.
It would be more useful to have a full function for real-world usage of truncating a decimal in C#. This could be converted to a Decimal extension method pretty easy if you wanted:
public decimal TruncateDecimal(decimal value, int precision)
{
decimal step = (decimal)Math.Pow(10, precision);
decimal tmp = Math.Truncate(step * value);
return tmp / step;
}
If you need VB.NET try this:
Function TruncateDecimal(value As Decimal, precision As Integer) As Decimal
Dim stepper As Decimal = Math.Pow(10, precision)
Dim tmp As Decimal = Math.Truncate(stepper * value)
Return tmp / stepper
End Function
Then use it like so:
decimal result = TruncateDecimal(0.275, 2);
or
Dim result As Decimal = TruncateDecimal(0.275, 2)
I've used these in the past:
In this particular case, where you need to replace a specific string across stored procedures, the first link is probably more relevant.
A little off-topic, the Quick Find add-in is also useful for searching object names with SQL Server Management Studio. There's a modified version available with some improvements, and another newer version also available on Codeplex with some other useful add-ins as well.
You can simply iterate it as in an array:
for(var i in txt){
console.log(txt[i]);
}
You can explicitly have a join like this:
$qb->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId');
But you need to use the namespace of the class Join from doctrine:
use Doctrine\ORM\Query\Expr\Join;
Or if you prefere like that:
$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, 'c.id = p.customerId');
Otherwise, Join class won't be detected and your script will crash...
Here the constructor of the innerJoin method:
public function innerJoin($join, $alias, $conditionType = null, $condition = null);
You can find other possibilities (not just join "ON", but also "WITH", etc...) here: http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html#the-expr-class
EDIT
Think it should be:
$qb->select('c')
->innerJoin('c.phones', 'p', Join::ON, 'c.id = p.customerId')
->where('c.username = :username')
->andWhere('p.phone = :phone');
$qb->setParameters(array(
'username' => $username,
'phone' => $phone->getPhone(),
));
Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.
Open Graph data:
<meta property="og:title" content="Title of your website | website.com"/>
<meta property="og:type" content="Most popular business directory of Bangladesh"/>
<meta property="og:url" content="http://www.website.com/"/>
<meta property="og:image" content="http://www.moumaachi.com/images/dhaka-city.jpg"/>
<meta property="og:site_name" content="@website"/>
<meta property="fb:admins" content="Author"/>
<meta property="og:description" content="website.com is your online business directory of Country"/>
Use strtotime() function:
$time = strtotime("-1 year", time());
$date = date("Y-m-d", $time);
The name of the public class within a file has to be the same as the name of that file.
So if your file declares class WeatherArray, it needs to be named WeatherArray.java
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
Use the strconv
package's Itoa
function.
For example:
package main
import (
"strconv"
"fmt"
)
func main() {
t := strconv.Itoa(123)
fmt.Println(t)
}
You can concat strings simply by +
'ing them, or by using the Join
function of the strings
package.
#include <typeinfo>
...
string s = typeid(YourClass).name()
Html.CheckBoxFor
expects a Func<TModel, bool>
as the first parameter. Therefore your lambda must return a bool
, you are currently returning an instance of List<Checkboxes>
:
model => model.EmploymentType
You need to iterate over the List<Checkboxes>
to output each checkbox:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked,
new { id = string.Format("employmentType_{0}", i) })
}
I solve the problem ...as follows
<bindings>
<netTcpBinding>
<binding name="ECMSBindingConfig" closeTimeout="00:10:00" openTimeout="00:10:00"
sendTimeout="00:10:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647"
maxReceivedMessageSize="2147483647" portSharingEnabled="true">
<readerQuotas maxArrayLength="2147483647" maxNameTableCharCount="2147483647"
maxStringContentLength="2147483647" maxDepth="2147483647"
maxBytesPerRead="2147483647" />
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ECMSServiceBehavior">
<dataContractSerializer ignoreExtensionDataObject="true" maxItemsInObjectGraph="2147483647" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceTimeouts transactionTimeout="00:10:00" />
<serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="100"
maxConcurrentInstances="100" />
</behavior>
</serviceBehaviors>
</behaviors>
Main differences are:
You can do it easily by using JUnit or TestNG framework. Do the assertion as below:
String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);
OR,
assertTrue(driver.getTitle().contains("Title of Page"));
You can use perl one-liners much like you do with sed, with the advantage of full perl regular expression support (which is much more powerful than what you get with sed). There is also very little variation across *nix platforms - perl is generally perl. So you can stop worrying about how to make your particular system's version of sed do what you want.
In this case, you can do
perl -pe 's/(regex)/\n$1/'
-pe
puts perl into a "execute and print" loop, much like sed's normal mode of operation.
'
quotes everything else so the shell won't interfere
()
surrounding the regex is a grouping operator. $1
on the right side of the substitution prints out whatever was matched inside these parens.
Finally, \n
is a newline.
Regardless of whether you are using parentheses as a grouping operator, you have to escape any parentheses you are trying to match. So a regex to match the pattern you list above would be something like
\(\d\d\d\)\d\d\d-\d\d\d\d
\(
or \)
matches a literal paren, and \d
matches a digit.
Better:
\(\d{3}\)\d{3}-\d{4}
I imagine you can figure out what the numbers in braces are doing.
Additionally, you can use delimiters other than / for your regex. So if you need to match / you won't need to escape it. Either of the below is equivalent to the regex at the beginning of my answer. In theory you can substitute any character for the standard /'s.
perl -pe 's#(regex)#\n$1#'
perl -pe 's{(regex)}{\n$1}'
A couple final thoughts.
using -ne
instead of -pe
acts similarly, but doesn't automatically print at the end. It can be handy if you want to print on your own. E.g., here's a grep-alike (m/foobar/
is a regex match):
perl -ne 'if (m/foobar/) {print}'
If you are finding dealing with newlines troublesome, and you want it to be magically handled for you, add -l
. Not useful for the OP, who was working with newlines, though.
Bonus tip - if you have the pcre package installed, it comes with pcregrep
, which uses full perl-compatible regexes.
Take a look also to the do { ... }
command since gnuplot 4.6 as it is very powerful:
do for [t=0:50] {
outfile = sprintf('animation/bessel%03.0f.png',t)
set output outfile
splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}
This is a solution. Later you can split by ":" and take the values of the array
/**
* Converts milliseconds to human readeable language separated by ":"
* Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
*/
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = '0' + Math.floor( (t - d * cd) / ch),
m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
return [d, h.substr(-2), m.substr(-2)].join(':');
}
//Example
var delay = 190980000;
var fullTime = dhm(delay);
console.log(fullTime);
Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam()
with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value:
//function to remove query params from a URL
function removeURLParameter(url, parameter) {
//better to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "");
return url;
} else {
return url;
}
}
//function to add/update query params
function insertParam(key, value) {
if (history.pushState) {
// var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1';
var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search;
var hash = window.location.hash
//remove any param for the same key
var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key);
//figure out if we need to add the param with a ? or a &
var queryStart;
if(currentUrlWithOutHash.indexOf('?') !== -1){
queryStart = '&';
} else {
queryStart = '?';
}
var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash
window.history.pushState({path:newurl},'',newurl);
}
}
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
An example might have been useful, but if I understood you correctly, this would work:
echo "Hello: world" | cut -f1 -d":"
This will convert Hello: world
into Hello
.
gstreamer can handle webcam input. If I remeber well, there are python bindings for it!
Thanks to everyone, each of your posts helped me a lot. rbierman code was pretty straight for my question, I have modified a bit and created a function to plot vectors from given arrays. I'd love to see any suggestions to improve it further.
import numpy as np
import matplotlib.pyplot as plt
def plotv(M):
rows,cols = M.T.shape
print(rows,cols)
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
fig = plt.figure()
fig.suptitle('Vectors', fontsize=10, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('Vector operations')
ax.set_xlabel('x')
ax.set_ylabel('y')
for i,l in enumerate(range(0,cols)):
# print(i)
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.2,head_length=0.1,zorder=3)
ax.text(M[i,0],M[i,1], str(M[i]), style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':0.5})
plt.plot(0,0,'ok') #<-- plot a black point at the origin
# plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
r = np.random.randint(4,size=[2,2])
print(r[0,:])
print(r[1,:])
r12 = np.add(r[0,:],r[1,:])
print(r12)
plotv(np.vstack((r,r12)))
Use intptr_t
and uintptr_t
.
To ensure it is defined in a portable way, you can use code like this:
#if defined(__BORLANDC__)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
typedef unsigned char uint8_t;
typedef __int64 int64_t;
#else
#include <stdint.h>
#endif
Just place that in some .h file and include wherever you need it.
Alternatively, you can download Microsoft’s version of the stdint.h
file from here or use a portable one from here.
Make sure you don't have any firewalls blocking SMTP. The first time I tried to send an email, it was blocked both by Windows Firewall and McAfee - took forever to find them both.
If you would like a ggplot2
solution, you can do this if you can shape your data to this format (see example below)
# dummy data
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45),
variable=rep(paste0("category", 1:9), each=5))
# plot
ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))
Have a look at insertAdjacentHTML
var element = document.getElementById("one");
var newElement = '<div id="two">two</div>'
element.insertAdjacentHTML( 'afterend', newElement )
// new DOM structure: <div id="one">one</div><div id="two">two</div>
position is the position relative to the element you are inserting adjacent to:
'beforebegin' Before the element itself
'afterbegin' Just inside the element, before its first child
'beforeend' Just inside the element, after its last child
'afterend' After the element itself
From a Microsoft's script:
DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'
IF (EXISTS (SELECT name
FROM master.dbo.sysdatabases
WHERE ('[' + name + ']' = @dbname
OR name = @dbname)))
-- code mine :)
PRINT 'db exists'
As long as checker
is not null
, you may use !checker
as posted. This is possible since Java 5, because this Boolean
variable will be autoboxed to the primivite boolean
value.
You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).
ContextCompat.getColor(context, R.color.my_color)
As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.
You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:
compile 'com.android.support:support-v4:23.0.1'
Found this works in Safari. SVG only colors in with background-color where an element's bounding box covers. So, give it a border (stroke) with a zero pixel boundary. It fills in the whole thing for you with your background-color.
<svg style='stroke-width: 0px; background-color: blue;'> </svg>
I probably tried all the solutions mentioned above but all in vain. To summarize, I did:
Download HAXM directly from the website https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager and install it.
Uninstall and reinstall Android Studio.
Copy the HAXM from my another system where HAXM was working fine, from the location C:\Users\UserName\AppData\Local\Android\Sdk\extras\intel
Nothing worked for me. What worked for me: I noticed the issue "unable to run mksdcard sdk tool" when I try to download SDK platform.So after some research, I found some SDK tools such as mksdcard.exe require Microsoft Visual C++ runtime 2015-2019. So based on my system type,(for me it was x64) I downloaded the latest Microsoft Visual C++ Redistributable for Visual Studio 2019 from the link https://visualstudio.microsoft.com/downloads/. Detailed answer given here: Android Studio install failed - unable to run mksdcard sdk tool in Windows
After downloading and installing Visual C++ ,the error "unable to run mksdcard sdk tool" was fixed, also when I try to install HAXM after this, it was install successfully. Everything was fine. I was also able to create AVD now(which was also a problem when HAXM was not install).
I wanted to add an answer if the checkboxes are being generated in a loop. For example if your structure is like this (Assuming you are using server side constructs on your View
, like a foreach
loop):
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
<li id="checkboxlist" class="list-group-item card">
<div class="checkbox checkbox-inline">
<label><input type="checkbox" id="checkbox1">Checkbox 1</label>
<label><input type="checkbox" id="checkbox2">Checkbox 2</label>
</div>
</li>
Corresponding Jquery
:
$(".list-group-item").each(function (i, li) {
var currentli = $(li);
$(currentli).find("#checkbox1").on('change', function () {
$(currentli).find("#checkbox2").not(this).prop('checked',false);
});
$(currentli).find("#checkbox2").on('change', function () {
$(currentli).find("#checkbox1").not(this).prop('checked', false);
});
});
Working DEMO: https://jsfiddle.net/gr67qk20/
Another way to create an array with String apart from
String[] strings = { "abc", "def", "hij", "xyz" };
is to use split. I find this more readable if there are lots of Strings.
String[] strings = "abc,def,hij,xyz".split(",");
or the following is good if you are parsing lines of strings from another source.
String[] strings = ("abc\n" +
"def\n" +
"hij\n" +
"xyz").split("\n");