You can change the eclipse tomcat server configuration. Open the server view, double click on you server to open server configuration. Then click to activate "Publish module contents to separate XML files". Finally, restart your server, the message must disappear.
if(window.location.href.indexOf("?added-to-cart=555") >= 0)
It's window.location.href
, not window.location
.
This is a little hacky I guess, but it results in the correct validation attributes etc being applied
@Html.Raw(Html.TextBoxFor(m => m.File).ToHtmlString().Replace("type=\"text\"", "type=\"file\""))
For Blocks lover you can use ALActionBlocks to add action of gestures in block
__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];
Ensure that you've changed the link to the git repository to the HTTPS
option after you've selected "Native" in IntelliJ settings if SSH
doesn't work.
The freezing / deadlock can also be caused by this bug on GTK3 + Xorg
https://bugs.eclipse.org/bugs/show_bug.cgi?id=568859
Can be workarounded by using Wayland session, although in my case Eclipse fails to detect reasonable font for some reason and looks like this:
Related:
https://www.reddit.com/r/swaywm/comments/bkzeo7/font_rendering_really_bad_and_rough_in_gtk3/
https://www.reddit.com/r/swaywm/comments/kmd3d1/webkit_gtk_font_rendering_on_wayland/
To list all local groups which have users assigned to them, use this command:
cut -d: -f1 /etc/group | sort
For more info- > Unix groups, Cut command, sort command
yes you can . you need to refer both JS file
to the .aspx
page
<script language="javascript" type="text/javascript" src="JScript1.js">
</script>
<script language="javascript" type="text/javascript" src="JScript2.js">
</script>
JScript1.js
function ani1() {
alert("1");
ani2();
}
JScript2.js
function ani2() {
alert("2");
}
Since others have covered the differences, I'll hit the uses.
TIFF is usually used by scanners. It makes huge files and is not really used in applications.
BMP is uncompressed and also makes huge files. It is also not really used in applications.
GIF used to be all over the web but has fallen out of favor since it only supports a limited number of colors and is patented.
JPG/JPEG is mainly used for anything that is photo quality, though not for text. The lossy compression used tends to mar sharp lines.
PNG isn't as small as JPEG but is lossless so it's good for images with sharp lines. It's in common use on the web now.
Personally, I usually use PNG everywhere I can. It's a good compromise between JPG and GIF.
I had the same problem, which went away after I listed my library last: gcc prog.c -lm
I was facing the same issue , there could be two reasons for this-
src
base folder might not been declared, to resolve this go to tsconfig.json
and add the baseUrl
as "src
"{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "src",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"module": "esnext",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true
}
}
npm install
Many answers regarding Maven are right but you don't have to configure the plugin directly.
Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.
<project>
[...]
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
[...]
</project>
In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.
public class DrawingCanvas extends View {
private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;
public DrawingCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);
mPath = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(mPath, mPaint);
super.onDraw(canvas);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isUserInteractionEnabled) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mPath.moveTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
mPath.lineTo(event.getX(), event.getY());
invalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
}
return true;
}
public void moveCursorTo(float x, float y) {
mPath.moveTo(x, y);
}
public void makeLine(float toX, float toY) {
mPath.lineTo(toX, toY);
}
public void setUserInteractionEnabled(boolean userInteractionEnabled) {
isUserInteractionEnabled = userInteractionEnabled;
}
}
And then use it like
drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction
To Draw programatically
drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)
Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("your.package.to.scan");
return marshaller;
}
My fellows,
In January 2019 I used a code made before:
<script type="text/javascript">
function imprimir() {
var divToPrint=document.getElementById("ConsutaBPM");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
</script>
To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...
The table mas be defined with BORDER and CELLPADDING:
<table border='1' cellpadding='1' id='Tablbpm1' >
It worked fine!!!
I have just had all the script variations tested by Pui Cdm, included answers above and many others using php, htaccess, server configuration, and Javascript, the results are that the script
<script type="text/javascript">
function showProtocall() {
if (window.location.protocol != "https") {
window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
window.location.reload();
}
}
showProtocall();
</script>
provided by vivek-srivastava works best and you can add further security in java script.
Use .lower()
- For example:
s = "Kilometer"
print(s.lower())
The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()
If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine.
If you want to convert larger numbers then the following will do:
char *string = "24";
int value;
int assigned = sscanf(string, "%d", &value);
** don't forget to check the status (which should be 1 if it worked in the above case).
Paul.
The crux of the solution is setting
CURLOPT_RETURNTRANSFER => true
then
$response = curl_exec($ch);
CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.
I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:
By using (
,)
, you are capturing the group, if you simply remove them you will not have this problem.
>>> str1 = "a b c d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']
However there is no need for regex, str.split
without any delimiter specified will split this by whitespace for you. This would be the best way in this case.
>>> str1.split()
['a', 'b', 'c', 'd']
If you really wanted regex you can use this ('\s'
represents whitespace and it's clearer):
>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']
or you can find all non-whitespace characters
>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']
Direct Mail is an OS X desktop app that can show you previews of what your email will look like in a variety of email clients:
http://directmailmac.com/mac-email-design/
Full Disclosure: I work for the developers of Direct Mail
As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: http://code.activestate.com/recipes/576693/ ).
I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm not sure (and I don't have easy access to test).
Old pythons simplejson implementations dont handle the OrderedDict objects nicely .. and convert them to regular dicts before outputting them.. but you can overcome this by doing the following:
class OrderedJsonEncoder( simplejson.JSONEncoder ):
def encode(self,o):
if isinstance(o,OrderedDict.OrderedDict):
return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
else:
return simplejson.JSONEncoder.encode(self, o)
now using this we get:
>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}
Which is pretty much as desired.
Another alternative would be to specialise the encoder to directly use your row class, and then you'd not need any intermediate dict or UnorderedDict.
An alternative solution is to use marker, a tool I've created recently that allows you to "bookmark" command templates and easily place cursor at command place-holders:
I found that most of time, I'm using shell functions so I don't have to write frequently used commands again and again in the command-line. The issue of using functions for this use case, is adding new terms to my command vocabulary and having to remember what functions parameters refer to in the real-command. Marker goal is to eliminate that mental burden.
It's best to use miske's answer.
If you really want to use natecarlson's repository, the instructions just below can do any of the following:
apt-get update
gives a 404
error after add-apt-repository
apt-get update
gives a NO_PUBKEY
error after manually adding it to /etc/apt/sources.list
Open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!
If you installed natecarlson's repository (either using add-apt-repository
or manually added to /etc/apt/sources.list
) and you don't want it anymore, open a terminal and run the following:
sudo -i
Enter your password if necessary, then paste the following into the terminal:
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!
The following command will work for you, if you want to change default path. Just type this in bin directory of mongodb.
mongod --dbpath=yourdirectory\data\db
In case you want to move existing data too, then just copy all the folders from existing data\db directory to new directory before you execute the command.
And also stop existing mongodb services which are running.
Answers so far helped me come up with mine. I'm wary of UTC vs local time; ticks should always be UTC IMO.
public class Time
{
public static void Timestamps()
{
OutputTimestamp();
Thread.Sleep(1000);
OutputTimestamp();
}
private static void OutputTimestamp()
{
var timestamp = DateTime.UtcNow.Ticks;
var localTicks = DateTime.Now.Ticks;
var localTime = new DateTime(timestamp, DateTimeKind.Utc).ToLocalTime();
Console.Out.WriteLine("Timestamp = {0}. Local ticks = {1}. Local time = {2}.", timestamp, localTicks, localTime);
}
}
Output:
Timestamp = 636988286338754530. Local ticks = 636988034338754530. Local time = 2019-07-15 4:03:53 PM.
Timestamp = 636988286348878736. Local ticks = 636988034348878736. Local time = 2019-07-15 4:03:54 PM.
First initialize Property values
MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());
DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);
context.registerBeanDefinition("beanName", connectionFactory);
Add to the list of beans
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
Install these 2 packages
<packages>
<package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
<package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>
Helper function
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelToCsv
{
public class ExcelFileHelper
{
public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
{
using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
IExcelDataReader reader = null;
if (excelFilePath.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (excelFilePath.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
if (reader == null)
return false;
var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
{
UseHeaderRow = false
}
});
var csvContent = string.Empty;
int row_no = 0;
while (row_no < ds.Tables[0].Rows.Count)
{
var arr = new List<string>();
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
}
row_no++;
csvContent += string.Join(",", arr) + "\n";
}
StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
csv.Write(csvContent);
csv.Close();
return true;
}
}
}
}
Usage :
var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);
Simple answer: You can stop a thread INTERNALLY in one of two common ways:
You can also stop threads EXTERNALLY:
system.exit
(this kills your entire process)interrupt()
method *kill()
or stop()
)*: The expectation is that this is supposed to stop a thread. However, what the thread actually does when this happens is entirely up to what the developer wrote when they created the thread implementation.
A common pattern you see with run method implementations is a while(boolean){}
, where the boolean is typically something named isRunning
, it's a member variable of its thread class, it's volatile, and typically accessible by other threads by a setter method of sorts, e.g. kill() { isRunnable=false; }
. These subroutines are nice because they allow the thread to release any resources it holds before terminating.
For me the solution was besides using "Ntlm" as credential type:
XxxSoapClient xxxClient = new XxxSoapClient();
ApplyCredentials(userName, password, xxxClient.ClientCredentials);
private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
{
clientCredentials.UserName.UserName = userName;
clientCredentials.UserName.Password = password;
clientCredentials.Windows.ClientCredential.UserName = userName;
clientCredentials.Windows.ClientCredential.Password = password;
clientCredentials.Windows.AllowNtlm = true;
clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
}
Try the following:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteRule \.(gif|jpg)$ - [F]
Returns 403, if you access images directly, but allows them to be displayed on site.
Note: It is possible that when you open some page with image and then copy that image's path into the address bar you can see that image, it is only because of the browser's cache, in fact that image has not been loaded from the server (from Davo, full comment below).
Maybe loadash needs to be installed. Usually these things are handled by the package manager. On your command line:
npm install lodash
or maybe it needs to be globally installed
npm install -g lodash
As of Python 3.5, you can merge two dicts with:
merged = {**dictA, **dictB}
(https://www.python.org/dev/peps/pep-0448/)
So:
jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)
etc.
With Bootstrap you can use an anchor like a button.
<a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>
And use target="_blank"
to open the link in a new tab.
You can use the arithmetic operators to do relative time.
Time.now - 2.days
Will give you 2 days ago.
Best practice: one form per product is definitely the way to go.
Benefits:
In your specific situation
If you only ever intend to have one form element, in this case a submit
button, one form for all should work just fine.
My recommendation Do one form per product, and change your markup to something like:
<form method="post" action="">
<input type="hidden" name="product_id" value="123">
<button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>
This will give you a much cleaner and usable POST
. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).
Note: There's no technical benefit to using
<button>
vs.<input>
, but as a programmer I find it cooler to work withaction=='add_to_cart'
thanaction=='Add to Cart'
. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.
The equivalent of LIMIT
is SET ROWCOUNT
, but if you want generic pagination it's better to write a query like this:
;WITH Results_CTE AS
(
SELECT
Col1, Col2, ...,
ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
FROM Table
WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).
Note: the @Offset
parameter should use one-based indexing for this rather than the normal zero-based indexing.
In your activity_main.xml
, you can adjust from there
in the line:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
.......
android:theme="@style/Theme.Design.Light.NoActionBar"
.......
">
Sometimes when you can see things like this Click here, You can select from here the "noActionBar" theme.
Hope me helped you.
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
Not to belabor the point, but if you are working in a Dockerfile
, you would solve this particular issue with Composer by installing the unzip
utility. Below is an example using the official PHP image to install unzip
and the zip
PHP extension for good measure.
FROM php:7.4-apache
# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer
# Install unzip utility and libs needed by zip PHP extension
RUN apt-get update && apt-get install -y \
zlib1g-dev \
libzip-dev \
unzip
RUN docker-php-ext-install zip
This is a helpful GitHub issue where the above is lovingly lifted from.
You just have to refer your original list to be the one that the Collectors.toList()
returns.
Here's a demo:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Reference {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(list);
// Just collect even numbers and start referring the new list as the original one.
list = list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(list);
}
}
And here's how you can add the newly created elements to your original list in just one line.
List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList())
);
That's what this Functional Programming Paradigm provides.
You can probably use
new Date().setUTCHours(0,0,0,0)
if you need the value only once.
I had a similar problem where the SelectedItem-binding did not update when I selected something in the combobox. My problem was that I had to set UpdateSourceTrigger=PropertyChanged for the binding.
<ComboBox ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedItem, UpdateSourceTrigger=PropertyChanged}" />
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.
Specifically:
...snip...
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
...snip...
http://www.cplusplus.com/reference/clibrary/cstring/strcat.html
There's an example here as well.
To further answer what DRUA referred to in his/her answer...
I develop my databases in Access 2007. My users are using access 2007 runtime. They have read permissions to a database_Front (front end) folder, and read/write permissions to the database_Back folder.
In rolling out a new database, the user did not follow the full instructions of copying the front end to their computer, and instead created a shortcut. Running the Front-end through the shortcut will create a condition where the query is not updateable because of the file write restrictions.
Copying the front end to their documents folder solves the problem.
Yes, it complicates things when the users have to get an updated version of the front-end, but at least the query works without having to resort to temp tables and such.
In my case I have use actionlink
button in MVC and I have facing this issue, I have tried many solutions above and other, but still facing that issue, then I realize my error in code.
I have called modal in javascript by using
$('#ModalId').modal('show');
Before the error I using this button
<a href="" onclick="return Edit();" class="btn btn-primary">Edit</a>
I have no value for href property in this button so I facing the issue.
Then I edit this button code like this
<a href="#" onclick="return Edit();" class="btn btn-primary">Edit</a>
then issue get solved just an error because of no # in first one.
see if this will helpful to you.
Try downloading jar from here
You can find, it holds the class you need.
EDIT
Seems like the website has changed its structure. You need to choose which jar file you need for your project.
For slf4j-api jar
file for latest version as of now, please visit this link
For slf4j-simple jar
file for latest version as of now, please visit this link
Here's the complete regexp to parse a URL.
(?:http://(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.
)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)
){3}))(?::(?:\d+))?)(?:/(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F
\d]{2}))|[;:@&=])*)(?:/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))*)(?:\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-fA-F\d]{
2}))|[;:@&=])*))?)?)|(?:ftp://(?:(?:(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?
:%[a-fA-F\d]{2}))|[;?&=])*)(?::(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),]|(?:%[a-
fA-F\d]{2}))|[;?&=])*))?@)?(?:(?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-
)*[a-zA-Z\d])?)\.)*(?:[a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?: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[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:
\.(?:\d+)){3}))(?::(?:\d+))?)(?:(?:/(?:(?:(?:(?:(?:[a-zA-Z\d\$\-_.!~*'
(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\-_.!~*'(),
])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))?)|(?:/(?:(?:(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d\$\
-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?))|(?:(?:(?:(?:(?:[a-zA-
Z\d\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*)(?:/(?:(?:(?:[a-zA-Z\d
\$\-_.!~*'(),])|(?:%[a-fA-F\d]{2})|[:@&=+])*))*)?)))
Given its complexibility, I think you should go the urlparse way.
For completeness, here's the pseudo-BNF of the above regex (as a documentation):
; The generic form of a URL is: genericurl = scheme ":" schemepart ; Specific predefined schemes are defined here; new schemes ; may be registered with IANA url = httpurl | ftpurl | newsurl | nntpurl | telneturl | gopherurl | waisurl | mailtourl | fileurl | prosperourl | otherurl ; new schemes follow the general syntax otherurl = genericurl ; the scheme is in lower case; interpreters should use case-ignore scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] schemepart = *xchar | ip-schemepart ; URL schemeparts for ip based protocols: ip-schemepart = "//" login [ "/" urlpath ] login = [ user [ ":" password ] "@" ] hostport hostport = host [ ":" port ] host = hostname | hostnumber hostname = *[ domainlabel "." ] toplabel domainlabel = alphadigit | alphadigit *[ alphadigit | "-" ] alphadigit toplabel = alpha | alpha *[ alphadigit | "-" ] alphadigit alphadigit = alpha | digit hostnumber = digits "." digits "." digits "." digits port = digits user = *[ uchar | ";" | "?" | "&" | "=" ] password = *[ uchar | ";" | "?" | "&" | "=" ] urlpath = *xchar ; depends on protocol see section 3.1 ; The predefined schemes: ; FTP (see also RFC959) ftpurl = "ftp://" login [ "/" fpath [ ";type=" ftptype ]] fpath = fsegment *[ "/" fsegment ] fsegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] ftptype = "A" | "I" | "D" | "a" | "i" | "d" ; FILE fileurl = "file://" [ host | "localhost" ] "/" fpath ; HTTP httpurl = "http://" hostport [ "/" hpath [ "?" search ]] hpath = hsegment *[ "/" hsegment ] hsegment = *[ uchar | ";" | ":" | "@" | "&" | "=" ] search = *[ uchar | ";" | ":" | "@" | "&" | "=" ] ; GOPHER (see also RFC1436) gopherurl = "gopher://" hostport [ / [ gtype [ selector [ "%09" search [ "%09" gopher+_string ] ] ] ] ] gtype = xchar selector = *xchar gopher+_string = *xchar ; MAILTO (see also RFC822) mailtourl = "mailto:" encoded822addr encoded822addr = 1*xchar ; further defined in RFC822 ; NEWS (see also RFC1036) newsurl = "news:" grouppart grouppart = "*" | group | article group = alpha *[ alpha | digit | "-" | "." | "+" | "_" ] article = 1*[ uchar | ";" | "/" | "?" | ":" | "&" | "=" ] "@" host ; NNTP (see also RFC977) nntpurl = "nntp://" hostport "/" group [ "/" digits ] ; TELNET telneturl = "telnet://" login [ "/" ] ; WAIS (see also RFC1625) waisurl = waisdatabase | waisindex | waisdoc waisdatabase = "wais://" hostport "/" database waisindex = "wais://" hostport "/" database "?" search waisdoc = "wais://" hostport "/" database "/" wtype "/" wpath database = *uchar wtype = *uchar wpath = *uchar ; PROSPERO prosperourl = "prospero://" hostport "/" ppath *[ fieldspec ] ppath = psegment *[ "/" psegment ] psegment = *[ uchar | "?" | ":" | "@" | "&" | "=" ] fieldspec = ";" fieldname "=" fieldvalue fieldname = *[ uchar | "?" | ":" | "@" | "&" ] fieldvalue = *[ uchar | "?" | ":" | "@" | "&" ] ; Miscellaneous definitions lowalpha = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" hialpha = "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" alpha = lowalpha | hialpha digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" safe = "$" | "-" | "_" | "." | "+" extra = "!" | "*" | "'" | "(" | ")" | "," national = "{" | "}" | "|" | "\" | "^" | "~" | "[" | "]" | "`" punctuation = "" | "#" | "%" | reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f" escape = "%" hex hex unreserved = alpha | digit | safe | extra uchar = unreserved | escape xchar = unreserved | reserved | escape digits = 1*digit
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
If you really need a list:
>>> list(string.ascii_lowercase)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
And to do it with range
>>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1)))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
Other helpful string
module features:
>>> help(string) # on Python 3
....
DATA
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
octdigits = '01234567'
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace = ' \t\n\r\x0b\x0c'
Instead of catching the error, wouldn't it be possible to test in or before the myplotfunction()
function first if the error will occur (i.e. if the breaks are unique) and only plot it for those cases where it won't appear?!
try
<img src="https://cdn.glitch.com/0e4d1ff3-5897-47c5-9711-d026c01539b8%2Fbddfd6e4434f42662b009295c9bab86e.gif?v=1573157191712" alt="this slowpoke moves" width="250" alt="404 image"/>
_x000D_
and switch the src with your source. If the alt pops up, try a different url. If it doesn't work, restart your computer or switch your browser.
<script>_x000D_
$(document).ready(function(){_x000D_
var a =parseInt($("#a").val());_x000D_
var b =parseInt($("#b").val());_x000D_
$("#submit").on("click",function(){_x000D_
var sum = a + b;_x000D_
alert(sum);_x000D_
});_x000D_
});_x000D_
</script>
_x000D_
This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''
Assuming the first parameter is an empty variable here is a simple example:
Wrong
nvl( ,0)
Fix
nvl('' ,0)
Put your query into your database software and check it for that error. Generally this is an easy fix
I would suggest you Matrix library as an open source tool for c++, its usage is like arrays in c++. Here you can see documention.
Matrix funcionName(){
Matrix<int> arr(2, 2);
arr[0][0] = 5;
arr[0][1] = 10;
arr[1][0] = 0;
arr[1][1] = 44;
return arr;
}
By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.
I thought I'd toss in the boost solution as well:
#include <boost/algorithm/string/replace.hpp>
// in place
std::string in_place = "blah#blah";
boost::replace_all(in_place, "#", "@");
// copy
const std::string input = "blah#blah";
std::string output = boost::replace_all_copy(input, "#", "@");
Just tried the stored procedure script. Seems the problem is the '
marks around the delimiters. The MySQL Docs show that delimiter characters do not need the single quotes.
So you want:
delimiter //
Instead of:
delimiter '//'
Works for me :)
Check out setParseBigDecimal
in DecimalFormat. With this setter, parse
will return a BigDecimal for you.
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
Try: http://www.mattweber.org/2007/03/04/python-script-renamepy/
I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.
This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.
The program's source code is also available.
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
task :build_all do
[ :debug, :release ].each do |t|
$build_type = t
Rake::Task["build"].reenable
Rake::Task["build"].invoke
end
end
That should sort you out, just needed the same thing myself.
doAnswer
and thenReturn
do the same thing if:
Let's mock this BookService
public interface BookService {
String getAuthor();
void queryBookTitle(BookServiceCallback callback);
}
You can stub getAuthor() using doAnswer
and thenReturn
.
BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return "Joshua";
}
}).when(service).getAuthor();
Note that when using doAnswer
, you can't pass a method on when
.
// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());
So, when would you use doAnswer
instead of thenReturn
? I can think of two use cases:
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
BookServiceCallback callback = new BookServiceCallback() {
@Override
public void onSuccess(String bookTitle) {
assertEquals("Effective Java", bookTitle);
}
};
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
callback.onSuccess("Effective Java");
// return null because queryBookTitle is void
return null;
}
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:
List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));
Using doAnswer we can stub it safely.
List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));
Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn
.
List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));
If the purpose of a dark theme is to make your eyes comfortable, you can enable High Contrast settings of your Operating System. For example in Windows 8.1 you can turn on - off High Contrast by pressing ALT + left SHIFT + PRINT SCREEN
This will make entire OS in dark mode, not only eclipse. Below is a sample screenshot of Eclipse with High Contrast enabled
The first answer mentioned how to get the description property programatically. If you're going to bother with program anyway, since the comments in the query are so kludgy, instead of trying to put the comments in the query, maybe it's better to put them in a program and use the program to make all your queries
Dim dbs As DAO.Database
Dim qry As DAO.QueryDef
Set dbs = CurrentDb
'put your comments wherever in your program makes the most sense
dbs.QueryDefs("qryName").SQL = "SELECT whatever.fields FROM whatever_table;"
DoCmd.OpenQuery "qryname"
You can use gitk [filename]
to see the changes log
It would seem that is.nan
doesn't actually have a method for data frames, unlike is.na
. So, let's fix that!
is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))
data123[is.nan(data123)] <- 0
Eclipse can show/highlight code that can't be reached. JUnit can show you code coverage, but you'd need some tests and have to decide if the relevant test is missing or the code is really unused.
You need to generate an SSH key (if you don't have one) and associate the public key with your Github account. See Github's own documentation.
As pointed out by @AlexDupuy in the comments, definition lists can be used for this.
This is not supported by all markdown processors, but is widely available: Markdown Guide - Definition Lists
Term 1
: definition 1
: definition 2
Term 2
: definition 1
: definition 2
Renders as (html):
<dl>
<dt>Term 1</dt>
<dd>definition 1</dd>
<dd>definition 2</dd>
<dt>Term 2</dt>
<dd>definition 1</dd>
<dd>definition 2</dd>
</dl>
Typically the DT
is rendered in a heading-like format, and each DD
is rendered as indented text beneath this.
If you don't want a heading/term, just use a non-breaking space in place of the definition term:
: This is the text that I want indented. All text on the same line as the preceding colon will be included in this definition.
: If you include a second definition you'll get a new line; potentially separated by a space. <br />Some inline HTML may be supported within this too, allowing you to create new lines without spaces.
: Support for other markdown syntax varies; e.g. we can add a bullet list, but each one's wrapped in a separate definition term, so the spacing may be out.
: - item 1
: - item 2
: - item 3
You can see this in action by copy-pasting the above examples to this site: Stack Edit Markdown Editor
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
I had this problem because I forgot to select "Visual C++" when I was installing Visual Studio.
To add it, see: https://stackoverflow.com/a/31568246/1054322
Assume you got a JSON like this
[
{
"type": "qrcode",
"symbol": [
{
"seq": 0,
"data": "HelloWorld9887725216",
"error": null
}
]
}
]
To parse the above JSON in unity, you can create JSON model like this.
[System.Serializable]
public class QrCodeResult
{
public QRCodeData[] result;
}
[System.Serializable]
public class Symbol
{
public int seq;
public string data;
public string error;
}
[System.Serializable]
public class QRCodeData
{
public string type;
public Symbol[] symbol;
}
And then simply parse in the following manner...
var myObject = JsonUtility.FromJson<QrCodeResult>("{\"result\":" + jsonString.ToString() + "}");
Now you can modify the JSON/CODE according to your need. https://docs.unity3d.com/Manual/JSONSerialization.html
\d will not match the decimal point. Use the following for the decimal.
const re = /^\d*(\.\d+)?$/
'123'.match(re) // true
'123.3'.match(re) // true
'123!3'.match(re) // false
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(message);
}
Use the return
keyword.
From MSDN:
The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.
So in your case, the usage would be:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
return; //exit this event
}
}
UIWebView
and UIWebViewDelegate
are deprecated. You won't be allowed to push an update to the Appstore with it. Reference
Use WKWebView and WKNavigationDelegate
Sample code:
class YourClass: WKNavigationDelegate {
override public func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView()
webView.navigationDelegate = self
self.view.addaddSubview(webView)
}
public func webView(_ webView: WKWebView,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let cred = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, cred)
}
public func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
self.webView.load(navigationAction.request)
decisionHandler(.allow)
}
}
When going the other way (hasMany):
User::with(array('post'=>function($query){
$query->select('id','user_id');
}))->get();
Don't forget to include the foreign key (assuming it is user_id in this example) to resolve the relationship, otherwise you'll get zero results for your relation.
Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.
Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.
And fight the temptation of using eval
, that's not safe.
I faced this issue when I was tring to link a locally created repo with a blank repo on github.
Initially I was trying git remote set-url
but I had to do git remote add
instead.
git remote add origin https://github.com/VijayNew/NewExample.git
%u prints unsigned integer
%d prints signed integer
to get a pointer address use %p
Here are the full list of formatting escapes. I am just giving a screen shot from this page
It is simple. So follow this code.
decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);
Result is 11
Simply delete the maintenance.flag
file in root folder and then delete the files of cache folder and session folder inside var/
folder.
You can turn the values of an Object into an array and test that a string is present. It assumes that the Object is not nested and the string is an exact match:
var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
console.log('has test1');
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
@Someone Somewhere I used this to clear focus:
editText.clearFocus();
and it helps
Programming to Interfaces is awesome, it promotes loose coupling. As @lassevk mentioned, Inversion of Control is a great use of this.
In addition, look into SOLID principals. here is a video series
It goes through a hard coded (strongly coupled example) then looks at interfaces, finally progressing to a IoC/DI tool (NInject)
The simple solution is:
1.keep the image file and HTML file in the same folder.
2.code: <img src="Desert.png">
// your image name.
3.keep the folder in D drive.
Keeping the folder on the desktop(which is c drive) you can face the issue of permission.
If you want to access folder you specified using Anaconda Prompt, try typing
cd C:\Users\u354590
Why not a named anchor?
You can either use the prepareStatement
method taking an additional int
parameter
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:
PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})
In our case, it helped to add a parameter for SQL Server service:
Services.msc
, select SQL Server Service
and open Properties. Startup Parameters
and add new
parameter –g512
As you say, there are some important differences between ToUpper and ToLower, and only one is dependably accurate when you're trying to do case insensitive equality checks.
Ideally, the best way to do a case-insensitive equality check would be:
String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)
NOTE, HOWEVER that this does not work in this case! Therefore we are stuck with ToUpper
or ToLower
.
Note the OrdinalIgnoreCase to make it security-safe. But exactly the type of case (in)sensitive check you use depends on what your purposes is. But in general use Equals for equality checks and Compare when you're sorting, and then pick the right StringComparison for the job.
Michael Kaplan (a recognized authority on culture and character handling such as this) has relevant posts on ToUpper vs. ToLower:
He says "String.ToUpper – Use ToUpper rather than ToLower, and specify InvariantCulture in order to pick up OS casing rules"
Short answer: H.264 MPEG (MP4)
Long answer from Apple.com:
Video formats supported: H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second,
Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second,
Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
invalidate();
calls the list view to invalidate itself (ie. background color)
invalidateViews();
calls all of its children to be invalidated. allowing you to update the children views
I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.
To keep the promise chain going, you can't use setTimeout()
the way you did because you aren't returning a promise from the .then()
handler - you're returning it from the setTimeout()
callback which does you no good.
Instead, you can make a simple little delay function like this:
function delay(t, v) {
return new Promise(function(resolve) {
setTimeout(resolve.bind(null, v), t)
});
}
And, then use it like this:
getLinks('links.txt').then(function(links){
let all_links = (JSON.parse(links));
globalObj=all_links;
return getLinks(globalObj["one"]+".txt");
}).then(function(topic){
writeToBody(topic);
// return a promise here that will be chained to prior promise
return delay(1000).then(function() {
return getLinks(globalObj["two"]+".txt");
});
});
Here you're returning a promise from the .then()
handler and thus it is chained appropriately.
You can also add a delay method to the Promise object and then directly use a .delay(x)
method on your promises like this:
function delay(t, v) {_x000D_
return new Promise(function(resolve) { _x000D_
setTimeout(resolve.bind(null, v), t)_x000D_
});_x000D_
}_x000D_
_x000D_
Promise.prototype.delay = function(t) {_x000D_
return this.then(function(v) {_x000D_
return delay(t, v);_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
Promise.resolve("hello").delay(500).then(function(v) {_x000D_
console.log(v);_x000D_
});
_x000D_
Or, use the Bluebird promise library which already has the .delay()
method built-in.
you should be sure
to add this line at your manifest
https://developer.android.com/studio/run/index.html#instant-run
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.
Just do
divToUpdate.html("");
or
divToUpdate.empty();
This should work :
curl -i -H "Accept: application/json" 'server:5050/a/c/getName{"param0":"pradeep"}'
use option -i instead of x.
vim-fugitive is versatile for that kind of examining in Vim.
Use :Ggrep
to do that. For more information you can install vim-fugitive and look up the turorial by :help Grep
. And this episode: exploring-the-history-of-a-git-repository will guide you to do all that.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
Would this CSS fix it?
iframe {
display:block;
width:100%;
}
From this example: http://jsfiddle.net/HNyJS/2/show/
I wrote this code snippet and it works fine:
<a href="#" class="clickable">Blah</a>
<input id="textbox">
<script type="text/javascript">
$(document).ready(function(){
$("a.clickable").click(function(event){
event.preventDefault();
$("input#textbox").val($(this).html());
});
});
</script>
Maybe you forgot to give a class name "clickable" to your links?
If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.
Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"
I would only use Ian's answer if the datetime is being concatenated with another string.
I struggled with this for a while - something so simple, yet so complicated, because ReactJS is just a completely different way of writing web applications, it's very alien to us older folk!
I created a separate component to abstract the mess away:
// LinkButton.js
import React from "react";
import PropTypes from "prop-types";
import {Route} from 'react-router-dom';
export default class LinkButton extends React.Component {
render() {
return (
<Route render={({history}) => (
<button {...this.props}
onClick={() => {
history.push(this.props.to)
}}>
{this.props.children}
</button>
)}/>
);
}
}
LinkButton.propTypes = {
to: PropTypes.string.isRequired
};
Then add it to your render()
method:
<LinkButton className="btn btn-primary" to="/location">
Button Text
</LinkButton>
Using [label sizeToFit];
will achieve the same result from Daniels Category.
Although I recommend to use autolayout and let the label resize itself based on constraints.
try {
$site="http://www.google.com";
$content = file_get_content($site);
echo $content;
} catch (ErrorException $e) {
// fix the url
}
set_error_handler(function ($errorNumber, $errorText, $errorFile,$errorLine )
{
throw new ErrorException($errorText, 0, $errorNumber, $errorFile, $errorLine);
});
As blocking on keyboard input (since the input()
function blocks) is frequently not what we want to do (we'd frequently like to keep doing other stuff), here's a very-stripped-down multi-threaded example to demonstrate how to keep running your main application while still reading in keyboard inputs whenever they arrive.
This works by creating one thread to run in the background, continually calling input()
and then passing any data it receives to a queue.
In this way, your main thread is left to do anything it wants, receiving the keyboard input data from the first thread whenever there is something in the queue.
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
input_str = input()
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit"
inputQueue = queue.Queue()
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
while (True):
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
time.sleep(0.01)
print("End.")
if (__name__ == '__main__'):
main()
"""
read_keyboard_input.py
Gabriel Staples
www.ElectricRCAircraftGuy.com
14 Nov. 2018
References:
- https://pyserial.readthedocs.io/en/latest/pyserial_api.html
- *****https://www.tutorialspoint.com/python/python_multithreading.htm
- *****https://en.wikibooks.org/wiki/Python_Programming/Threading
- https://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass
- https://docs.python.org/3/library/queue.html
- https://docs.python.org/3.7/library/threading.html
To install PySerial: `sudo python3 -m pip install pyserial`
To run this program: `python3 this_filename.py`
"""
import threading
import queue
import time
def read_kbd_input(inputQueue):
print('Ready for keyboard input:')
while (True):
# Receive keyboard input from user.
input_str = input()
# Enqueue this input string.
# Note: Lock not required here since we are only calling a single Queue method, not a sequence of them
# which would otherwise need to be treated as one atomic operation.
inputQueue.put(input_str)
def main():
EXIT_COMMAND = "exit" # Command to exit this program
# The following threading lock is required only if you need to enforce atomic access to a chunk of multiple queue
# method calls in a row. Use this if you have such a need, as follows:
# 1. Pass queueLock as an input parameter to whichever function requires it.
# 2. Call queueLock.acquire() to obtain the lock.
# 3. Do your series of queue calls which need to be treated as one big atomic operation, such as calling
# inputQueue.qsize(), followed by inputQueue.put(), for example.
# 4. Call queueLock.release() to release the lock.
# queueLock = threading.Lock()
#Keyboard input queue to pass data from the thread reading the keyboard inputs to the main thread.
inputQueue = queue.Queue()
# Create & start a thread to read keyboard inputs.
# Set daemon to True to auto-kill this thread when all other non-daemonic threads are exited. This is desired since
# this thread has no cleanup to do, which would otherwise require a more graceful approach to clean up then exit.
inputThread = threading.Thread(target=read_kbd_input, args=(inputQueue,), daemon=True)
inputThread.start()
# Main loop
while (True):
# Read keyboard inputs
# Note: if this queue were being read in multiple places we would need to use the queueLock above to ensure
# multi-method-call atomic access. Since this is the only place we are removing from the queue, however, in this
# example program, no locks are required.
if (inputQueue.qsize() > 0):
input_str = inputQueue.get()
print("input_str = {}".format(input_str))
if (input_str == EXIT_COMMAND):
print("Exiting serial terminal.")
break # exit the while loop
# Insert your code here to do whatever you want with the input_str.
# The rest of your program goes here.
# Sleep for a short time to prevent this thread from sucking up all of your CPU resources on your PC.
time.sleep(0.01)
print("End.")
# If you run this Python file directly (ex: via `python3 this_filename.py`), do the following:
if (__name__ == '__main__'):
main()
$ python3 read_keyboard_input.py
Ready for keyboard input:
hey
input_str = hey
hello
input_str = hello
7000
input_str = 7000
exit
input_str = exit
Exiting serial terminal.
End.
Note that Queue.put()
and Queue.get()
and other Queue class methods are thread-safe! That means they implement all the internal locking semantics required for inter-thread operations, so each function call in the queue class can be considered as a single, atomic operation. See the notes at the top of the documentation: https://docs.python.org/3/library/queue.html (emphasis added):
The queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics.
<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>
Using data.frame
instead of cbind
should be helpful
x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
col1 col2 col3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
sapply(x, class) # looking into x to see the class of each element
col1 col2 col3
"numeric" "factor" "factor"
As you can see elements from col1 are numeric
as you wish.
data.frame
can have variables of different class
: numeric
, factor
and character
but matrix
doesn't, once you put a character
element into a matrix all the other will become into this class no matter what clase they were before.
It permanently comments out that code so the compiler will never compile it.
The coder can later change the #ifdef to have that code compile in the program if he wants to.
It's exactly like the code doesn't exist.
Try
select date_part('year', your_column) from your_table;
or
select extract(year from your_column) from your_table;
C99 offers some really cool stuff using anonymous arrays:
Removing pointless variables
{
int yes=1;
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
}
becomes
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, (int[]){1}, sizeof(int));
Passing a Variable Amount of Arguments
void func(type* values) {
while(*values) {
x = *values++;
/* do whatever with x */
}
}
func((type[]){val1,val2,val3,val4,0});
Static linked lists
int main() {
struct llist { int a; struct llist* next;};
#define cons(x,y) (struct llist[]){{x,y}}
struct llist *list=cons(1, cons(2, cons(3, cons(4, NULL))));
struct llist *p = list;
while(p != 0) {
printf("%d\n", p->a);
p = p->next;
}
}
Any I'm sure many other cool techniques I haven't thought of.
Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.
You will need:
Change the file extension of the .apk
file by either adding a .zip
extension to the filename, or to change .apk
to .zip
.
For example, com.example.apk
becomes com.example.zip
, or com.example.apk.zip
. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:
Extract the renamed APK file in a specific folder. For example, let that folder be demofolder
.
If it didn't work, try opening the file in another application such as WinZip or 7-Zip.
For macOS, you can try running unzip
in Terminal (available at /Applications/Terminal.app
), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip
for documentation and arguments.
Download dex2jar
(see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.
Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex
and press enter. This will generate classes-dex2jar.jar
file in the same folder.
d2j-dex2jar.bat
with d2j-dex2jar.sh
. In other words, run d2j-jar2dex.sh classes.dex
in the terminal and press enter.Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.
From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar
file into it, or go to File > Open File...
and browse for the jar.
Next, in the menu, go to File > Save All Sources
(Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)
Extract that zip file (classes-dex2jar.jar.src.zip
) and you should get all java files of the application.
xml
files from APKapktool
website for installation instructions and moreWindows:
myxmlfolder
).myxmlfolder
folder and rename the apktool jar file to apktool.jar
..apk
file in the same folder (i.e myxmlfolder
).Open the command prompt (or terminal) and change your current directory to the folder where apktool
is stored (in this case, myxmlfolder
). Next, type the command apktool if framework-res.apk
.
What we're doing here is that we are installing a framework. For more info, see the docs.
In the command prompt, type the command apktool d filename.apk
(where filename
is the name of apk file). This should decode the file. For more info, see the docs.
This should result in a folder filename.out
being outputted, where filename
is the original name of the apk file without the .apk
file extension. In this folder are all the XML files such as layout, drawables etc.
Source: How to get source code from APK file - Comptech Blogspot
Although prop changed the checked status but change also show that in the form.
$('input[name="correctAnswer"]').prop('checked', false).change();
In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
I found it easier in following links:
In
http://www.remondo.net/visitor-pattern-example-csharp/ I found an example that shows an mock example that shows what is benefit of visitor pattern. Here you have different container classes for Pill
:
namespace DesignPatterns
{
public class BlisterPack
{
// Pairs so x2
public int TabletPairs { get; set; }
}
public class Bottle
{
// Unsigned
public uint Items { get; set; }
}
public class Jar
{
// Signed
public int Pieces { get; set; }
}
}
As you see in above, You BilsterPack
contain pairs of Pills' so you need to multiply number of pair's by 2. Also you may notice that Bottle
use unit
which is different datatype and need to be cast.
So in main method you may calculate pill count using following code:
foreach (var item in packageList)
{
if (item.GetType() == typeof (BlisterPack))
{
pillCount += ((BlisterPack) item).TabletPairs * 2;
}
else if (item.GetType() == typeof (Bottle))
{
pillCount += (int) ((Bottle) item).Items;
}
else if (item.GetType() == typeof (Jar))
{
pillCount += ((Jar) item).Pieces;
}
}
Notice that above code violate Single Responsibility Principle
. That means you must change main method code if you add new type of container. Also making switch longer is bad practice.
So by introducing following code:
public class PillCountVisitor : IVisitor
{
public int Count { get; private set; }
#region IVisitor Members
public void Visit(BlisterPack blisterPack)
{
Count += blisterPack.TabletPairs * 2;
}
public void Visit(Bottle bottle)
{
Count += (int)bottle.Items;
}
public void Visit(Jar jar)
{
Count += jar.Pieces;
}
#endregion
}
You moved responsibility of counting number of Pill
s to class called PillCountVisitor
(And we removed switch case statement). That mean's whenever you need to add new type of pill container you should change only PillCountVisitor
class. Also notice IVisitor
interface is general for using in another scenarios.
By adding Accept method to pill container class:
public class BlisterPack : IAcceptor
{
public int TabletPairs { get; set; }
#region IAcceptor Members
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
#endregion
}
we allow visitor to visit pill container classes.
At the end we calculate pill count using following code:
var visitor = new PillCountVisitor();
foreach (IAcceptor item in packageList)
{
item.Accept(visitor);
}
That mean's: Every pill container allow the PillCountVisitor
visitor to see their pills count. He know how to count your pill's.
At the visitor.Count
has the value of pills.
In http://butunclebob.com/ArticleS.UncleBob.IuseVisitor you see real scenario in which you can not use polymorphism (the answer) to follow Single Responsibility Principle. In fact in:
public class HourlyEmployee extends Employee {
public String reportQtdHoursAndPay() {
//generate the line for this hourly employee
}
}
the reportQtdHoursAndPay
method is for reporting and representation and this violate the Single Responsibility Principle. So it is better to use visitor pattern to overcome the problem.
The framework creates threads to support each window you create, eg, as when you create a Form and .Show() it. When the windows close, the threads are terminated (ie, they exit).
This is normal behavior. However, if the application is creating threads, and there are a lot of thread exit messages corresponding to these threads (one could tell possibly by the thread's names, by giving them distinct names in the app), then perhaps this is indicative of a problem with the app creating threads when it shouldn't, due to a program logic error.
It would be an interesting followup to have the original poster let us know what s/he discovered regarding the problems with the server crashing. I have a feeling it wouldn't have anything to do with this... but it's hard to tell from the information posted.
CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf
, and upload it to your remote server where your blog or website is hosted.
@font-face {
font-family: myfont;
src: url('myfont.ttf');
}
If you want to "get" an attribute, there is a very simple answer, which should be obvious: getattr
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
return self.a
>>> getattr(MyClass, 'a')
'12'
>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>
It works dandy both in Python 2.7 and Python 3.x.
If you want a list of these items, you will still need to use inspect.
With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request
Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs
using System;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc
{
public static class HttpRequestExtensions
{
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
}
I searched for a while now on this and hope that will help some others too ;)
If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:
IdentityFile ~/.foo/identity
man ssh_config
to find other config options.
That's it! There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it.
Note that this is the same regardless of what kind of virtual environment you are using. virtualenv
, venv
, Anaconda environment, pyenv
, pipenv
are all based the same principle here.
Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.
//jQuery
jQuery(document).ready(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
$(window).scrollTop($("#<%=hidScroll.ClientID %>").val());
$(window).scroll(function (event) {
$("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
});
});
//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />
Sure, just use the arguments
object.
function foo() {
for (var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
This is how I did it without scripting:
@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}
Same, but with parameter and confirmation dialog:
@using (Html.BeginForm("Action", "Controller",
new { paramName = paramValue },
FormMethod.Get,
new { onsubmit = "return confirm('Are you sure?');" }))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}
INDEX=0
for i in $list; do
echo ${INDEX}_$i
let INDEX=${INDEX}+1
done
Another option is to use Upstart. It was originally developed for Ubuntu (and comes packaged with it by default), but is intended to be suitable for all Linux distros.
This approach is similar to Supervisord and daemontools, in that it automatically starts the daemon on system boot and respawns on script completion.
Create a new script file at /etc/init/myphpworker.conf
. Here is an example:
# Info
description "My PHP Worker"
author "Jonathan"
# Events
start on startup
stop on shutdown
# Automatically respawn
respawn
respawn limit 20 5
# Run the script!
# Note, in this example, if your PHP script returns
# the string "ERROR", the daemon will stop itself.
script
[ $(exec /usr/bin/php -f /path/to/your/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script
sudo service myphpworker start
sudo service myphpworker stop
sudo service myphpworker status
A big thanks to Kevin van Zonneveld, where I learned this technique from.
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
select <column list> into <table name> from <source> where <whereclause>
Try
$myLastElement = end($yourArray);
To reset it (thanks @hopeseekr):
reset($yourArray);
Link to manual
@David Murdoch added:
$myLastElement = end(array_values($yourArray));// and now you don't need to call reset().
On E_STRICT this produces the warning
Strict Standards: Only variables should be passed by reference
Thanks o_O Tync and everyone!
seems you need to link with the obj file that implements tolayer5()
Update: your function declaration doesn't match the implementation:
void tolayer5(int AorB, struct msg msgReceived)
void tolayer5(int, char data[])
So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().
I think you have red so many definitions but in the case you still have doubts or In case you are new to programming and want to go deep into this then I will suggest you to watch this video, https://youtu.be/HpJTGW9AwX0 It's just reference to get more info about polymorphism... Hope you get better understanding with this
You can also use showdialog
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
dim mydialogbox as new aboutbox1
aboutbox1.showdialog()
End Sub
Try git rebase -i master
on your feature branch. You can then change all but one 'pick' to 'squash' to combine the commits. See squashing commits with rebase
Finally, you can then do the merge from master branch.
I think the accepted answer is not the perfect solution because it converts to string
.
If you don't wanna convert to string
and back to a double
use
double.toPrecision(decimalNumber)
from GetX package.
If you don't wanna use GetX just for this (I highly recommend GetX, it will change your life with flutter) you can copy and paste this.
import 'dart:math';
extension Precision on double {
double toPrecision(int fractionDigits) {
var mod = pow(10, fractionDigits.toDouble()).toDouble();
return ((this * mod).round().toDouble() / mod);
}
}
For those who are newbie like me, Open IIS, expand your server name, choose sites, click on your website. On new install, it is Default web site. Click it. On the right side you have Default document option. Double click it. You will see default.htm, default.asp, index.htm etc.. to the extreme right click add. Enter the full name of your file(including extension) that you want to set it as default. click ok. Open cmd prompt as admin and reset iis. Remove all files from c:\inetpub\wwwroot folder like iisstart.html, index.html etc.
Note: This will automatically create web.config file in your c:\inetpub\wwwroot folder. I didnt have any web.config files in my inetpub or wwwroot folders. This automatically created one for me.
Next time when you enter http(s)://servername, it opens the default page you set.
You can set your hash directly to URL too.
window.location.hash = "YourHash";
The result : http://url#YourHash
using Linq would be:
listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";
UPDATE
This can be simplified to be...
listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";
For multiple items (condition is met by multiple items):
listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");
coalesce
is supported in both Oracle and SQL Server and serves essentially the same function as nvl
and isnull
. (There are some important differences, coalesce
can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull
matches the type of the first argument, that is not true for coalesce
, at least on SQL Server.)
In 2.5, theres no way to suppress it, other than measures like not giving users write access to the directory.
In python 2.6 and 3.0 however, there may be a setting in the sys module called "dont_write_bytecode" that can be set to suppress this. This can also be set by passing the "-B" option, or setting the environment variable "PYTHONDONTWRITEBYTECODE"
What you're looking for is n choose k. Basically:
For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).
Since filter
returns a QuerySet
, you can use count to check how many results were returned. This is assuming you don't actually need the results.
num_results = User.objects.filter(email = cleaned_info['username']).count()
After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
num_results = len(user_object)
Well, after looking around the best comparison I've found so far is:
http://www.sturmnet.org/blog/2010/03/04/poll-ioc-containers-for-net
http://www.sturmnet.org/blog/2010/03/04/poll-results-ioc-containers-for-net
It was a poll taken in March 2010.
One point of interest to me is that people who've used a DI/IoC Framework and liked/disliked it, StructureMap appears to come out on top.
Also from the poll, it seems that Castle.Windsor and StructureMap seem to be most highly favoured.
Interestingly, Unity and Spring.Net seem to be the popular options which are most generally disliked. (I was considering Unity out of laziness (and Microsoft badge/support), but I'll be looking more closely at Castle Windsor and StructureMap now.)
Of course this probably (?) doesn't apply to Unity 2.0 which was released in May 2010.
Hopefully someone else can provide a comparison based on direct experience.
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen.
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials
By default, gcc selects the language based on the file extension, but you can force gcc to select a different language backend with the -x option thus:
gcc -x c++
More options are detailed in the gcc man page under "Options controlling the kind of output". See e.g. http://linux.die.net/man/1/gcc (search on the page for the text -x language
).
This facility is very useful in cases where gcc can't guess the language using a file extension, for example if you're generating code and feeding it to gcc via stdin.
Note that as of Gson 2.8.6, instance method JsonParser.parse
has been deprecated and replaced by static method JsonParser.parseString
:
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
ALTER TABLE table_name
CONVERT to CHARACTER SET utf8;
*IMPORTANT: Back-up first, execute after
In Visual Studio 2015 and 2017 for C# code.
For those using AppCompact...Try this
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = (Button) findViewById(R.id.db);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
makeCall();
}
});
}
protected void makeCall() {
EditText num = (EditText)findViewById(R.id.Dail);
String phone = num.getText().toString();
String d = "tel:" + phone ;
Log.i("Make call", "");
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
phoneIntent.setData(Uri.parse(d));
try {
startActivity(phoneIntent);
finish();
Log.i("Finished making a call", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Call faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}
}
Then add this to your manifest,,,
<uses-permission android:name="android.permission.CALL_PHONE" />
It might help if you know little bit of internals...
static_cast
float
to int
. Use static_cast
for them.A
to B
, static_cast
calls B
's constructor passing A
as param. Alternatively, A
could have a conversion operator (i.e. A::operator B()
). If B
doesn't have such constructor, or A
doesn't have a conversion operator, then you get compile time error.A*
to B*
always succeeds if A and B are in inheritance hierarchy (or void) otherwise you get compile error.A&
to B&
.dynamic_cast
(Base*)
to (Derived*)
may fail if pointer is not actually of derived type.A*
to B*
, if cast is invalid then dynamic_cast will return nullptr.A&
to B&
if cast is invalid then dynamic_cast will throw bad_cast exception.const_cast
set<T>
which only returns its elements as const to make sure you don't change its key. However if your intent is to modify object's non-key members then it should be ok. You can use const_cast to remove constness.T& SomeClass::foo()
as well as const T& SomeClass::foo() const
. To avoid code duplication, you can apply const_cast to return value of one function from another.reinterpret_cast
float
to 4 bytes of int
to see how bits in float
looks like.java: Java application executor which is associated with a console to display output/errors
javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.
javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.
All are part of JRE and use the same JVM.
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return '[email protected]'
result['Phone']; // return '123'
"foo is bar".replace(/ /g, '')
Here's some info if someone comes upon this in 2019.
I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.
One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!
Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}
) or returning "falsey" values where a boolean is expected.
Hope this helps someone
From the javadoc:
The serialization runtime associates with each serializable class a version number, called a
serialVersionUID
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a differentserialVersionUID
than that of the corresponding sender's class, then deserialization will result in anInvalidClassException
. A serializable class can declare its ownserialVersionUID
explicitly by declaring a field named"serialVersionUID"
that must be static, final, and of type long:
You can configure your IDE to:
As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":
No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException
.
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
http://underscorejs.org/#omit
var thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
_.omit(thisIsObject,'Cow'); //It will return a new object
=> {'Cat' : 'Meow', 'Dog' : 'Bark'} //result
If you want to modify the current object, assign the returning object to the current object.
thisIsObject = _.omit(thisIsObject,'Cow');
With pure JavaScript, use:
delete thisIsObject['Cow'];
Another option with pure JavaScript.
thisIsObject.cow = undefined;
thisIsObject = JSON.parse(JSON.stringify(thisIsObject ));
As stated in PostgreSQL docs here:
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.
Code snippet specifically answering your question:
SELECT field1, field2,
CASE
WHEN field1>0 THEN field2/field1
ELSE 0
END
AS field3
FROM test
JQuery can't append elements to <svg>
(it does seem to add them in the DOM explorer, but not on the screen).
One workaround is to append an <svg>
with all of the elements that you need to the page, and then modify the attributes of the elements using .attr()
.
$('body')
.append($('<svg><circle id="c" cx="10" cy="10" r="10" fill="green" /></svg>'))
.mousemove( function (e) {
$("#c").attr({
cx: e.pageX,
cy: e.pageY
});
});
You should give the container an id and use that in your custom css file (which should be linked after the bootstrap css):
#container {
box-shadow: values
}
There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard
to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.
To be concrete, here's a simple extension of Nevik Rehnel's original answer:
git reset --hard origin/master
git pull origin master
NOTE: using git reset --hard
will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.
Here is the complete solution for directly integrating a report-viewer control (as well as any asp.net server side control) in an MVC .aspx view, which will also work on a report with multiple pages (unlike Adrian Toman's answer) and with AsyncRendering set to true, (based on "Pro ASP.NET MVC Framework" by Steve Sanderson).
What one needs to do is basically:
Add a form with runat = "server"
Add the control, (for report-viewer controls it can also sometimes work even with AsyncRendering="True" but not always, so check in your specific case)
Add server side scripting by using script tags with runat = "server"
Override the Page_Init event with the code shown below, to enable the use of PostBack and Viewstate
Here is a demonstration:
<form ID="form1" runat="server">
<rsweb:ReportViewer ID="ReportViewer1" runat="server" />
</form>
<script runat="server">
protected void Page_Init(object sender, EventArgs e)
{
Context.Handler = Page;
}
//Other code needed for the report viewer here
</script>
It is of course recommended to fully utilize the MVC approach, by preparing all needed data in the controller, and then passing it to the view via the ViewModel.
This will allow reuse of the View!
However this is only said for data this is needed for every post back, or even if they are required only for initialization if it is not data intensive, and the data also has not to be dependent on the PostBack and ViewState values.
However even data intensive can sometimes be encapsulated into a lambda expression and then passed to the view to be called there.
A couple of notes though:
Gradle is what makes it possible to automate the building of complex Android projects that involve 10s of thousands of lines of code from multiple sources, projects, libraries, etc. It can conditionally generate multiple optimized APKs based on a plethora of configuration specifications - if you are interested, the other answers provide more details of this aspect of Gradle.
However, if you're new to Android development, Gradle in 99% of cases is what stops your project from building. It is an inscrutable, complex system that effectively obfuscates the Android build process and essentially renders it unavailable to inexperienced developers, ie in order to build a simple entry-level Android App the unsuspecting newbie might need to study and understand many things that they didn't bargain for such as:
All these things are interesting and useful for Android developers to know, but they are far from easy and present a formidable barrier to entry. I suspect that what inspired the OP to ask this question is the feeling of frustration that inevitably hits the neophyte developer after spending way too long trying to get a simple app to build and being continually thwarted by Gradle. The problem is perversely exacerbated by the overwhelming quantity of highly technical documentation that is available for all these technologies. Also for a large amount of development needs, Gradle is overkill.
An alternative is to write a shell script that builds your project by automating the tools available in the Android SDK. The virtues of this approach are many, for starters, it's probably the best way to study and understand the build process and the Android ecosystem, and it allows you to completely control how your app is built. However, this approach is more suitable for deeply irredeemable tech-heads than it is to inexperienced noobs trying out android.
What is conspicuous by its absence (please inform me if there is such a thing) is an entry-level, lightweight IDE with a reduced feature set that simultaneously simplifies the build process while not obscuring it (so not Netbeans or Eclipse) it could possibly still use Gradle (what was wrong with Ant). It should make it easy to generate APKs that conform to a few common configurations and use a project structure that can evolve to a full Android Studio project should you decide to take it that way.
You need to use ajax.
http://api.jquery.com/jQuery.ajax/
<code>
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
</code>
Using the standard CustomCreationConverter
, I was struggling to work how to generate the correct type (Person
or Employee
), because in order to determine this you need to analyse the JSON and there is no built in way to do this using the Create
method.
I found a discussion thread pertaining to type conversion and it turned out to provide the answer. Here is a link: Type converting.
What's required is to subclass JsonConverter
, overriding the ReadJson
method and creating a new abstract Create
method which accepts a JObject
.
The JObject class provides a means to load a JSON object and provides access to the data within this object.
The overridden ReadJson
method creates a JObject
and invokes the Create
method (implemented by our derived converter class), passing in the JObject
instance.
This JObject
instance can then be analysed to determine the correct type by checking existence of certain fields.
Example
string json = "[{
\"Department\": \"Department1\",
\"JobTitle\": \"JobTitle1\",
\"FirstName\": \"FirstName1\",
\"LastName\": \"LastName1\"
},{
\"Department\": \"Department2\",
\"JobTitle\": \"JobTitle2\",
\"FirstName\": \"FirstName2\",
\"LastName\": \"LastName2\"
},
{\"Skill\": \"Painter\",
\"FirstName\": \"FirstName3\",
\"LastName\": \"LastName3\"
}]";
List<Person> persons =
JsonConvert.DeserializeObject<List<Person>>(json, new PersonConverter());
...
public class PersonConverter : JsonCreationConverter<Person>
{
protected override Person Create(Type objectType, JObject jObject)
{
if (FieldExists("Skill", jObject))
{
return new Artist();
}
else if (FieldExists("Department", jObject))
{
return new Employee();
}
else
{
return new Person();
}
}
private bool FieldExists(string fieldName, JObject jObject)
{
return jObject[fieldName] != null;
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
/// <summary>
/// Create an instance of objectType, based properties in the JSON object
/// </summary>
/// <param name="objectType">type of object expected</param>
/// <param name="jObject">
/// contents of JSON object that will be deserialized
/// </param>
/// <returns></returns>
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
// Populate the object properties
serializer.Populate(jObject.CreateReader(), target);
return target;
}
}
By alphabetical-order I assume the order to be : A|a < B|b < C|c... Hope this is what @Nick is(or was) looking for and the answer follows the above assumption.
I would suggest to have a class implement compare method of Comparator-interface as :
public int compare(Object o1, Object o2) {
return o1.toString().compareToIgnoreCase(o2.toString());
}
and from the calling method invoke the Arrays.sort method with custom Comparator as :
Arrays.sort(inputArray, customComparator);
Observed results: input Array : "Vani","Kali", "Mohan","Soni","kuldeep","Arun"
output(Alphabetical-order) is : Arun, Kali, kuldeep, Mohan, Soni, Vani
Output(Natural-order by executing Arrays.sort(inputArray) is : Arun, Kali, Mohan, Soni, Vani, kuldeep
Thus in case of natural ordering, [Vani < kuldeep] which to my understanding of alphabetical-order is not the thing desired.
for more understanding of natural and alphabetical/lexical order visit discussion here
to just look at a tables layout from the cli. you would do
desc mytable
or
show table mytable
df = pd.DataFrame({'one' : pd.Series([1., 1, 1, 3]), 'two' : pd.Series([1., 2., 1, 3] ), 'three' : pd.Series([1., 2., 1, 2] )})
df['str_list'] = df.apply(lambda row: ' '.join([str(int(val)) for val in row]), axis=1)
df1 = pd.DataFrame(df['str_list'].value_counts().values, index=df['str_list'].value_counts().index, columns=['Count'])
Produces:
>>> df1
Count
1 1 1 2
3 2 3 1
1 2 2 1
If the index values must be a list, you could take the above code a step further with:
df1.index = df1.index.str.split()
Produces:
Count
[1, 1, 1] 2
[3, 2, 3] 1
[1, 2, 2] 1
As for the path relative to the current executing script, since Ruby 2.0 you can also use
__dir__
So this is basically the same as
File.dirname(__FILE__)
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
libCURL is a pretty good option for you. Depending on what you need to do, the tutorial should tell you what you want, specifically for the easy handle. But, basically, you could do this just to see the source of a page:
CURL* c;
c = curl_easy_init();
curl_easy_setopt( c, CURL_URL, "www.google.com" );
curl_easy_perform( c );
curl_easy_cleanup( c );
I believe this will cause the result to be printed to stdout. If you want to handle it instead -- which, I assume, you do -- you need to set the CURL_WRITEFUNCTION. All of that is covered in the curl tutorial linked above.
You can get this type of error if your class' .m file is not listed under the "Compile Sources" step of the "Build Phases" tab of your target. Normally Xcode does this for you, but sometimes it loses the plot and you need to add the .m file manually.
To do this:
TargetSettings -> Build Phases -> Compile Sources -> add your .m class ->Build and Run
This worked for me On Windows 10,
xcopy /s {source drive..i.e. C:} {destination drive..i.e. D:} This will copy all the files and folders plus the folder contents.
After jQuery 1.6, using promise seems like a better option.
var $div1 = $('#div1');
var fadeOutDone = $div1.fadeOut().promise();
// do your logic here, e.g.fetch your 2nd image url
$.get('secondimageinfo.json').done(function(data){
fadeoOutDone.then(function(){
$div1.html('<img src="' + data.secondImgUrl + '" alt="'data.secondImgAlt'">');
$div1.fadeIn();
});
});
If someone is facing issue using texttocolumns function in UFT. Please try using below function.
myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true
Here we are using coma(,) as delimiter.
There are good resources out there if you know what to search for. Try "Contract First" and WCF. or "WSDL First" and WCF.
Here is a selection:
Just in case someone else encounters this problem. You need to call
window.location.reload()
And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:
(click)="realodPage()"
And simply define the function:
reloadPage() {
window.location.reload();
}
If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay
reloadPage() {
setTimeout(()=>{
window.location.reload();
}, 100);
}
What about like this?
public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
return true;
}
You still have to pass a value to the parameter from C# but it is an optional ref param.
Please make sure you have imported the correct package
import org.springframework.core.env.Environment;
and then use the Environment object
@Autowired
private Environment env; // Environment Object containts the port number
@GetMapping("/status")
public String status()
{
return "it is runing on"+(env.getProperty("local.server.port"));
}
There is also Math.DivRem
quotient = Math.DivRem(dividend, divisor, out remainder);
Did you build the Python from source? If so, you need the --with-ssl
option while building.
From the documentation (help copy-item -full
):
-force <SwitchParameter>
Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.
Required? false
Position? named
Default value False
Accept pipeline input? false
Accept wildcard characters? false
@echo off
RD %TEMP%\. /S /Q
::pause
explorer %temp%
This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.
HTTPbis will address the phrasing of 400 Bad Request so that it covers logical errors as well. So 400 will incorporate 422.
From https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-18#section-7.4.1
"The server cannot or will not process the request, due to a client error (e.g., malformed syntax)"
There are many ways to rename the branch, but I am going to focus on the bigger problem: "how to allow clients to fast-forward and not have to mess with their branches locally".
This is something actually easy to do; but don't abuse it. The whole idea hinges on merge commits; as they allow fast-forward, and link histories of a branch with another.
# rename the branch "master" to "master-old"
# this works even if you are on branch "master"
git branch -m master master-old
# create master from new starting point
git branch master <new-master-start-point>
# now we've got to fix the new branch...
git checkout master
# ... by doing a merge commit that obsoletes
# "master-old" hence the "ours" strategy.
git merge -s ours master-old
git push origin master
This works because creating a merge
commit allows fast-forwarding the branch to a new revision.
renamed branch "master" to "master-old" and use commit ba2f9cc as new "master"
-- this is done by doing a merge commit with "ours" strategy which obsoletes
the branch.
these are the steps I did:
git branch -m master master-old
git branch master ba2f9cc
git checkout master
git merge -s ours master-old
How I would do this
git checkout master
git pull origin master
git merge test
git push origin master
If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test
is only for you? So no reason to publish it.
git always tries to respect yours and others changes, and so will --rebase
. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature
The horizontal scrollbar can appear if the container-fluid
div is placed directly inside the body
.
The correct way to use a container-fluid
structure is:
<body>
<section>
<div class="container-fluid">
<div class="row">
<!-- content goes here -->
</div>
</div>
</section>
</body>
So, try wrapping your container-fluid
DIVs inside an outer div, such as a <div id="wrap">
or a <section>
or <article>
or <aside>
or other specialized <div>
, and presto! no horizontal scrollbar.
...this is obviously performing a 'string' comparison
No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:
WHERE int_column = '1'
...where the string value of "1" is converted to an INTeger because int_column
's data type is INT, not CHAR/VARCHAR/TEXT.
If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:
WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')
Keys must be comparable, but you haven't defined a suitable operator<
for your custom class.
To show the dots instead of the password set the PasswordTransformationMethod:
yourEditText.setTransformationMethod(new PasswordTransformationMethod());
of course you can set this by default in your edittext element in the xml layout with
android:password
To re-show the readable password, just pass null as transformation method:
yourEditText.setTransformationMethod(null);
JavaScript only has a Number type that stores floating point values.
There is no int.
Edit:
If you want to format the number as a string with two digits after the decimal point use:
(4).toFixed(2)
My issue was very simple, the working directory was not the "Source" directory that was printed when the file ran. To fix this, you can use getwd()
and setwd()
to get your relative links working, or just use a full path when opening the csv.
print(getwd()) # Where does the code think it is?
setwd("~/Documents") # Where do I want my code to be?
dat = read.csv("~/Documents/Data Visualization/expDataAnalysis/one/ac1_survey.csv") #just make it work!