I just got that problem when converting from %
formatting to .format()
.
Previous code:
"SET !TIMEOUT_STEP %{USER_TIMEOUT_STEP}d" % {'USER_TIMEOUT_STEP' = 3}
Problematic syntax:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format('USER_TIMEOUT_STEP' = 3)
The problem is that format
is a function that needs parameters. They cannot be strings.
That is one of worst python error messages I've ever seen.
Corrected code:
"SET !TIMEOUT_STEP {USER_TIMEOUT_STEP}".format(USER_TIMEOUT_STEP = 3)
There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.
To modify a remote system's global environment variables, you would use
setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere
This does not require restarting Windows Explorer.
I posted too soon however the ways to configure are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
and way to get access keys are given in below link
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html#cli-signup
You could start converting this java snippet to C the author states he has converted it from C based on the book numerical recipies which you find online! here
A function returns a value and a procedure just executes commands.
The name function comes from math. It is used to calculate a value based on input.
A procedure is a set of command which can be executed in order.
In most programming languages, even functions can have a set of commands. Hence the difference is only in the returning a value part.
But if you like to keep a function clean, (just look at functional languages), you need to make sure a function does not have a side effect.
With HttpClient 4.5 you can do this:
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();
Note that this one implements Closeable (for shutting down of the connection manager).
This answers the 'best random' request:
Adi's answer1 from Security.StackExchange has a solution for this:
Make sure you have OpenSSL support, and you'll never go wrong with this one-liner
$token = bin2hex(openssl_random_pseudo_bytes(16));
1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/
bootstrap.min.css is more specific than your own stylesheet if you just use .table td. So use this instead:
.table>tbody>tr>th, .table>tbody>tr>td {
border-top: none;
}
You can't update with a number greater than 1 for datatype number(2,2)
is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1
. i.e. 0.12, 0.95 etc.
Please check NUMBER DATATYPE in NUMBER Datatype.
UPDATED ANSWER
Google Analytics Admin panel has 3 panels, wherein deleting can be done on any of the following :
Deleting the account, will remove all data pertaining to that account, along with all properties/profiles it contains. This is (usually) as good as removing the entire website data.
To delete the account, follow the following steps : (refer to image below)
Delete Account
Note : If you have multiple accounts linked with your login, the other accounts are NOT touched, only this account will be deleted.
Deleting a property will remove the selected property, and all the views it holds. To delete a property, delete all views it contains individually (see below for deleting views)
Deleting a profile will remove only data pertaining to that view, if there is a single profile, the property is automatically deleted.
Sometimes you have a lot of websites, which you want to keep the data, but remove them from the list, since you don't view them often. I thought of a workaround, in case you do not want to delete the data.
Use another account.
Since A was your primary account, you no longer will be able to access it from the list!
And you still have your data saved, just that you'll have to log in via the other (spare) account.
Previous Answer :
These are the steps to delete a profile from Google Support page :
Delete profiles
Remember, too, that when you delete a profile, you also delete all data associated with that profile, and it is not possible to retrieve that deleted data.
To delete a profile:
- Click the Admin tab at the top right of any Analytics page.
- Click the account that contains the profile you want to delete.
- Click the web property from which you want to delete the profile.
- Use the Profile menu to select the profile.
- Click the Profile Settings tab.
- Click Delete this profile at the bottom of the page.
- Click Delete in the confirmation message.
if somebody still has a problem the only thing working perfectly for me by useing (loaded.bs.modal) :
$('#editModal').on('loaded.bs.modal', function () {
console.log('edit modal loaded');
$('.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
clearBtn: true,
rtl: false,
todayHighlight: true,
toggleActive: true,
changeYear: true,
changeMonth: true
});
});
Assuming the original date is in cell A1:
=A1-180
Works in at least Excel 2003 and 2010.
For the more performance aware devs
uint wrap(int k, int n) ((uint)k)%n
A small performance comparison
Modulo: 00:00:07.2661827 ((n%x)+x)%x)
Cast: 00:00:03.2202334 ((uint)k)%n
If: 00:00:13.5378989 ((k %= n) < 0) ? k+n : k
As for performance cost of cast to uint have a look here
For all who come here trying to run a nginx image in a docker container, that will run as a service
As there is no whole Dockerfile, here is my whole Dockerfile
solving the issue.
Nice and working. Thanks to all answers here in order to solve the final nginx issue.
FROM ubuntu:18.04
MAINTAINER stackoverfloguy "[email protected]"
RUN apt-get update -y
RUN apt-get install net-tools nginx ufw sudo -y
RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
USER docker
RUN sudo ufw default allow incoming
RUN sudo rm /etc/nginx/nginx.conf
RUN sudo rm /etc/nginx/sites-available/default
RUN sudo rm /var/www/html/index.nginx-debian.html
VOLUME /var/log
VOLUME /usr/share/nginx/html
VOLUME /etc/nginx
VOLUME /var/run
COPY conf/nginx.conf /etc/nginx/nginx.conf
COPY content/* /var/www/html/
COPY Dockerfile /var/www/html
COPY start.sh /etc/nginx/start.sh
RUN sudo chmod +x /etc/nginx/start.sh
RUN sudo chmod -R 777 /var/www/html
EXPOSE 80
EXPOSE 443
ENTRYPOINT sudo nginx -c /etc/nginx/nginx.conf -g 'daemon off;'
And run it with:
docker run -p 80:80 -p 443:443 -dit
Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.
Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)
**
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
int returnVal = process.exitValue();
}
**
Since the deprecation of RequestOptions, sending data as body in a DELETE request is not supported.
If you look at the definition of DELETE, it looks like this:
delete<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;
You can send payload along with the DELETE request as part of the params in the options object as follows:
this.http.delete('http://testAPI:3000/stuff', { params: {
data: yourData
}).subscribe((data)=>.
{console.log(data)});
However, note that params only accept data as string or string[] so you will not be able to send your own interface data unless you stringify it.
Try this:
SELECT user.userID, edge.TailUser, edge.Weight
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043
OR
AND edge.HeadUser=5043
instead of WHERE clausule.
I would expect this query to work with your program:
"SELECT COUNT(*) AS count FROM "+lastTempTable+")"
(You need to alias the column, not the table)
In Python 3, the default encoding is "utf-8"
, so you can directly use:
b'hello'.decode()
which is equivalent to
b'hello'.decode(encoding="utf-8")
On the other hand, in Python 2, encoding defaults to the default string encoding. Thus, you should use:
b'hello'.decode(encoding)
where encoding
is the encoding you want.
Note: support for keyword arguments was added in Python 2.7.
If you want the transition work for whole application you can create a rootacivity
and inherit it in the activity you need. In Root Activity's onCreate call overridePendingTransition
with desired direction. And onStart
call overridePendingTransition
with other direction if activity is resumed. Here I am giving full running code below.Correct me if I am wrong.
create this xml file on your anim folder
anim_slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%" >
</translate>
</set>
anim_slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="-100%"
android:toXDelta="0%" >
</translate>
</set>
anim_slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="0%"
android:toXDelta="-100%" >
</translate>
</set>
anim_slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="600"
android:fromXDelta="0%"
android:toXDelta="100%" >
</translate>
</set>
RootActivity
import android.app.Activity;
import android.os.Bundle;
public class RootActivity extends Activity {
int onStartCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onStartCount = 1;
if (savedInstanceState == null) // 1st time
{
this.overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
} else // already created so reverse animation
{
onStartCount = 2;
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
if (onStartCount > 1) {
this.overridePendingTransition(R.anim.anim_slide_in_right,
R.anim.anim_slide_out_right);
} else if (onStartCount == 1) {
onStartCount++;
}
}
}
FirstActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class FirstActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("First Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(i);
}
});
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SecondActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("Second Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(SecondActivity.this, ThirdActivity.class);
startActivity(i);
}
});
}
}
ThirdActivity
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ThirdActivity extends RootActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(R.id.tvTitle);
tv.setText("Third Activity");
Button bt = (Button) findViewById(R.id.buttonNext);
bt.setText("previous");
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
and finally Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.transitiontest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.transitiontest.FirstActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.transitiontest.SecondActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name="com.example.transitiontest.ThirdActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>
According to Javax's persistence documentation:
Whether the column is included in SQL UPDATE statements generated by the persistence provider.
It would be best to understand from the official documentation here.
From the HTTP core module docs:
Example from the documentation:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
If it's still confusing, here's a longer explanation.
You do not need to use ORDER BY
in inner query after WHERE
clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC)
.
SELECT
*
FROM (
SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
stockmain.vrdate,
stockdetail.qty,
stockdetail.rate,
stockdetail.amount,
ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum --< ORDER BY
FROM StockMain
INNER JOIN StockDetail
ON StockMain.stid = StockDetail.stid
INNER JOIN party
ON party.party_id = stockmain.party_id
INNER JOIN item
ON item.item_id = stockdetail.item_id
WHERE stockmain.etype='purchase'
) AS MyDerivedTable
WHERE
MyDerivedTable.RowNum BETWEEN 1 and 5
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
I would dump your query so you can take a look at the SQL that was actually executed and see how that differs from what you wrote.
You should be able to do that with the following code:
$queries = DB::getQueryLog();
$last_query = end($queries);
var_dump($last_query);
die();
Hopefully that should give you enough information to allow you to figure out what's gone wrong.
for MySQL all (and 5.7)
SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;
packed
means it will use the smallest possible space for struct Ball
- i.e. it will cram fields together without paddingaligned
means each struct Ball
will begin on a 4 byte boundary - i.e. for any struct Ball
, its address can be divided by 4These are GCC extensions, not part of any C standard.
All you need to do instal install package libxml2-dev for example:
sudo apt-get install libxml2-dev
On CentOS/RHEL:
sudo yum install libxml2-devel
&
should work just fine, Wikipedia has a List of predefined entities in XML.
In this instance, your div
elements have been changed from block
level elements to inline
elements. A typical characteristic of inline
elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)
There are a few solutions that can be used to solve this.
Example 1 - Comment the whitespace out: (example)
<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>
Example 2 - Remove the line breaks: (example)
<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>
Example 3 - Close part of the tag on the next line (example)
<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>
Example 4 - Close the entire tag on the next line: (example)
<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>
font-size
Since the whitespace between the inline
elements is determined by the font-size
, you could simply reset the font-size
to 0
, and thus remove the space between the elements.
Just set font-size: 0
on the parent elements, and then declare a new font-size
for the children elements. This works, as demonstrated here (example)
#parent {
font-size: 0;
}
#child {
font-size: 16px;
}
This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size
is declared using em
units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline
elements.
display: flex
In some cases, you can also set the display
of the parent element to flex
. (example)
This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.
.parent {
display: flex;
}
.parent > div {
display: inline-block;
padding: 1em;
border: 2px solid #f00;
}
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
display: inline-block;_x000D_
padding: 1em;_x000D_
border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
</div>
_x000D_
It is incredibly unreliable to use negative margins to remove the space between inline
elements. Please don't use negative margins if there are other, more optimal, solutions.
you can use webview in android that will use chrome browser Or you can try Phonegap or sencha Touch
Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders })
, where orders
was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.
.where(`order.id IN (${orders})`);
One possible solution to avoid, which uses multiple CPU cores and expected to go faster, yet it performs about 5X slower:
list.AsParallel().ToArray();
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xs.Serialize(xw, model, ns);
xw.Flush();
return sb.ToString();
}
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
You can add position: fixed;
with top left right bottom 0
attribute, that solution work on older browsers too.
If you want to embed it, add position: absolute;
to the wrapper, and position: relative
to the div outside of the wrapper.
.wrapper {_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
_x000D_
display: grid;_x000D_
border-style: solid;_x000D_
border-color: red;_x000D_
grid-template-columns: repeat(3, 1fr);_x000D_
grid-template-rows: repeat(3, 1fr);_x000D_
grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
border-style: solid;_x000D_
border-color: blue;_x000D_
grid-column: 1 / 3;_x000D_
grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
border-style: solid;_x000D_
border-color: yellow;_x000D_
grid-column: 2 / 4;_x000D_
grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
border-style: solid;_x000D_
border-color: violet;_x000D_
grid-row: 2 / 5;_x000D_
grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
border-style: solid;_x000D_
border-color: aqua;_x000D_
grid-column: 3;_x000D_
grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
border-style: solid;_x000D_
border-color: green;_x000D_
grid-column: 2;_x000D_
grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
border-style: solid;_x000D_
border-color: purple;_x000D_
grid-column: 3;_x000D_
grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
<div class="one">One</div>_x000D_
<div class="two">Two</div>_x000D_
<div class="three">Three</div>_x000D_
<div class="four">Four</div>_x000D_
<div class="five">Five</div>_x000D_
<div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
If you need binary mode, you'll need to do it the hard way:
s = File.open(filename, 'rb') { |f| f.read }
If not, shorter and sweeter is:
s = IO.read(filename)
I went with using the regex from detectmobilebrowser.com to check against the user-agent
string. Even tho it says it was last updated in 2014 it was accurate on the devices I tested.
Here is the C#
code I got from them at the time of submitting this answer:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%
string u = Request.ServerVariables["HTTP_USER_AGENT"];
Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4)))) {
Response.Redirect("http://detectmobilebrowser.com/mobile");
}
%>
I found this on exceljet.net and works for me:
=LEFT(B4,FIND(" ",B4)-1)
I have almost exactly the same code as you and mine works.
Do you have jQueryUI.js included in the page?
There's a fiddle here
<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}
var datePicker = angular.module('app', []);
datePicker.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'DD, d MM, yy',
onSelect: function (date) {
scope.date = date;
scope.$apply();
}
});
}
};
});
You'll also need the ng-app="app" somewhere in your HTML
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.
Jefferson is right, you have to do it backwards.
Here's the c# equivalent:
for (var i == list.Items.Count - 1; i >= 0; i--)
{
list.Items.RemoveAt(i);
}
Styling the infowindow is fairly straightforward with vanilla javascript. I used some of the info from this thread when writing this. I also took into account the possible problems with earlier versions of ie (although I have not tested it with them).
var infowindow = new google.maps.InfoWindow({
content: '<div id="gm_content">'+contentString+'</div>'
});
google.maps.event.addListener(infowindow,'domready',function(){
var el = document.getElementById('gm_content').parentNode.parentNode.parentNode;
el.firstChild.setAttribute('class','closeInfoWindow');
el.firstChild.setAttribute('title','Close Info Window');
el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
el.setAttribute('class','infoWindowContainer');
for(var i=0; i<11; i++){
el = (el.previousElementSibling)?el.previousElementSibling:el.previousSibling;
el.style.display = 'none';
}
});
The code creates the infowindow as usual (no need for plugins, custom overlays or huge code), using a div with an id to hold the content. This gives a hook in the system that we can use to get the correct elements to manipulate with a simple external stylesheet.
There are a couple of extra pieces (that are not strictly needed) which handle things like giving a hook into the div with the close info window image in it.
The final loop hides all the pieces of the pointer arrow. I needed this myself as I wanted to have transparency on the infowindow and the arrow got in the way. Of course, with the hook, changing the code to replace the arrow image with a png of your choice should be fairly simple too.
If you want to change it to jquery (no idea why you would) then that should be fairly simple.
I'm not usually a javascript developer so any thoughts, comments, criticisms welcome :)
Be careful if you're using a theme or something, they'll often declare img max-width at 100%. You got to make none. Test it out :)
https://jsfiddle.net/o63u8sh4/
<p>Original:</p>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
<p>Wrapped:</p>
<div>
<img src="http://i.stack.imgur.com/2OrtT.jpg" alt="image"/>
</div>
div{
width:150px;
height:100px;
position:relative;
overflow:hidden;
}
div img{
min-width:100%;
min-height:100%;
height:auto;
position:relative;
top:50%;
left:50%;
transform:translateY(-50%) translateX(-50%);
}
Use this code
using System.Threading;
// ...
Thread.Sleep(50);
When using IN
with a collection-valued parameter you don't need (...)
:
@NamedQuery(name = "EventLog.viewDatesInclude",
query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND "
+ "el.timeMark <= :dateTo AND "
+ "el.name IN :inclList")
Here are conversion method for both ways. this = instance of your class
public string ToXML()
{
using(var stringwriter = new System.IO.StringWriter())
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
}
public static YourClass LoadFromXMLString(string xmlText)
{
using(var stringReader = new System.IO.StringReader(xmlText))
{
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
}
try sudo vi /etc/ssh/sshd_config
in first few lies you'll find
Package generated configuration file
See the sshd_config(5) manpage for details
What ports, IPs and protocols we listen for
Port xxxxx
change Port xxxxx to "Port 22" and exit vi by saving changes.
restart ssh sudo service ssh restart
I started off using curl
, but since have migrated to use kibana
. Here is some more information on the ELK stack from elastic.co (E elastic search, K kibana): https://www.elastic.co/elk-stack
With kibana your POST
requests are a bit more simple:
POST /<INDEX_NAME>/<TYPE_NAME>
{
"field": "value",
"id": 1,
"account_id": 213,
"name": "kimchy"
}
If you want to round off then use the round function. Use ceiling function when you want to get the smallest integer just greater than your argument.
For ex: select round(843.4923423423,0) from dual gives you 843 and
select round(843.6923423423,0) from dual gives you 844
You have a lot of unnecessary keyframes. Don't think of keyframes as individual frames, think of them as "steps" in your animation and the computer fills in the frames between the keyframes.
Here is a solution that cleans up a lot of code and makes the animation start from the center:
.gps_ring {
border: 3px solid #999;
-webkit-border-radius: 30px;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
You can see it in action here: http://jsfiddle.net/Fy8vD/
Another built-in command that's long been installed in Windows by default dating back to 2003 is Certutil, which of course can be invoked from PowerShell, too.
CertUtil -hashfile file.foo MD5
(Caveat: MD5 should be in all caps for maximum robustness)
The metacharacter \b
is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.
There are three different positions that qualify as word boundaries:
Simply put: \b
allows you to perform a "whole words only" search using a regular expression in the form of \bword\b
. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".
In all flavors, the characters [a-zA-Z0-9_]
are word characters. These are also matched by the short-hand character class \w
. Flavors showing "ascii" for word boundaries in the flavor comparison recognize only these as word characters.
\w
stands for "word character", usually [A-Za-z0-9_]
. Notice the inclusion of the underscore and digits.
\B
is the negated version of \b
. \B
matches at every position where \b
does not. Effectively, \B
matches at any position between two word characters as well as at any position between two non-word characters.
\W
is short for [^\w]
, the negated version of \w
.
EDIT: Use this Solution here: https://stackoverflow.com/a/20559175/2033223 Works perfect!
First of, thank for your solution @luizfelipetx
I changed your solution a little bit. This works for me:
public static String getRealPathFromDocumentUri(Context context, Uri uri){
String filePath = "";
Pattern p = Pattern.compile("(\\d+)$");
Matcher m = p.matcher(uri.toString());
if (!m.find()) {
Log.e(ImageConverter.class.getSimpleName(), "ID for requested image not found: " + uri.toString());
return filePath;
}
String imgId = m.group();
String[] column = { MediaStore.Images.Media.DATA };
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ imgId }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
Note: So we got documents and image, depending, if the image comes from 'recents', 'gallery' or what ever. So I extract the image ID first before looking it up.
This code will do that
<?php
$string = 'abc-123-xyz-789';
$output = explode("-",$string);
echo $output[count($output)-1];
?>
The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources
.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FilenameUtils;
public class ImageDownloader
{
public static void main(String[] arguments) throws IOException
{
downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
new File("").getAbsolutePath());
}
public static void downloadImage(String sourceUrl, String targetDirectory)
throws MalformedURLException, IOException, FileNotFoundException
{
URL imageUrl = new URL(sourceUrl);
try (InputStream imageReader = new BufferedInputStream(
imageUrl.openStream());
OutputStream imageWriter = new BufferedOutputStream(
new FileOutputStream(targetDirectory + File.separator
+ FilenameUtils.getName(sourceUrl)));)
{
int readByte;
while ((readByte = imageReader.read()) != -1)
{
imageWriter.write(readByte);
}
}
}
}
Interestingly, http://maps.apple.com
links will open directly in Apple Maps on an iOS device, or redirect to Google Maps otherwise (which is then intercepted on an Android device), so you can craft a careful URL that will do the right thing in both cases using an "Apple Maps" URL like:
http://maps.apple.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA
Alternatively, you can use a Google Maps url directly (without the /maps
URL component) to open directly in Google Maps on an Android device, or open in Google Maps' Mobile Web on an iOS device:
http://maps.google.com/?daddr=1+Infinite+Loop,+Cupertino+CA
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.
If you want all columns where link is unique:
SELECT * FROM posted WHERE link in
(SELECT link FROM posted WHERE ad='$key' GROUP BY link);
DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.
Because the TOP 1
from the ordered sub-query does not have profile_id = 'u162231993'
Remove where u.id = 'u162231993'
and see results then.
Run the sub-query separately to understand what's going on.
You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev
where rev
is the last revision at which the file existed.
I had to do exactly this a little while ago and if I remember correctly, using the -r
option to svn
didn't work; I had to use the :rev
syntax. (Although I might have remembered it backwards...)
I suggest you use TO_CHAR()
when converting to string. In order to do that, you need to build a date first.
SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
(SELECT EXTRACT( DAY FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
FROM DUAL
)) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)), 09) AS MONTH, EXTRACT(YEAR FROM
(SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
)) AS YEAR
FROM DUAL
);
R is missing a concurrent assignment as proposed by Edsger W. Dijkstra in A Discipline of Programming, 1976, ch.4, p.29. This would allow for an elegant solution:
a, b <- b, a # swap
a, b, c <- c, a, b # rotate right
I'm using Cors 5.1.0.0, after much headache, I discovered the issue to be duplicated Access-Control-Allow-Origin & Access-Control-Allow-Header headers from the server
Removed config.EnableCors()
from the WebApiConfig.cs file and just set the [EnableCors("*","*","*")]
attribute on the Controller class
Check this article for more detail.
It's worth noting that if you want to sort particular properties descending, you don't want to simply append .reverse() at the end, as this will make all of the sorts descending.
To make particular sorts descending, chain your sorts from least significant to most significant, calling .reverse() after each sort that you want to be descending.
var data = _(data).chain()
.sort("date")
.reverse() // sort by date descending
.sort("name") // sort by name ascending
.result()
Since _'s sort is a stable sort, you can safely chain and reverse sorts because if two items have the same value for a property, their order is preserved.
May be like this:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^OLDDOMAIN\.com$ [NC]
RewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L]
The best answer for this question was answered here:
Getting the source directory of a Bash script from within
And it is:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
One-liner which will give you the full directory name of the script no matter where it is being called from.
To understand how it works you can execute the following script:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX()
or isXXXX()
as a method name. From the Java Beans spec:
8.3.2 Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is
<PropertyName>()
;This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:
public boolean isMarsupial(); public void setMarsupial(boolean m);
If you want to save the model and wants to resume the training later:
Single GPU: Save:
state = {
'epoch': epoch,
'state_dict': model.state_dict(),
'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)
Load:
checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
Multiple GPU: Save
state = {
'epoch': epoch,
'state_dict': model.module.state_dict(),
'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)
Load:
checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']
#Don't call DataParallel before loading the model otherwise you will get an error
model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU
It's just one of those language design choices. On some level they are justified. They make it so you need to go pretty far out of your way to try and call the method, and if you really need it that badly, you must have a pretty good reason!
Debugging hooks and testing come to mind as possible applications, used responsibly of course.
I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in
CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake
(which can be set through an environment variable). So for example the boost configuration is in the path
CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake
In that configuration you can set variables. My config file for boost looks like that:
set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS})
set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )
Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.
Hope this this is helpful for other people.
There is no real way to do that in git. And if you won’t be making changes that affect both trees at once as a single work unit, there is no good reason to use a single repository for both. I thought I would miss this Subversion feature, but I found that creating repositories has so little administrative mental overhead (simply due to the fact that repositories are stored right next to their working copy, rather than requiring me to explicitly pick some place outside of the working copy) that I got used to just making lots of small single-purpose repositories.
If you insist (or really need it), though, you could make a git repository with just mytheme
and myplugins
directories and symlink those from within the WordPress install.
MDCore wrote:
making a commit to, e.g., mytheme will increment the revision number for myplugin
Note that this is not a concern for git, if you do decide to put both directories in a single repository, because git does away entirely with the concept of monotonically increasing revision numbers of any form.
The sole criterion for what things to put together in a single repository in git is whether it constitutes a single unit, ie. in your case whether there are changes where it does not make sense to look at the edits in each directory in isolation. If you have changes where you need to edit files in both directories at once and the edits belong together, they should be one repository. If not, then don’t glom them together.
Git really really wants you to use separate repositories for separate entities.
Submodules do not address the desire to keep both directories in one repository, because they would actually enforce having a separate repository for each directory, which are then brought together in another repository using submodules. Worse, since the directories inside the WordPress install are not direct subdirectories of the same directory and are also part of a hierarchy with many other files, using the per-directory repositories as submodules in a unified repository would offer no benefit whatsoever, because the unified repository would not reflect any use case/need.
Other way to get the minor version is:
SELECT extversion
FROM pg_catalog.pg_extension
WHERE extname='postgis'
This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).
If you want common functionality, you should build a library to be used in the two different controllers.
I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.
You can load into a string by adding true
at the end of the view call:
$string_view = $this->load->view('someview', array('data'=>'stuff'), true);
This is what I usually do to "vertical align" text inside labels:
label {
display: block;
float: left;
padding-top: 2px; /*This needs to be modified to fit */
}
It won't scale very nicely, but it works.
You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
//here is how to do it in Windows App.Config
public static bool ChangeConnectionString(string Name, string value, string providerName, string AppName)
{
bool retVal = false;
try
{
string FILE_NAME = string.Concat(Application.StartupPath, "\\", AppName.Trim(), ".exe.Config"); //the application configuration file name
XmlTextReader reader = new XmlTextReader(FILE_NAME);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
string nodeRoute = string.Concat("connectionStrings/add");
XmlNode cnnStr = null;
XmlElement root = doc.DocumentElement;
XmlNodeList Settings = root.SelectNodes(nodeRoute);
for (int i = 0; i < Settings.Count; i++)
{
cnnStr = Settings[i];
if (cnnStr.Attributes["name"].Value.Equals(Name))
break;
cnnStr = null;
}
cnnStr.Attributes["connectionString"].Value = value;
cnnStr.Attributes["providerName"].Value = providerName;
doc.Save(FILE_NAME);
retVal = true;
}
catch (Exception ex)
{
retVal = false;
//Handle the Exception as you like
}
return retVal;
}
Use git-diff
:
git diff -- yourfile
Just use in the CSS whatever you would use in a fill
attribute.
Of course, this requires that you have defined the linear gradient somewhere in your SVG.
Here is a complete example:
rect {_x000D_
cursor: pointer;_x000D_
shape-rendering: crispEdges;_x000D_
fill: url(#MyGradient);_x000D_
}
_x000D_
<svg width="100" height="50" version="1.1" xmlns="http://www.w3.org/2000/svg">_x000D_
<style type="text/css">_x000D_
rect{fill:url(#MyGradient)}_x000D_
</style>_x000D_
<defs>_x000D_
<linearGradient id="MyGradient">_x000D_
<stop offset="5%" stop-color="#F60" />_x000D_
<stop offset="95%" stop-color="#FF6" />_x000D_
</linearGradient>_x000D_
</defs>_x000D_
_x000D_
<rect width="100" height="50"/>_x000D_
</svg>
_x000D_
@Controller
is used to mark classes as Spring MVC Controller.@RestController
is a convenience annotation that does nothing more than adding the @Controller
and @ResponseBody
annotations (see: Javadoc)So the following two controller definitions should do the same
@Controller
@ResponseBody
public class MyController { }
@RestController
public class MyRestController { }
If all the above doesn't work, especially if having big size dependency (like my case), both building and loading were taking a minimum of 15 seconds, so it seems the delay gave a false message "Invalid hook call." So what you can do is give some time to ensure the build is completed before testing.
Your code won't work because you haven't assigned anything to n
before you first use it. Try this:
def oracle():
n = None
while n != 'Correct':
# etc...
A more readable approach is to move the test until later and use a break
:
def oracle():
guess = 50
while True:
print 'Current number = {0}'.format(guess)
n = raw_input("lower, higher or stop?: ")
if n == 'stop':
break
# etc...
Also input
in Python 2.x reads a line of input and then evaluates it. You want to use raw_input
.
Note: In Python 3.x, raw_input
has been renamed to input
and the old input
method no longer exists.
Add a maxlength
attribute to your input.
<input type="text" id="phone" name="phone" maxlength="10">
See this working example on JSFiddle.
I had same application on my localhost and on a shared server. On my localhost the redirects worked fine while on this shared server didn't. I checked the phpinfo and I saw what caused this:
While on my localhost I had this:
So I asked the system admin to increase that value and after he did that, everything worked fine.
Yes; copy the string to a char array, sort the char array, then copy that back into a string.
static string SortString(string input)
{
char[] characters = input.ToArray();
Array.Sort(characters);
return new string(characters);
}
Also you can use f-string formatting to write integer to file
For appending use following code, for writing once replace 'a' with 'w'.
for i in s_list:
with open('path_to_file','a') as file:
file.write(f'{i}\n')
file.close()
You have to use Promise to print or store values of element.
var ExpectedValue:string ="AllTestings.com";
element(by.id("xyz")).getAttribute("value").then(function (Text) {
expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
console.log("Text");//Print here in Console
});
Ok solved it.
Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting
In my app.js routing config:
$routeProvider.when('/pages/:name', {
templateUrl: '/pages/home.html',
controller: CMSController
});
Then in my CMS controller:
function CMSController($scope, $route, $routeParams) {
$route.current.templateUrl = '/pages/' + $routeParams.name + ".html";
$.get($route.current.templateUrl, function (data) {
$scope.$apply(function () {
$('#views').html($compile(data)($scope));
});
});
...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];
With #views being my <div id="views" ng-view></div>
So now it works with standard routing and dynamic routing.
To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio
into my browser and hey presto portfolio.html was displayed....
Updated Added $apply and $compile to the html so that dynamic content can be injected.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.
The C++ FAQ Lite covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup.
Excerpt:
[...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.
[...]
Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.
EDIT Corrected Most to All (thanks litb)
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss
formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
Here's how I do it when I need a database query's results in my batch file:
sqlplus -S schema/schema@db @query.sql> __query.tmp
set /p result=<__query.tmp
del __query.tmp
The key is in line 2: "set /p" sets the value of "result" to the value of the first line (only) in "__query.tmp" via the "<" redirection operator.
Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506
Undefined means a variable has been declared but has no value:
var var1;
alert(var1); //undefined
alert(typeof var1); //undefined
Null is an assignment:
var var2= null;
alert(var2); //null
alert(typeof var2); //object
If you want to iterate over both the keys and the values in a key sorted order, this form is quite succinct
let d = [
"A" : [1, 2],
"Z" : [3, 4],
"D" : [5, 6]
]
Swift 1,2:
for (k,v) in Array(d).sorted({$0.0 < $1.0}) {
println("\(k):\(v)")
}
Swift 3+:
for (k,v) in Array(d).sorted(by: {$0.0 < $1.0}) {
println("\(k):\(v)")
}
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
If you use MyISAM tables, then you can recover any data you deleted, just
open file: mysql/data/[your_db]/[your_table].MYD
with any text editor
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
I made this simple function
to achieve this:
void clearscreen() {
for(int i=0; i<10; i++) {
Serial.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
It works well for me in the default terminal
1.This will search XMLHelpers/XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers'))
2.This will search XMLHelpers.psm1 in current folder
Import-Module (Resolve-Path('XMLHelpers.psm1'))
The following article perhaps goes into some more detail as to which is a better choice; throw 'An error'
or throw new Error('An error')
:
http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/
It suggests that the latter (new Error()
) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.
Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.
Answer:
Use a Singleton if:
Do not use a Singleton if:
How to create the best singleton:
Regular expressions are very strong but expensive tool. It is valid to use them for checking if the first character is a digit but it is not so elegant :) I prefer this way:
public boolean isLeadingDigit(final String value){
final char c = value.charAt(0);
return (c >= '0' && c <= '9');
}
Postgresql > 8.4
SELECT
row_number() OVER (ORDER BY col1) AS i,
e.col1,
e.col2,
...
FROM ...
1.- Yes, but it pretty much refers to the whole memory used by your program.
2.- Yes see Java VM options
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
Ie
java -Xmx2g
assign 2 gigabytes of ram as maximum to your app
But you should see if you don't have a memory leak first.
3.- It depends on the program. Try spot memory leaks. This question would be to hard to answer. Lately you can profile using JConsole to try to find out where your memory is going to
A thread safe rotation function is the following (it works much better):
-(UIImage*)imageByRotatingImage:(UIImage*)initImage fromImageOrientation:(UIImageOrientation)orientation
{
CGImageRef imgRef = initImage.CGImage;
CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);
CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = orientation;
switch(orient) {
case UIImageOrientationUp: //EXIF = 1
return initImage;
break;
case UIImageOrientationUpMirrored: //EXIF = 2
transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
break;
case UIImageOrientationDown: //EXIF = 3
transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationDownMirrored: //EXIF = 4
transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
transform = CGAffineTransformScale(transform, 1.0, -1.0);
break;
case UIImageOrientationLeftMirrored: //EXIF = 5
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
transform = CGAffineTransformScale(transform, -1.0, 1.0);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationLeft: //EXIF = 6
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
break;
case UIImageOrientationRightMirrored: //EXIF = 7
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeScale(-1.0, 1.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
case UIImageOrientationRight: //EXIF = 8
boundHeight = bounds.size.height;
bounds.size.height = bounds.size.width;
bounds.size.width = boundHeight;
transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
transform = CGAffineTransformRotate(transform, M_PI / 2.0);
break;
default:
[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
}
// Create the bitmap context
CGContextRef context = NULL;
void * bitmapData;
int bitmapByteCount;
int bitmapBytesPerRow;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (bounds.size.width * 4);
bitmapByteCount = (bitmapBytesPerRow * bounds.size.height);
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
{
return nil;
}
// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
CGColorSpaceRef colorspace = CGImageGetColorSpace(imgRef);
context = CGBitmapContextCreate (bitmapData,bounds.size.width,bounds.size.height,8,bitmapBytesPerRow,
colorspace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);
if (context == NULL)
// error creating context
return nil;
CGContextScaleCTM(context, -1.0, -1.0);
CGContextTranslateCTM(context, -bounds.size.width, -bounds.size.height);
CGContextConcatCTM(context, transform);
// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(context, CGRectMake(0,0,width, height), imgRef);
CGImageRef imgRef2 = CGBitmapContextCreateImage(context);
CGContextRelease(context);
free(bitmapData);
UIImage * image = [UIImage imageWithCGImage:imgRef2 scale:initImage.scale orientation:UIImageOrientationUp];
CGImageRelease(imgRef2);
return image;
}
By far the best option nowadays would be using a maven container as a builder tool. A mvn.sh
script like this would be enough:
#!/bin/bash
docker run --rm -ti \
-v $(pwd):/opt/app \
-w /opt/app \
-e TERM=xterm \
-v $HOME/.m2:/root/.m2 \
maven mvn "$@"
Try using FLAG_ACTIVITY_CLEAR_TASK
I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.
With multiple return and multi parameter
string ConnectionString = CommonFunctions.GetConnectionString();
using (IDbConnection conn = new SqlConnection(ConnectionString))
{
IEnumerable<dynamic> results = conn.Query(sql: "ProductSearch",
param: new { CategoryID = 1, SubCategoryID="", PageNumber=1 },
commandType: CommandType.StoredProcedure);. // single result
var reader = conn.QueryMultiple("ProductSearch",
param: new { CategoryID = 1, SubCategoryID = "", PageNumber = 1 },
commandType: CommandType.StoredProcedure); // multiple result
var userdetails = reader.Read<dynamic>().ToList(); // instead of dynamic, you can use your objects
var salarydetails = reader.Read<dynamic>().ToList();
}
public static string GetConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
Alternatively to information_schema
it is possible to use pg_tables
:
select * from pg_tables where schemaname='public';
I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.
$(document).ready(function () {
jQuery.noConflict();
var Ammount = document.getElementById('Ammount');
$("#addtocart").click(function () {
if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
{
$('#myModal').modal();
$("#myModalLabelbronze").show();
$("#myModalLabelsilver").hide();
$("#myModalLabelgold").hide();
$("#myModalPbronze").show();
$("#myModalPSilver").hide();
$("#myModalPGold").hide();
}
}
});
I was having the exact same problem in Windows.
I noticed that in OP's gist, he uses string("open ")
in line 21, however, by using it one comes across this error:
'open' is not recognized as an internal or external command
After researching, I have found that open
is MacOS the default command to open things. It is different on Windows or Linux.
Linux: xdg-open <URL>
Windows: start <URL>
For those of you that are using Windows, as I am, you can use the following:
std::string op = std::string("start ").append(url);
system(op.c_str());
NODE USERS (REACT,EXPRESS) FOLLOW THESE STEPS
npm install base-64 --save
import { encode } from "base-64";
const response = await fetch(URL, {
method: 'post',
headers: new Headers({
'Authorization': 'Basic ' + encode(username + ":" + password),
'Content-Type': 'application/json'
}),
body: JSON.stringify({
"PassengerMobile": "xxxxxxxxxxxx",
"Password": "xxxxxxx"
})
});
const posts = await response.json();
Don't forget to define this whole function as async
I use Lodash for defensive coding reasons.
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
A "fully defensive" approach with Lodash would use both keys as well as get:
const firstKey = _.get(_.keys(ahash), 0);
Wrap them in an extra pair of parens and you're good to go.
if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}
Step by steps of that, +
turn value to a number and if you add to an empty array +[]
...as it's empty and is equal to 0
, it will
So from there, now look into your code, it's ++[[]][+[]]+[+[]]
...
And there is plus between them ++[[]][+[]]
+ [+[]]
So these [+[]]
will return [0]
as they have an empty array which gets converted to 0
inside the other array...
So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]]
will be equal to [[]][0]
which will return []
...
And at the end ++
convert it and increase it to 1
...
So you can imagine, 1
+ "0"
will be "10"
...
A more simple English explanation: jQuery is something that makes AJAX and other JavaScript tasks much easier.
The error seems to be thrown when you try and load they keystore from "C:/jakarta-tomcat/webapps/PlanB/Certs/my_pkcs12.p12" here:
ks.load( new FileInputStream(_privateKeyPath), _keyPass.toCharArray() );
Have you tried replaceing "/" with "\\" in your file path? If that doesn't help it probably has to do with Java's Unlimited Strength Jurisdiction Policy Files. You could check this by writing a little program that does AES encryption. Try encrypting with a 128 bit key, then if that works, try with a 256 bit key and see if it fails.
Code that does AES encyrption:
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Test
{
final String ALGORITHM = "AES"; //symmetric algorithm for data encryption
final String PADDING_MODE = "/CBC/PKCS5Padding"; //Padding for symmetric algorithm
final String CHAR_ENCODING = "UTF-8"; //character encoding
//final String CRYPTO_PROVIDER = "SunMSCAPI"; //provider for the crypto
int AES_KEY_SIZE = 256; //symmetric key size (128, 192, 256) if using 256 you must have the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files installed
private String doCrypto(String plainText) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException
{
byte[] dataToEncrypt = plainText.getBytes(CHAR_ENCODING);
//get the symmetric key generator
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(AES_KEY_SIZE); //set the key size
//generate the key
SecretKey skey = keyGen.generateKey();
//convert to binary
byte[] rawAesKey = skey.getEncoded();
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipher = Cipher.getInstance(ALGORITHM + PADDING_MODE);
//set it to encrypt mode, with the generated key
aesCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
//get the initialization vector being used (to be returned)
byte[] aesIV = aesCipher.getIV();
//encrypt the data
byte[] encryptedData = aesCipher.doFinal(dataToEncrypt);
//initialize the secret key with the appropriate algorithm
SecretKeySpec skeySpecDec = new SecretKeySpec(rawAesKey, ALGORITHM);
//get an instance of the symmetric cipher
Cipher aesCipherDec = Cipher.getInstance(ALGORITHM +PADDING_MODE);
//set it to decrypt mode with the AES key, and IV
aesCipherDec.init(Cipher.DECRYPT_MODE, skeySpecDec, new IvParameterSpec(aesIV));
//decrypt and return the data
byte[] decryptedData = aesCipherDec.doFinal(encryptedData);
return new String(decryptedData, CHAR_ENCODING);
}
public static void main(String[] args)
{
String text = "Lets encrypt me";
Test test = new Test();
try {
System.out.println(test.doCrypto(text));
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Does this code work for you?
You might also want to try specifying your bouncy castle provider in this line:
Cipher.getInstance(ALGORITHM +PADDING_MODE, "YOUR PROVIDER");
And see if it could be an error associated with bouncy castle.
As far as I know, you can't ask apt
for what their current sources are. However, you can do what you want using shell tools.
Getting a list of repositories:
grep -h ^deb /etc/apt/sources.list /etc/apt/sources.list.d/* >> current.repos.list
Applying the list:
apt-add-repository << current.repos.list
Regarding getting the repository from a package (installed or available), this will do the trick:
apt-cache policy package_name | grep -m1 http | awk '{ print $2 " " $3 }'
However, that will show you the repository of the latest version available of that package, and you may have more repositories for the same package with older versions. Remove all the grep/awk stuff if you want to see the full list.
You're missing __init__.py. From the Python tutorial:
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
Put an empty file named __init__.py in your Models directory, and all should be golden.
The size member function.
myList.size();
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
With minimum amount of built-in functions, assuming it's interview settings
array = [1, 2, 3, 4, 5, 6,7, 8]
inverse = [] #create container for inverse array
length = len(array) #to iterate later, returns 8
counter = length - 1 #because the 8th element is on position 7 (as python starts from 0)
for i in range(length):
inverse.append(array[counter])
counter -= 1
print(inverse)
Try using the Format
function:
Private Sub btncalc_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles btncalc.Click
txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) *
Val(txtF.Text) / Val(txtE.Text), "0.00")
txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub
Here's what I've been doing to cope with the situation.
I use global imports on a new test class.
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;
This allows you to code away without getting 'stuck' trying to find the correct package to import.
First, Identify the user you are logged in as:
select user();
select current_user();
The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost
in mysql.
Grant_priv
to root@localhost
. Here is how you can check.
mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host | user | password | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root | ***************************************** | N | Y |
| localhost | debian-sys-maint | ***************************************** | Y | Y |
| localhost | staging | ***************************************** | N | N |
+-----------+------------------+-------------------------------------------+------------+------------+
You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';
I logged back in, it was fine.
Try using pandoc
pandoc -f html -t docx -o output.docx input.html
If the input or output format is not specified explicitly, pandoc will attempt to guess it from the extensions of the input and output filenames.
— pandoc manual
So you can even use
pandoc -o output.docx input.html
I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
LANGUAGE plpgsql
AS $_$
DECLARE
old_parent INTEGER;
new_parent INTEGER;
id_nom INTEGER;
txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
IF TG_OP = 'INSERT' THEN
EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT $1.id,$1.id,0 UNION ALL
SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
ELSE
-- EXECUTE does not support conditional statements inside
EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
EXECUTE '
-- prevent cycles in the tree
UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
|| ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
|| TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
-- first remove edges between all old parents of node and its descendants
DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
(SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
AND ancestor_id IN
(SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
-- then add edges for all new parents ...
INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT child_id,ancestor_id,d_c+d_a FROM
(SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
CROSS JOIN
(SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
|| TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
END IF;
END IF;
RETURN NULL;
END;
$_$;
Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');
For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'TRUNCATE ' || tbl_closure || ';
INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
WITH RECURSIVE tree AS
(
SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
UNION ALL
SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
JOIN tree ON child_id = ' || fld_parent || '
)
SELECT * FROM tree;';
END;
$$;
Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;
In Java, you can use the library class sun.net.util.IPAddressUtil
:
IPAddressUtil.isIPv6LiteralAddress(iPaddress);
There is just a caveat that I discovered today.
If you have a function that is calling a plot a lot of times you better use plt.close(fig)
instead of fig.clf()
somehow the first does not accumulate in memory. In short if memory is a concern use plt.close(fig) (Although it seems that there are better ways, go to the end of this comment for relevant links).
So the the following script will produce an empty list:
for i in range(5):
fig = plot_figure()
plt.close(fig)
# This returns a list with all figure numbers available
print(plt.get_fignums())
Whereas this one will produce a list with five figures on it.
for i in range(5):
fig = plot_figure()
fig.clf()
# This returns a list with all figure numbers available
print(plt.get_fignums())
From the documentation above is not clear to me what is the difference between closing a figure and closing a window. Maybe that will clarify.
If you want to try a complete script there you have:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1000)
y = np.sin(x)
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
plt.close(fig)
print(plt.get_fignums())
for i in range(5):
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, y)
fig.clf()
print(plt.get_fignums())
If memory is a concern somebody already posted a work-around in SO see: Create a figure that is reference counted
You could take a different approach: define a constant string to represent your array and then split the string into an array when you need it, e.g.
const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');
This approach gives you a constant which can be stored in configuration and converted to an array when needed.
It's easy with rules:
CREATE RULE file_insert_defer AS ON INSERT TO file
WHERE (EXISTS ( SELECT * FROM file WHERE file.id = new.id)) DO INSTEAD NOTHING
But it fails with concurrent writes ...
I've read many answers to this question often stating to simply run makemigrations
in some other ways. But to me, the problem was in the Meta
subclass of models.
I have an app config that says label = <app name>
(in the apps.py
file, beside models.py
, views.py
etc). If by any chance your meta class doesn't have the same label as the app label (for instance because you are splitting one too big app into multiple ones), no changes are detected (and no helpful error message whatsoever). So in my model class I have now:
class ModelClassName(models.Model):
class Meta:
app_label = '<app name>' # <-- this label was wrong before.
field_name = models.FloatField()
...
Running Django 1.10 here.
I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL
formula, but (at least as of Excel 2003), it doesn't return the cell's color.
It would be pretty easy to implement with VBA:
Public Function myColor(r As Range) As Integer
myColor = r.Interior.ColorIndex
End Function
Then in the worksheet:
=mycolor(A1)
Wanted to use lombok's @ToString
but soon faced random compile errors on project rebuild in Intellij IDEA. Had to hit compile several times before incremental compilation could complete with success.
Tried both lombok 1.12.2 and 0.9.3 with Intellij IDEA 12.1.6 and 13.0 without any lombok plugin under jdk 1.6.0_39 and 1.6.0_45.
Had to manually copy generated methods from delomboked source and put lombok on hold until better times.
Update
The problem happens only with parallel compile enabled.
Filed an issue: https://github.com/rzwitserloot/lombok/issues/648
Update
mplushnikov commented on 30 Jan 2016:
Newer version of Intellij doesn't have such issues anymore. I think it can be closed here.
Update
I would highly recommend to switch from Java+Lombok to Kotlin if possible. As it has resolved from the ground up all Java issues that Lombok tries to work around.
As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.
However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.
The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:
ALTER USER xyz_user ACCOUNT UNLOCK;
However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:
ALTER USER xyz_user IDENTIFIED BY new_password;
Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.
EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.
REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY
REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE
REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'
REM Show the status of the account before reset.
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""
REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD
REM Select the old spare4 and password columns as delimited strings
SELECT
'''' || SPARE4 || '''' AS SPARE4HASH,
'''' || PASSWORD || '''' AS PWORDHASH
FROM
SYS.USER$
WHERE
NAME = '&USER_NAME';
REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD
REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older)
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;
REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer)
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;
REM Show the status of the account after reset
SELECT
ACCOUNT_STATUS,
TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
DBA_USERS
WHERE
USERNAME = '&USER_NAME';
Next lines you can find convertion from int[] -> List -> int[]
private static int[] convert(int[] arr) {
List<Integer> myList=new ArrayList<Integer>();
for(int number:arr){
myList.add(number);
}
}
int[] myArray=new int[myList.size()];
for(int i=0;i<myList.size();i++){
myArray[i]=myList.get(i);
}
return myArray;
}
Of course the answers above all do the job, but still i would like to use something like
gradle run path1 path2
well this can't be done, but what if we can:
gralde run --- path1 path2
If you think it is more elegant, then you can do it, the trick is to process the command line and modify it before gradle does, this can be done by using init scripts
The init script below:
So in your run task (or JavaExec, Exec) you can:
if (project.gradle.hasProperty("appArgs")) {
List<String> appArgs = project.gradle.appArgs;
args appArgs
}
The init script is:
import org.gradle.api.invocation.Gradle
Gradle aGradle = gradle
StartParameter startParameter = aGradle.startParameter
List tasks = startParameter.getTaskRequests();
List<String> appArgs = new ArrayList<>()
tasks.forEach {
List<String> args = it.getArgs();
Iterator<String> argsI = args.iterator();
while (argsI.hasNext()) {
String arg = argsI.next();
// remove '---' and all that follow
if (arg == "---") {
argsI.remove();
while (argsI.hasNext()) {
arg = argsI.next();
// and add it to appArgs
appArgs.add(arg);
argsI.remove();
}
}
}
}
aGradle.ext.appArgs = appArgs
Limitations:
If you don't like global init script, you can specify it in command line
gradle -I init.gradle run --- f:/temp/x.xml
Or better add an alias to your shell:
gradleapp run --- f:/temp/x.xml
For my case, it is solved by changing the properties of edmx file.
this solved the problem for me. The problem is, when the container try to find the meta data, it cant find it. so simply make it in the same assembly. this solution will not work if you have your edmx files in another assembly
An easier way to understand it, is what make code not thread-safe. There's two main issue that will make a threaded application to have unwanted behavior.
Accessing shared variable without locking
This variable could be modified by another thread while executing the function. You want to prevent it with a locking mechanism to be sure of the behavior of your function. General rule of thumb is to keep the lock for the shortest time possible.
Deadlock caused by mutual dependency on shared variable
If you have two shared variable A and B. In one function, you lock A first then later you lock B. In another function, you start locking B and after a while, you lock A. This is a potential deadlock where first function will wait for B to be unlocked when second function will wait for A to be unlocked. This issue will probably not occur in your development environment and only from time to time. To avoid it, all locks must always be in the same order.
FileCopy "1.mis", "1.txt"
I don't validate email address format anymore (Ok I check to make sure there is an at sign and a period after that). The reason for this is what says the correctly formatted address is even their email? You should be sending them an email and asking them to click a link or verify a code. This is the only real way to validate an email address is valid and that a person is actually able to recieve email.
Well one way to do it is set the height of your body to the height
that you want your page
to be. In this example I did 600px
.
Then set your wrapper
height to a percentage of the body here I did 70%
This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.
body {
padding-top: 70px;
border:1px solid black;
height:600px;
}
.mygrid-wrapper-div {
border: solid red 5px;
overflow: scroll;
height: 70%;
}
Update How about a jQuery approach.
$(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
$( window ).resize(function() {
var window_height = $(window).height(),
content_height = window_height - 200;
$('.mygrid-wrapper-div').height(content_height);
});
TypeScript uses getter/setter syntax that is like ActionScript3.
class foo {
private _bar: boolean = false;
get bar(): boolean {
return this._bar;
}
set bar(value: boolean) {
this._bar = value;
}
}
That will produce this JavaScript, using the ECMAScript 5 Object.defineProperty()
feature.
var foo = (function () {
function foo() {
this._bar = false;
}
Object.defineProperty(foo.prototype, "bar", {
get: function () {
return this._bar;
},
set: function (value) {
this._bar = value;
},
enumerable: true,
configurable: true
});
return foo;
})();
So to use it,
var myFoo = new foo();
if(myFoo.bar) { // calls the getter
myFoo.bar = false; // calls the setter and passes false
}
However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use --target
flag like this;
tsc --target ES5
If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that here:
As @DanFromGermany suggests below, if your are simply reading and writing a local property like foo.bar = true
, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.
You could use GCJ to compile your Java program into native code.
At some time they even compiled Eclipse into a native version.
This wikipedia article has an example in C.
A good example is that new modules written to augment the Apache Web server register with the main apache process by passing them function pointers so those functions are called back to process web page requests.
If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:
/**_x000D_
* Map over an ES6 Map._x000D_
*_x000D_
* @param {Map} map_x000D_
* @param {Function} cb Callback. Receives two arguments: key, value._x000D_
* @returns {Array}_x000D_
*/_x000D_
function mapMap(map, cb) {_x000D_
let out = new Array(map.size);_x000D_
let i = 0;_x000D_
map.forEach((val, key) => {_x000D_
out[i++] = cb(key, val);_x000D_
});_x000D_
return out;_x000D_
}_x000D_
_x000D_
let map = new Map([_x000D_
["a", 1],_x000D_
["b", 2],_x000D_
["c", 3]_x000D_
]);_x000D_
_x000D_
console.log(_x000D_
mapMap(map, (k, v) => `${k}-${v}`).join(', ')_x000D_
); // a-1, b-2, c-3
_x000D_
The best way to force the use of a number composed of digits only:
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
To allow number keys only:
isNaN(Number(event.key))
but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...
You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters.
For your case:
... LIKE '%[_]d'
Here's yet another way to convert 65 into A (via octal):
help printf # in Bash
man bash | less -Ip '^[[:blank:]]*printf'
printf "%d\n" '"A'
printf "%d\n" "'A"
printf '%b\n' "$(printf '\%03o' 65)"
To search in man bash
for \'
use (though futile in this case):
man bash | less -Ip "\\\'" # press <n> to go through the matches
Here's your solution :
Put Below code into your Xcode project and enjoy,
- (void)showMessage:(NSString*)message atPoint:(CGPoint)point {
const CGFloat fontSize = 16;
UILabel* label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont fontWithName:@"Helvetica-Bold" size:fontSize];
label.text = message;
label.textColor = UIColorFromRGB(0x07575B);
[label sizeToFit];
label.center = point;
[self.view addSubview:label];
[UIView animateWithDuration:0.3 delay:1 options:0 animations:^{
label.alpha = 0;
} completion:^(BOOL finished) {
label.hidden = YES;
[label removeFromSuperview];
}];
}
How to use ?
[self showMessage:@"Toast in iOS" atPoint:CGPointMake(160, 695)];
If someone is looking for installing Go 1.8 the follow this:
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt-get update
sudo apt-get install golang-go
And then install go
sudo apt-get install golang-1.8-go
This worked for me using excel 2010 and getting the same error when opening a macro-enabled .xlsm
file.
-after dismissing the error dialog, do "save as
" tab-delimited .txt
file. click OK
for
...only active sheet.
...functions not saved.
-then "save as
" again, but this time select macro-enabled .xlsm
format. (to another file or overwrite original doesn't matter, but save as another feels safer.)
-close out excel.
-open the newly saved .xlsm
file. In my cases, the error messages went away and the macros are working.
For me that function worked:
private static JSONObject concatJSONS(JSONObject json, JSONObject obj) {
JSONObject result = new JSONObject();
for(Object key: json.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, json.get(key));
}
for(Object key: obj.keySet()) {
System.out.println("adding " + key + " to result json");
result.put(key, obj.get(key));
}
return result;
}
(notice) - this implementation of concataion of json is for import org.json.simple.JSONObject;
Edit
gulp-util
is deprecated and should be avoid, so it's recommended to use minimist instead, which gulp-util
already used.
So I've changed some lines in my gulpfile to remove gulp-util
:
var argv = require('minimist')(process.argv.slice(2));
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (argv.theme || 'main') + '.scss'])
…
});
Original
In my project I use the following flag:
gulp styles --theme literature
Gulp offers an object gulp.env
for that. It's deprecated in newer versions, so you must use gulp-util for that. The tasks looks like this:
var util = require('gulp-util');
gulp.task('styles', function() {
return gulp.src(['src/styles/' + (util.env.theme ? util.env.theme : 'main') + '.scss'])
.pipe(compass({
config_file: './config.rb',
sass : 'src/styles',
css : 'dist/styles',
style : 'expanded'
}))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'ff 17', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(livereload(server))
.pipe(gulp.dest('dist/styles'))
.pipe(notify({ message: 'Styles task complete' }));
});
The environment setting is available during all subtasks. So I can use this flag on the watch task too:
gulp watch --theme literature
And my styles task also works.
Ciao Ralf
Another approach (more words, less code) that may help:
The locations of local maxima and minima are also the locations of the zero crossings of the first derivative. It is generally much easier to find zero crossings than it is to directly find local maxima and minima.
Unfortunately, the first derivative tends to "amplify" noise, so when significant noise is present in the original data, the first derivative is best used only after the original data has had some degree of smoothing applied.
Since smoothing is, in the simplest sense, a low pass filter, the smoothing is often best (well, most easily) done by using a convolution kernel, and "shaping" that kernel can provide a surprising amount of feature-preserving/enhancing capability. The process of finding an optimal kernel can be automated using a variety of means, but the best may be simple brute force (plenty fast for finding small kernels). A good kernel will (as intended) massively distort the original data, but it will NOT affect the location of the peaks/valleys of interest.
Fortunately, quite often a suitable kernel can be created via a simple SWAG ("educated guess"). The width of the smoothing kernel should be a little wider than the widest expected "interesting" peak in the original data, and its shape will resemble that peak (a single-scaled wavelet). For mean-preserving kernels (what any good smoothing filter should be) the sum of the kernel elements should be precisely equal to 1.00, and the kernel should be symmetric about its center (meaning it will have an odd number of elements.
Given an optimal smoothing kernel (or a small number of kernels optimized for different data content), the degree of smoothing becomes a scaling factor for (the "gain" of) the convolution kernel.
Determining the "correct" (optimal) degree of smoothing (convolution kernel gain) can even be automated: Compare the standard deviation of the first derivative data with the standard deviation of the smoothed data. How the ratio of the two standard deviations changes with changes in the degree of smoothing cam be used to predict effective smoothing values. A few manual data runs (that are truly representative) should be all that's needed.
All the prior solutions posted above compute the first derivative, but they don't treat it as a statistical measure, nor do the above solutions attempt to performing feature preserving/enhancing smoothing (to help subtle peaks "leap above" the noise).
Finally, the bad news: Finding "real" peaks becomes a royal pain when the noise also has features that look like real peaks (overlapping bandwidth). The next more-complex solution is generally to use a longer convolution kernel (a "wider kernel aperture") that takes into account the relationship between adjacent "real" peaks (such as minimum or maximum rates for peak occurrence), or to use multiple convolution passes using kernels having different widths (but only if it is faster: it is a fundamental mathematical truth that linear convolutions performed in sequence can always be convolved together into a single convolution). But it is often far easier to first find a sequence of useful kernels (of varying widths) and convolve them together than it is to directly find the final kernel in a single step.
Hopefully this provides enough info to let Google (and perhaps a good stats text) fill in the gaps. I really wish I had the time to provide a worked example, or a link to one. If anyone comes across one online, please post it here!
The two errors you have in your code are very different.
The first problem is that you're initializing and populating your Map
in the body of the class without a statement.
You can either have a static Map
and a static {//TODO manipulate Map}
statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.
The second problem is that you cannot treat a Map
syntactically like an array
, so the statement data["John"] = "Taxi Driver";
should be replaced by data.put("John", "Taxi Driver")
.
If you already have a "John" key in your HashMap
, its value will be replaced with "Taxi Driver".
stat's "%s" format gives you the actual number of bytes in a file.
find . -type f |
xargs stat --format=%s |
awk '{s+=$1} END {print s}'
Feel free to substitute your favourite method for summing numbers.
So the question is how can I check if my array already has a "horse" included so that I don't fill it with the same horse?
While the answers are concerned with looking through the array to see if a particular string or object exists, that's really going about it wrong, because, as the array gets larger, the search will take longer.
Instead, use either a Hash, or a Set. Both only allow a single instance of a particular element. Set will behave closer to an Array but only allows a single instance. This is a more preemptive approach which avoids duplication because of the nature of the container.
hash = {}
hash['a'] = nil
hash['b'] = nil
hash # => {"a"=>nil, "b"=>nil}
hash['a'] = nil
hash # => {"a"=>nil, "b"=>nil}
require 'set'
ary = [].to_set
ary << 'a'
ary << 'b'
ary # => #<Set: {"a", "b"}>
ary << 'a'
ary # => #<Set: {"a", "b"}>
Hash uses name/value pairs, which means the values won't be of any real use, but there seems to be a little bit of extra speed using a Hash, based on some tests.
require 'benchmark'
require 'set'
ALPHABET = ('a' .. 'z').to_a
N = 100_000
Benchmark.bm(5) do |x|
x.report('Hash') {
N.times {
h = {}
ALPHABET.each { |i|
h[i] = nil
}
}
}
x.report('Array') {
N.times {
a = Set.new
ALPHABET.each { |i|
a << i
}
}
}
end
Which outputs:
user system total real
Hash 8.140000 0.130000 8.270000 ( 8.279462)
Array 10.680000 0.120000 10.800000 ( 10.813385)
How about PlantUML? It's not for reverse engineering!!! It's for engineering before you code.
<!-- Method 1 -->
<!-- Copy dependency libraries jar files to a separated LIB folder -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<excludeTransitive>false</excludeTransitive>
<stripVersion>false</stripVersion>
</configuration>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Add LIB folder to classPath -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<!-- Method 2 -->
<!-- Package all libraries classes into one runnable jar -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
Set content type. Look at this method.
message.setContent("<h1>Hello</h1>", "text/html");
Of course you can, but why do this? You have to include a <script></script>
pair of tags that link to the jQuery web page, i.e.:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
. Then you will load the whole jQuery object just to use one single function, and because jQuery is a JavaScript library which will take time for the computer to upload, it will execute slower than just JavaScript.
Actually you can do it in interface builder.
You should set Title to "Attributed" and then choose center alignment.
You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).
So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND
, CREATE
, FLUSH PRIVILEGES
, etc.) into init file (any file).
Here is my example of recovering root account:
echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql
echo "FLUSH PRIVILEGES;" >> your_init_file.sql
and after you've created your file, you can run:
killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql
then to check if this worked, press Ctrl+Z and type: bg
to run the process from the foreground into the background, then verify your access by:
mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |
See also:
You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.
A simple example:
import difflib
cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
('afrykanerskojezycznym', 'afrykanerskojezyczny'),
('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
('abcdefg','xac')]
for a,b in cases:
print('{} => {}'.format(a,b))
for i,s in enumerate(difflib.ndiff(a, b)):
if s[0]==' ': continue
elif s[0]=='-':
print(u'Delete "{}" from position {}'.format(s[-1],i))
elif s[0]=='+':
print(u'Add "{}" to position {}'.format(s[-1],i))
print()
prints:
afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20
afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2
afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20
nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16
abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7
In short: It is not possible, and as it seems won't ever be supported (see here https://github.com/npm/npm/issues/775).
There are some hacky work-arrounds with using the CLI or ENV-Variables (see the current selected answer), .npmrc-Config-Files or npm link
- what they all have in common: They are never just project-specific, but always some kind of global
Solutions.
For me, none of those solutions are really clean because contributors to your project always need to create some special configuration or have some special knowledge - they can't just npm install
and it works.
So: Either you will have to put your package.json in the same directory where you want your node_modules installed, or live with the fact that they will always be in the root-dir of your project.
I had the same issue as i was using the 23.2.0 version of AppCompat Library. I updated the suppport library to 23.2.1 and the problem was solved.
This Issue of Toolbar has been resolved in 23.2.1
One way to do it is to check what mysql_num_rows
returns. A minimal complete example would be the following:
if ($result = mysql_query($sql) && mysql_num_rows($result) > 0) {
// there are results in $result
} else {
// no results
}
But it's recommended that you check the return value of mysql_query
and handle it properly in the case it's false
(which would be caused by an error); probably by also calling mysql_error
and logging the error somewhere.
When using Python 3 the empty lines can be avoid by using the codecs module. As stated in the documentation, files are opened in binary mode so no change of the newline kwarg is necessary. I was running into the same issue recently and that worked for me:
with codecs.open( csv_file, mode='w', encoding='utf-8') as out_csv:
csv_out_file = csv.DictWriter(out_csv)
So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:
GET /v2/_catalog
GET /v2/<name>/tags/list
Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):
$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}
Just check JSON option from the drop down next to binary; when you click raw. This should do
As answered by Magus :
the full path must me specified
Abstract states can be used to add a prefix to all child state urls. But note that abstract still needs a ui-view for its children to populate. To do so you can simply add it inline.
.state('app', {
url: "/app",
abstract: true,
template: '<ui-view/>'
})
For more information see documentation : https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views
Change this line:
if (typeof(T) == typeof(string))
For this line:
if (t.GetType() == typeof(string))
In C, int
, char
, long
, etc. are all integers.
They typically have different memory sizes and thus different ranges as in INT_MIN
to INT_MAX
. char
and arrays of char
are often used to store characters and strings. Integers are stored in many types: int
being the most popular for a balance of speed, size and range.
ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char
variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
To convert an int
to a char
, simple assign:
int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
This warning comes up because int
typically has a greater range than char
and so some loss-of-information may occur. By using the cast (char)
, the potential loss of info is explicitly directed.
To print the value of an integer:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
There are additional issues about printing such as using %hhu
or casting when printing an unsigned char
, but leave that for later. There is a lot to printf()
.
If you use bootstrap 4, you can hide element that way
className={this.state.hideElement ? "invisible" : "visible"}
The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe
:
C:\Program Files\Support Tools>setx /?
SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.
1) Command Line Mode: setx variable value [-m]
Optional Switches:
-m Set value in the Machine environment. Default is User.
...
For more information and example use: SETX -i
I think Windows 7 actually comes with setx
as part of a standard install.
In case someone stumbles in on this like I did, you can filter on multiple tags by adding a comma in between, like so:
adb logcat -s "browser","webkit"
System.exit(int i)
is to be used, but I would include it inside a more generic shutdown()
method, where you would include "cleanup" steps as well, closing socket connections, file descriptors, then exiting with System.exit(x)
.
I added a mMap.setOnMarkerClickListener(this);
in the onMapReady(GoogleMap googleMap)
method. So every time you click a marker it displays the text name in the toast method.
public class DemoMapActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
double lat=0.34924212701428;
double lng=32.616554024713;
String venue = "Capital Shoppers City";
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title(venue)).setTag(0);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(location);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(16);
mMap.moveCamera(cameraUpdate);
mMap.animateCamera(zoom);
mMap.setOnMarkerClickListener(this);
}
@Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked ",
Toast.LENGTH_SHORT).show();
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}
You can check this link for reference Markers
Word of warning: if you put config files in your WEB-INF/classes
folder, and your IDE, say Eclipse, does a clean/rebuild, it will nuke your conf files unless they were in the Java source directory. BalusC's great answer alludes to that in option 1 but I wanted to add emphasis.
I learned the hard way that if you "copy" a web project in Eclipse, it does a clean/rebuild from any source folders. In my case I had added a "linked source dir" from our POJO java library, it would compile to the WEB-INF/classes
folder. Doing a clean/rebuild in that project (not the web app project) caused the same problem.
I thought about putting my confs in the POJO src folder, but these confs are all for 3rd party libs (like Quartz or URLRewrite) that are in the WEB-INF/lib
folder, so that didn't make sense. I plan to test putting it in the web projects "src" folder when i get around to it, but that folder is currently empty and having conf files in it seems inelegant.
So I vote for putting conf files in WEB-INF/commonConfFolder/filename.properties
, next to the classes folder, which is Balus option 2.
Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name
<?php
$host="localhost";
$username="root";
$password="";
$dbname="your_database_name";
$con = new mysqli($host, $username, $password,$dbname);
$sql_data="select * from table_name";
$result_data=$con->query($sql_data);
$results=array();
filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while ($row = mysqli_fetch_assoc($result_data)) {
if (!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
?>
The easiest way would be:
String[] myArray = ...;
List<String> strs = Arrays.asList(myArray);
using the handy Arrays utility class. Note, that you can even do
List<String> strs = Arrays.asList("a", "b", "c");
I started using something like this:
kill $(pgrep 'python csp_build.py')
Simply do (mouseenter)
attribute in Angular2+...
In your HTML do:
<div (mouseenter)="mouseHover($event)">Hover!</div>
and in your component do:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'component',
templateUrl: './component.html',
styleUrls: ['./component.scss']
})
export class MyComponent implements OnInit {
mouseHover(e) {
console.log('hovered', e);
}
}
You can do something like this:
HTML:
<div class='div'>
<label>Something</label>
<input type='text' class='input'/>
<div>
CSS:
.div{
margin-bottom: 10px;
display: grid;
grid-template-columns: 1fr 4fr;
}
.input{
width: 50%;
}
Hope this helps ! :)
To set align text in dataGridCell you have two ways:
Set the align for a specific cell or set for each cell of row.
For one column go to Columns->DataGridViewCellStyle
or
For each column go to RowDefaultCellStyle
The control panel is the same as the follow:
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Firstly, just to check, you need to change into the directory you've created before running git init --bare
. Also, it's conventional to give bare repositories the extension .git
. So you can do
git init --bare test_repo.git
For Git versions < 1.8 you would do
mkdir test_repo.git
cd test_repo.git
git --bare init
To answer your later questions, bare repositories (by definition) don't have a working tree attached to them, so you can't easily add files to them as you would in a normal non-bare repository (e.g. with git add <file>
and a subsequent git commit
.)
You almost always update a bare repository by pushing to it (using git push
) from another repository.
Note that in this case you'll need to first allow people to push to your repository. When inside test_repo.git
, do
git config receive.denyCurrentBranch ignore
Community edit
git init --bare --shared=group
As commented by prasanthv, this is what you want if you are doing this at work, rather than for a private home project.
That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http
then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:
CFLAGS
rather than
CTAGS
- are you sure this is
correct? (What you have may be correct - this will depend on your build system!)LDFLAGS
If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx
etc) that was being executed?
From MSDN:
Key events occur in the following order:
Furthermore, KeyPress gives you a chance to declare the action as "handled" to prevent it from doing anything.