Similar to Howard's answer but a bit more efficient:
def my_func(low, up, leng):
step = ((up-low) * 1.0 / leng)
return [low+i*step for i in xrange(leng)]
with assuming below setting in .config file:
<configuration>
<appSettings>
<add key="PFUserName" value="myusername"/>
<add key="PFPassWord" value="mypassword"/>
</appSettings>
</configuration>
try this:
public class myController : Controller
{
NameValueCollection myKeys = ConfigurationManager.AppSettings;
public void MyMethod()
{
var myUsername = myKeys["PFUserName"];
var myPassword = myKeys["PFPassWord"];
}
}
Jacob Smullyan wrote a utility called pesterfish which uses effbot's ElementTree to convert XML to JSON.
The easiest way:
Step 1: Open AndroidManifest.xml file
Step 2: Locate android:theme="@style/AppTheme" >
Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >
Step 4: Then Add ImageView & Image
Step 4: That's it!
A "duplicate" question asked how to do this for a two-dimensional array, so this is a simple adaptation to answer that question. (The difference is only the six characters [2], 0
, which finds the third item in each subarray and passes an initial value of zero):
const twoDimensionalArray = [_x000D_
[10, 10, 1],_x000D_
[10, 10, 2],_x000D_
[10, 10, 3],_x000D_
];_x000D_
const sum = twoDimensionalArray.reduce( (partial_sum, a) => partial_sum + a[2], 0 ) ; _x000D_
console.log(sum); // 6
_x000D_
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
You just need to:
Step 1: Go home directory of C:\ with typing cd.. (2 times)
Step 2: It appears now C:\>
Step 3: Type dir Windows\System32\run
That's all, it shows complete files & folder details inside target folder.
Details: I used Windows\System32\com
folder as example, you should type your own folder name etc. Windows\System32\run
In MS-SQL Server 7+:
SELECT count(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'mytable'
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
You should really use Angular UI for that needs. Check it out: Angular UI Dialog
In a nutshell, with Angular UI dialog, you can pass variable from a controller to the dialog controller using resolve
. Here's your "from" controller:
var d = $dialog.dialog({
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '<url_of_your_template>',
controller: 'MyDialogCtrl',
// Interesting stuff here.
resolve: {
username: 'foo'
}
});
d.open();
And in your dialog controller:
angular.module('mymodule')
.controller('MyDialogCtrl', function ($scope, username) {
// Here, username is 'foo'
$scope.username = username;
}
EDIT: Since the new version of the ui-dialog, the resolve entry becomes:
resolve: { username: function () { return 'foo'; } }
I had same problem, for me npm install request --save
solved the problem. Hope it helps.
From here - Remember:
<input v-model="something">
is essentially the same as:
<input
v-bind:value="something"
v-on:input="something = $event.target.value"
>
or (shorthand syntax):
<input
:value="something"
@input="something = $event.target.value"
>
So v-model
is a two-way binding for form inputs. It combines v-bind
, which brings a js value into the markup, and v-on:input
to update the js value.
Use v-model
when you can. Use v-bind
/v-on
when you must :-) I hope your answer was accepted.
v-model
works with all the basic HTML input types (text, textarea, number, radio, checkbox, select). You can use v-model
with input type=date
if your model stores dates as ISO strings (yyyy-mm-dd). If you want to use date objects in your model (a good idea as soon as you're going to manipulate or format them), do this.
v-model
has some extra smarts that it's good to be aware of. If you're using an IME ( lots of mobile keyboards, or Chinese/Japanese/Korean ), v-model will not update until a word is complete (a space is entered or the user leaves the field). v-input
will fire much more frequently.
v-model
also has modifiers .lazy
, .trim
, .number
, covered in the doc.
The answers by Brandon and fatbotdesigns are both correct, but having implemented the Google docs preview, we found multiple .docx files that couldn't be handled by Google. Switched to the MS Office Online preview and works likes a charm.
My recommendation would be to use the MS Office Preview URL over Google's.
https://view.officeapps.live.com/op/embed.aspx?src=http://remote.url.tld/path/to/document.doc'
du -k /var/lib/postgresql/ |sort -n |tail
You can use the following code.
main()
{
int i = 0,j=0,count[26]={0};
char ch = 97;
char string[100]="Hello how are you buddy ?";
for (i = 0; i < 100; i++)
{
for(j=0;j<26;j++)
{
if (tolower(string[i]) == (ch+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",97+j,count[j]);
}
}
Hope this helps.
Using Java 8 or above you can use an Optional
and Java Streams.
So you can simply use the JdbcTemplate.queryForList()
method, create a Stream and use Stream.findFirst()
which will return the first value of the Stream or an empty Optional
:
public Optional<String> test() {
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
return jdbc.queryForList(sql, String.class)
.stream().findFirst();
}
To improve the performance of the query you can append LIMIT 1
to your query, so not more than 1 item is transferred from the database.
Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
string s;
string* _s = &s;
myfunc(_s);
should compile just fine.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.
With ruby:
ruby -e "File.write('output.txt', File.read('input.txt').encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: ''))"
Source: https://robots.thoughtbot.com/fight-back-utf-8-invalid-byte-sequences
Add the Below code in your CSS File to import Google Web Fonts.
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
Replace the Open+Sans parameter value with your Font name.
Your CSS file should look like:
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body{
font-family: 'Open Sans',serif;
}
not Error:
JSONObject json1 = getJsonX();
Error:
JSONObject json2 = null;
if(x == y)
json2 = getJSONX();
Error: Local variable statement defined in an enclosing scope must be final or effectively final.
But you can write:
JSONObject json2 = (x == y) ? json2 = getJSONX() : null;
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
I have uploaded the project you can directly open in eclipse and run that's all https://github.com/pareshmutha/XMLToJsonConverterUsingJAVA
Thank You
This message means that there are certain possible method calls which may fail at run-time. Suppose you have
class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}
The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.
This however can never fail and does not trigger the error
class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}
So no method may have more required parameters than its parent method.
The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:
class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}
as does this:
class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}
That seems more restrictive than it needs to be and I assume is due to internals.
Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.
While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam
, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.
@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) {
if( itemid.isPresent()){
Item i = itemDao.findOne(itemid.get());
return i;
} else ....
}
Without reading your code but just your scenario, I would solve by using localStorage
.
Here's an example, I'll use prompt()
for short.
On page1:
window.onload = function() {
var getInput = prompt("Hey type something here: ");
localStorage.setItem("storageName",getInput);
}
On page2:
window.onload = alert(localStorage.getItem("storageName"));
You can also use cookies but localStorage allows much more spaces, and they aren't sent back to servers when you request pages.
The direct answer to this question is:
if(rows.Any()) //prevent IndexOutOfRangeException for empty list
{
rows.RemoveAt(rows.Count - 1);
}
However... in the specific case of this question, it makes more sense not to add the row in the first place:
Row row = new Row();
//...
if (!row.cell[0].Equals("Something"))
{
rows.Add(row);
}
TBH, I'd go a step further by testing "Something"
against user.""
, and not even instantiating a Row
unless the condition is satisfied, but seeing as user.""
won't compile, I'll leave that as an exercise for the reader.
As a latest update to android in 2015, Google has included percent support library
com.android.support:percent:23.1.0
You can refer to this site for example of using it
https://github.com/JulienGenoud/android-percent-support-lib-sample
dependencies {
compile 'com.android.support:percent:22.2.0'
}
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:id="@+id/top_left"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:background="#ff44aacc"
app:layout_heightPercent="20%"
app:layout_widthPercent="70%" />
<View
android:id="@+id/top_right"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/top_left"
android:background="#ffe40000"
app:layout_heightPercent="20%"
app:layout_widthPercent="30%" />
<View
android:id="@+id/bottom"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/top_left"
android:background="#ff00ff22"
app:layout_heightPercent="80%" />
</android.support.percent.PercentRelativeLayout>
f = open('C:\\Users\\Pooja\\Desktop\\trolldata.csv')
Use '\\' for python program in Python version 3 and above.. Error will be resolved..
2016 Update
Use the Sharing Debugger to figure out what your problems are.
Make sure you're following the Facebook Sharing Best Practices.
Make sure you're using the Open Graph Markup correctly.
Original Answer
I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.
If you need to position an element relative to its containing element first you need to add position: relative
to the container element. The child element you want to position relatively to the parent has to have position: absolute
. The way that absolute positioning works is that it is done relative to the first relatively (or absolutely) positioned parent element. In case there is no relatively positioned parent, the element will be positioned relative to the root element (directly to the HTML element).
So if you want to position your child element to the top left of the parent container, you should do this:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
}
You will benefit greatly from reading this article. Hope this helps!
Encrypt:
openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey
Decrypt:
openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey
For details, see the openssl(1)
docs.
It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html
and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.
I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
pi = np.pi
# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
* np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
import xlwt
def output(filename, sheet, list1, list2, x, y, z):
book = xlwt.Workbook()
sh = book.add_sheet(sheet)
variables = [x, y, z]
x_desc = 'Display'
y_desc = 'Dominance'
z_desc = 'Test'
desc = [x_desc, y_desc, z_desc]
col1_name = 'Stimulus Time'
col2_name = 'Reaction Time'
#You may need to group the variables together
#for n, (v_desc, v) in enumerate(zip(desc, variables)):
for n, v_desc, v in enumerate(zip(desc, variables)):
sh.write(n, 0, v_desc)
sh.write(n, 1, v)
n+=1
sh.write(n, 0, col1_name)
sh.write(n, 1, col2_name)
for m, e1 in enumerate(list1, n+1):
sh.write(m, 0, e1)
for m, e2 in enumerate(list2, n+1):
sh.write(m, 1, e2)
book.save(filename)
for more explanation: https://github.com/python-excel
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
I'm afraid that WhatsApp for Android does not currently support to be called from a web browser.
I had the same requirement for my current project, and since I couldn't find any proper information I ended up downloading the APK file.
In Android, if an application wants to be called from a web browser, it needs to define an Activity with the category android.intent.category.BROWSABLE.
You can find more information about this here: https://developers.google.com/chrome/mobile/docs/intents
If you take a look to the WhatsApp AndroidManifest.xml file, the only Activiy with category BROWSABLE is this one:
<activity android:name="com.whatsapp.Conversation" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
<intent-filter>
<action android:name="android.intent.action.SENDTO" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="sms" />
<data android:scheme="smsto" />
</intent-filter>
</activity>
I've been playing with it for a while, and I couldn't make it to work. The most I got was to open the WhatsApp application from Chrome, but I couldn't figure out a way to set the message content and recipient.
Since it is not documented by the WhatsApp team, I think this is still work in progress. It looks like in the future WhatsApp will handle SMS too.
The only way to get more information is by reaching the WhatsApp dev team, what I tried, but I'm still waiting for a response.
Regards!
There is also a tool that oracle made called mysqlshow
If you run it with the --k keys $table_name
option it will display the keys.
SYNOPSIS
mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
· --keys, -k
Show table indexes.
example:
?-? mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(10) unsigned | | NO | PRI | | auto_increment | select,insert,update,references | |
| token | text | utf8mb4_unicode_ci | NO | | | | select,insert,update,references | |
| user_id | int(10) unsigned | | NO | MUL | | | select,insert,update,references | |
| expires_in | datetime | | YES | | | | select,insert,update,references | |
| created_at | timestamp | | YES | | | | select,insert,update,references | |
| updated_at | timestamp | | YES | | | | select,insert,update,references | |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0 | PRIMARY | 1 | id | A | 2 | | | | BTREE | | |
| tokens | 1 | tokens_user_id_foreign | 1 | user_id | A | 2 | | | | BTREE | | |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
Here is a solution for Docker in a script /bin/sh :
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "[client]" > /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "user=root" >> /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec echo "password=$MYSQL_ROOT_PASSWORD" >> /root/mysql-credentials.cnf'
docker exec [MYSQL_CONTAINER_NAME] sh -c 'exec mysqldump --defaults-extra-file=/root/mysql-credentials.cnf --all-databases'
Replace [MYSQL_CONTAINER_NAME] and be sure that the environment variable MYSQL_ROOT_PASSWORD is set in your container.
Hope it will help you like it could help me !
Use the mod rewrite with R=301 - where you use a incremental version number:
To achieve > css/ver/file.css => css/file.css?v=ver
RewriteRule ^css/([0-9]+)/file.css$ css/file.css?v=$1 [R=301,L,QSA]
so example, css/10/file.css => css/file.css?v=10
Same can be applied to js/ files. Increment ver to force update, 301 forces re-cache
I have tested this across Chrome, Firefox, Opera etc
PS: the ?v=ver is just for readability, this does not cause the refresh
# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]
I had the same issue. The other solutions here didn't work for me because I couldn't even see the Indigo / Helios update repos. The problem was that Eclipse was in Program Files, but I wasn't running it as an administrator.
Try redirecting the output like this:
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1
WITH PATHLIB MODULE (UPDATED ANSWER)
One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion>
and is much easier read and program with </opinion>
.
>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')
WITH OS MODULE
Use the os.path module:
>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr
'T:\Data\DBDesign'
You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path
. If not, you'll still probably need to use this module as the building block.
Here's a solution that moves the directives that need to be added dynamically, into the view and also adds some optional (basic) conditional-logic. This keeps the directive clean with no hard-coded logic.
The directive takes an array of objects, each object contains the name of the directive to be added and the value to pass to it (if any).
I was struggling to think of a use-case for a directive like this until I thought that it might be useful to add some conditional logic that only adds a directive based on some condition (though the answer below is still contrived). I added an optional if
property that should contain a bool value, expression or function (e.g. defined in your controller) that determines if the directive should be added or not.
I'm also using attrs.$attr.dynamicDirectives
to get the exact attribute declaration used to add the directive (e.g. data-dynamic-directive
, dynamic-directive
) without hard-coding string values to check for.
angular.module('plunker', ['ui.bootstrap'])_x000D_
.controller('DatepickerDemoCtrl', ['$scope',_x000D_
function($scope) {_x000D_
$scope.dt = function() {_x000D_
return new Date();_x000D_
};_x000D_
$scope.selects = [1, 2, 3, 4];_x000D_
$scope.el = 2;_x000D_
_x000D_
// For use with our dynamic-directive_x000D_
$scope.selectIsRequired = true;_x000D_
$scope.addTooltip = function() {_x000D_
return true;_x000D_
};_x000D_
}_x000D_
])_x000D_
.directive('dynamicDirectives', ['$compile',_x000D_
function($compile) {_x000D_
_x000D_
var addDirectiveToElement = function(scope, element, dir) {_x000D_
var propName;_x000D_
if (dir.if) {_x000D_
propName = Object.keys(dir)[1];_x000D_
var addDirective = scope.$eval(dir.if);_x000D_
if (addDirective) {_x000D_
element.attr(propName, dir[propName]);_x000D_
}_x000D_
} else { // No condition, just add directive_x000D_
propName = Object.keys(dir)[0];_x000D_
element.attr(propName, dir[propName]);_x000D_
}_x000D_
};_x000D_
_x000D_
var linker = function(scope, element, attrs) {_x000D_
var directives = scope.$eval(attrs.dynamicDirectives);_x000D_
_x000D_
if (!directives || !angular.isArray(directives)) {_x000D_
return $compile(element)(scope);_x000D_
}_x000D_
_x000D_
// Add all directives in the array_x000D_
angular.forEach(directives, function(dir){_x000D_
addDirectiveToElement(scope, element, dir);_x000D_
});_x000D_
_x000D_
// Remove attribute used to add this directive_x000D_
element.removeAttr(attrs.$attr.dynamicDirectives);_x000D_
// Compile element to run other directives_x000D_
$compile(element)(scope);_x000D_
};_x000D_
_x000D_
return {_x000D_
priority: 1001, // Run before other directives e.g. ng-repeat_x000D_
terminal: true, // Stop other directives running_x000D_
link: linker_x000D_
};_x000D_
}_x000D_
]);
_x000D_
<!doctype html>_x000D_
<html ng-app="plunker">_x000D_
_x000D_
<head>_x000D_
<script src="//code.angularjs.org/1.2.20/angular.js"></script>_x000D_
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>_x000D_
<script src="example.js"></script>_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div data-ng-controller="DatepickerDemoCtrl">_x000D_
_x000D_
<select data-ng-options="s for s in selects" data-ng-model="el" _x000D_
data-dynamic-directives="[_x000D_
{ 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },_x000D_
{ 'tooltip-placement' : 'bottom' },_x000D_
{ 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }_x000D_
]">_x000D_
<option value=""></option>_x000D_
</select>_x000D_
_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)
IF @AA> 0
BEGIN
SET @UserId = 0
END
ELSE
BEGIN
INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
SELECT SCOPE_IDENTITY()
END
END
When we have multiple projects in workspace, we have to set the references between the projects, not among the projects. If P1 references P2, P2 references P3, and P3 reference back to P1. That will cause a cycle.
The Solution is to draw a Diagram of the reference between projects in workspace. Check the Java Build Path of each of the projects to see the Tab of the Projects window. Take out the Project that are refering back to the main project, e.g. P3 references P1, in this example above.
Detailed operation is to select P3 project in RAD OR eclipse, right click on the project and choose the properties option, it brings up a new window for properties of P3. Click on the "Java Build Path" section, Choose the "Projects" option Tab. You can see the P3 has referenced P1 in the field. Select the P1 reference, click "Remove" button on the right side of the window. Then, click okay. The IDE will start to reset the path automatically.
Done.
Keep find all of the mis-referenced reference in every each projects until you have the right references to each of the projects in your Diagram. Good Luck!
select name, count(*) from DBS, TBLS
where DBS.DB_ID = TBLS.DB_ID
group by NAME into outfile '/tmp/QueryOut1.csv'
fields terminated by ',' lines terminated by '\n';
In IE 5.5+, you can use the contentWindow property:
iframe.height = iframe.contentWindow.document.scrollHeight;
In Netscape 6 (assuming firefox as well), contentDocument property:
iframe.height = iframe.contentDocument.scrollHeight
Check your php.ini, I'm using Apache2.2 + php 5.3. and I had the same problem and after modify the php.ini in order to set the libraries directory of PHP, it worked correctly. The problem is the default extension_dir
configuration value.
The default (and WRONG) value for my work enviroment is
; extension_dir="ext"
without any full path and commented with a semicolon.
There are two solution that worked fine for me.
1.- Including this line at php.ini file
extension_dir="X:/[PathToYourPHPDirectory]/ext
Where X: is your drive letter instalation (normally C: or D: )
2.- You can try to simply uncomment, deleting semicolon. Include the next line at php.ini file
extension_dir="ext"
Both ways worked fine for me but choose yours. Don't forget restart Apache before try again.
I hope this help you.
A little more elegant way of doing the same adding on to the above comment ..
<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
AutoGenerateColumns="false"
OnRowDeleting="deleteRow"
GridLines="Vertical">
<asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
<asp:BoundField DataField="EntityId" HeaderText="EntityId" />
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="lnkCustomize" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>' runat="server">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
And on the server side:
protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
string IdTemplate= e.Values["IdTemplate"].ToString();
string EntityId = e.Values["EntityId"].ToString();
// Do stuff..
}
As an addendum, if you want to reapply your changes on top of the remote, you can also try:
git pull --rebase origin master
If you then want to undo some of your changes (but perhaps not all of them) you can use:
git reset SHA_HASH
Then do some adjustment and recommit.
Pass multiple -v
arguments.
For instance:
docker -v /on/my/host/1:/on/the/container/1 \
-v /on/my/host/2:/on/the/container/2 \
...
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
System Preferences => Keyboard => Key Repeat Rate
Yes, check out the staticmethod decorator:
>>> class C:
... @staticmethod
... def hello():
... print "Hello World"
...
>>> C.hello()
Hello World
All of the responses so far take into account the non-standardized, but very common, X-Forwarded-For
header. There is a standardized Forwarded
header which is a little more difficult to parse out. Some examples are as follows:
Forwarded: for="_gazonk"
Forwarded: For="[2001:db8:cafe::17]:4711"
Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43
Forwarded: for=192.0.2.43, for=198.51.100.17
I have written a class that takes both of these headers into account when determining a client's IP address.
using System;
using System.Web;
namespace Util
{
public static class IP
{
public static string GetIPAddress()
{
return GetIPAddress(new HttpRequestWrapper(HttpContext.Current.Request));
}
internal static string GetIPAddress(HttpRequestBase request)
{
// handle standardized 'Forwarded' header
string forwarded = request.Headers["Forwarded"];
if (!String.IsNullOrEmpty(forwarded))
{
foreach (string segment in forwarded.Split(',')[0].Split(';'))
{
string[] pair = segment.Trim().Split('=');
if (pair.Length == 2 && pair[0].Equals("for", StringComparison.OrdinalIgnoreCase))
{
string ip = pair[1].Trim('"');
// IPv6 addresses are always enclosed in square brackets
int left = ip.IndexOf('['), right = ip.IndexOf(']');
if (left == 0 && right > 0)
{
return ip.Substring(1, right - 1);
}
// strip port of IPv4 addresses
int colon = ip.IndexOf(':');
if (colon != -1)
{
return ip.Substring(0, colon);
}
// this will return IPv4, "unknown", and obfuscated addresses
return ip;
}
}
}
// handle non-standardized 'X-Forwarded-For' header
string xForwardedFor = request.Headers["X-Forwarded-For"];
if (!String.IsNullOrEmpty(xForwardedFor))
{
return xForwardedFor.Split(',')[0];
}
return request.UserHostAddress;
}
}
}
Below are some unit tests that I used to validate my solution:
using System.Collections.Specialized;
using System.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UtilTests
{
[TestClass]
public class IPTests
{
[TestMethod]
public void TestForwardedObfuscated()
{
var request = new HttpRequestMock("for=\"_gazonk\"");
Assert.AreEqual("_gazonk", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv6()
{
var request = new HttpRequestMock("For=\"[2001:db8:cafe::17]:4711\"");
Assert.AreEqual("2001:db8:cafe::17", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv4()
{
var request = new HttpRequestMock("for=192.0.2.60;proto=http;by=203.0.113.43");
Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedIPv4WithPort()
{
var request = new HttpRequestMock("for=192.0.2.60:443;proto=http;by=203.0.113.43");
Assert.AreEqual("192.0.2.60", Util.IP.GetIPAddress(request));
}
[TestMethod]
public void TestForwardedMultiple()
{
var request = new HttpRequestMock("for=192.0.2.43, for=198.51.100.17");
Assert.AreEqual("192.0.2.43", Util.IP.GetIPAddress(request));
}
}
public class HttpRequestMock : HttpRequestBase
{
private NameValueCollection headers = new NameValueCollection();
public HttpRequestMock(string forwarded)
{
headers["Forwarded"] = forwarded;
}
public override NameValueCollection Headers
{
get { return this.headers; }
}
}
}
Sometimes the execution runs first time, and when we do maven clean install it doesn't generate after that. The issue was using true for skipMain and skip properties under maven-compiler-plugin of the main pom File. Remove them if they were introduced as a part of any issue or suggestion.
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
The reason csv
doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip()
on them to transpose them after.
>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)]
>>> zip(*l)
[('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)]
how about this solution?
if type(x) in (float, int):
# do whatever
else:
# do whatever
Exactly like in JavaScript, you can use the parseInt
or parseFloat
functions, or simply use the unary +
operator:
var x = "32";
var y: number = +x;
All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123"
, but will behave differently for various other, possibly expected, cases (like "123.45"
) and corner cases (like null
).
Table taken from this answer
Best way is to use Joda-Time, the highly successful open-source library you would add to your project.
String date1 = "2015-11-11";
String date2 = "2013-11-11";
DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
long diffInMillis = d2.getMillis() - d1.getMillis();
Duration duration = new Duration(d1, d2);
int days = duration.getStandardDays();
int hours = duration.getStandardHours();
int minutes = duration.getStandardMinutes();
If you're using Android Studio, very easy to add joda-time. In your build.gradle (app):
dependencies {
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.2'
}
A slightly different solution is to use the special variable ansible_limit
which is the contents of the --limit
CLI option for the current execution of Ansible.
- hosts: "{{ ansible_limit | default(omit) }}"
No need to define an extra variable here, just run the playbook with the --limit
flag.
ansible-playbook --limit imac-2.local user.yml
In Visual Studio:
Run a bash command with the following format:
find /path -type f -exec ls -l \{\} \;
Based on reading several Stackoverflow questions and answers on squashing, I think this is a good one liner to squash all commits on a branch:
git reset --soft $(git merge-base master YOUR_BRANCH) && git commit -am "YOUR COMMIT MESSAGE" && git rebase -i master
This is assuming master is the base branch.
The best way to do this is to p/invoke WNetUseConnection.
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
There is something fundamentally wrong with what you're trying to do. Binary floating-points values do not have decimal places. You cannot meaningfully round one to a given number of decimal places, because most "round" decimal values simply cannot be represented as a binary fraction. Which is why one should never use float
or double
to represent money.
So if you want decimal places in your result, that result must either be a String
(which you already got with the DecimalFormat
), or a BigDecimal
(which has a setScale()
method that does exactly what you want). Otherwise, the result cannot be what you want it to be.
Read The Floating-Point Guide for more information.
You must check if result returned by mysql_query is false.
$r = mysql_qyery("...");
if ($r) {
mysql_fetch_assoc($r);
}
You can use @mysql_fetch_assoc($r)
to avoid error displaying.
If you are in an interactive environment like Jupyter
or ipython
you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset
and reset_selective
is vailable on interactive python sessions like ipython
and Jupyter
1) reset
reset
Resets the namespace by removing all names defined by the user, if called without arguments.
in
and the out
parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist
parameter.
reset in out
Another interesting one is array
that only removes numpy Arrays:
reset array
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
Set the name
attribute of your form to "theForm"
and your code will work.
This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X>
can not be cast in List<Y>
, but List<X>
can be cast into IEnumerable<Y>
, and even with implicit cast.
Example:
List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error
but
List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY; // No issue
The big advantage is that it does not create a new list in memory.
There are already nice solution has been given. The below code can help others to query over datatable and get the value of each row of the datatable for the ImagePath column.
for (int i = 0; i < dataTable.Rows.Count; i++)
{
var theUrl = dataTable.Rows[i]["ImagePath"].ToString();
}
Storyboard doesn't work for me all the time even after trying all the solution here
So it is always perfect answer is using the code, Just create IBOutlet instance of the UIView and add the properties
Short answer :
layer.cornerRadius = 10
layer.borderWidth = 1
layer.borderColor = UIColor.blue.cgColor
Long answer :
customUIView.layer.cornerRadius = 10
pcustomUIView.layer.borderWidth = 2
customUIView.layer.borderColor = UIColor.blue.cgColor
I was able to undo another user's checkout with the following command:
tf undo {file path} /workspace:{workspace};{username}
You'll need to wrap that semicolon in double-quotes if you're running the command from PowerShell. We're running TFS 2010 (and VS 2010).
Disclaimer: I got this from the FCI-H blog at http://fci-h.blogspot.com/2011/01/how-to-force-undo-checkout-tfs.html
A very good solution to this can be found here:
Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs,
self.s.read(i)
returns an empty string and you might want to throw an exception to indicate the timeout.
It is also supposed to be fast according to the author:
The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)
while True:
print(rl.readline())
This can now be solved using flexbox
:
HTML
<form>
<h1>My Form</h1>
<label for="text">Input:</label>
<input type="text" name="text" id="text"/>
<!-- Put the elements in reverse order -->
<div class="form-actions">
<button>Ok</button> <!-- our default action is first -->
<button>Cancel</button>
</div>
</form>
CSS
.form-actions {
display: flex;
flex-direction: row-reverse; /* reverse the elements inside */
}
Explaination
Using flex box, we can reverse the order of the elements in a container that uses display: flex
by also using the CSS rule: flex-direction: row-reverse
. This requires no CSS or hidden elements. For older browsers that do not support flexbox, they still get a workable solution but the elements will not be reversed.
If you're developing for Android there is TextUtils class which may help you:
import android.text.TextUtils;
It is really helps a lot to check equality of Strings.
For example if you need to check Strings s1, s2 equality (which may be nulls) you may use instead of
if( (s1 != null && !s1.equals(s2)) || (s1 == null && s2 != null) )
{ ... }
this simple method:
if( !TextUtils.equals(s1, s2) )
{ ... }
As for initial question - for replacement it's easier to use s1.replace().
By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1. Therefore, you should handle it.
#include <iostream>
using namespace std;
int Fibonacci(int);
int main(void) {
int number;
cout << "Please enter a positive integer: ";
cin >> number;
if (number < 0)
cout << "That is not a positive integer.\n";
else
cout << number << " Fibonacci is: " << Fibonacci(number) << endl;
}
int Fibonacci(int x)
{
if (x < 2){
return x;
}
return (Fibonacci (x - 1) + Fibonacci (x - 2));
}
An efficient code in C++ that works for any angle and in both: radians and degrees is:
inline double getAbsoluteDiff2Angles(const double x, const double y, const double c)
{
// c can be PI (for radians) or 180.0 (for degrees);
return c - fabs(fmod(fabs(x - y), 2*c) - c);
}
See the "AWS CLI Command Reference" for more information.
AWS recently released their Command Line Tools, which work much like boto and can be installed using
sudo easy_install awscli
or
sudo pip install awscli
Once installed, you can then simply run:
aws s3 sync s3://<source_bucket> <local_destination>
For example:
aws s3 sync s3://mybucket .
will download all the objects in mybucket
to the current directory.
And will output:
download: s3://mybucket/test.txt to test.txt
download: s3://mybucket/test2.txt to test2.txt
This will download all of your files using a one-way sync. It will not delete any existing files in your current directory unless you specify --delete
, and it won't change or delete any files on S3.
You can also do S3 bucket to S3 bucket, or local to S3 bucket sync.
Check out the documentation and other examples.
Whereas the above example is how to download a full bucket, you can also download a folder recursively by performing
aws s3 cp s3://BUCKETNAME/PATH/TO/FOLDER LocalFolderName --recursive
This will instruct the CLI to download all files and folder keys recursively within the PATH/TO/FOLDER
directory within the BUCKETNAME
bucket.
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
Another simple example using ImageView to toggle visibility with less code, because of single InputType assign we need only equality operator:
EditText inputPassword = (EditText) findViewById(R.id.loginPassword);
ImageView inputPasswordShow = (ImageView) findViewById(R.id.imagePasswordShow);
inputPasswordShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(inputPassword.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
inputPassword.setInputType( InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else {
inputPassword.setInputType( InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD );
}
inputPassword.setSelection(inputPassword.getText().length());
}
});
Replacing :
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
With :
InputType.TYPE_CLASS_TEXT
Will give the same result but shorter word.
MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL team could just incorporate it into their codebase.
People are seeing real world MongoDB performance largely because MongoDB allows you to query in a different manner that is more sensible to your workload.
For example, consider a design that persisted a lot of information about a complicated entity in a normalised fashion. This could easily use dozens of tables in MySQL (or any relational db) to store the data in normal form, with many indexes needed to ensure relational integrity between tables.
Now consider the same design with a document store. If all of those related tables are subordinate to the main table (and they often are), then you might be able to model the data such that the entire entity is stored in a single document. In MongoDB you can store this as a single document, in a single collection. This is where MongoDB starts enabling superior performance.
In MongoDB, to retrieve the whole entity, you have to perform:
So a b-tree lookup, and a binary page read. Log(n) + 1 IOs. If the indexes can reside entirely in memory, then 1 IO.
In MySQL with 20 tables, you have to perform:
So the total for mysql, even assuming that all indexes are in memory (which is harder since there are 20 times more of them) is about 20 range lookups.
These range lookups are likely comprised of random IO — different tables will definitely reside in different spots on disk, and it's possible that different rows in the same range in the same table for an entity might not be contiguous (depending on how the entity has been updated, etc).
So for this example, the final tally is about 20 times more IO with MySQL per logical access, compared to MongoDB.
This is how MongoDB can boost performance in some use cases.
Check the php.ini
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
ini_set('max_execution_time', 0); //0=NOLIMIT
The minute you add a resource .RESX file to your project, Visual Studio will create a Designer.cs with the same name, creating a a class for you with all the items of the resource as static properties. You can see all the names of the resource when you type the dot in the editor after you type the name of the resource file.
Alternatively, you can use reflection to loop through these names.
Type resourceType = Type.GetType("AssemblyName.Resource1");
PropertyInfo[] resourceProps = resourceType.GetProperties(
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.GetProperty);
foreach (PropertyInfo info in resourceProps)
{
string name = info.Name;
object value = info.GetValue(null, null); // object can be an image, a string whatever
// do something with name and value
}
This method is obviously only usable when the RESX file is in scope of the current assembly or project. Otherwise, use the method provided by "pulse".
The advantage of this method is that you call the actual properties that have been provided for you, taking into account any localization if you wish. However, it is rather redundant, as normally you should use the type safe direct method of calling the properties of your resources.
When you are not sure of the number of rows, then you can do it this way:
followers_df.index = range(len(followers_df))
You can also use this free plug-and-play extension:
http://www.magentocommerce.com/magento-connect/manage-customer-account-menu.html
This extension does not touch any of the Magento core files.
With this extension you are able to:
tl;dr
cp -R "/src/project 1/App" "/src/project 2"
Explanation:
Using quotes will cater for spaces in the directory names
cp -R "/src/project 1/App" "/src/project 2"
If the App directory is specified in the destination directory:
cp -R "/src/project 1/App" "/src/project 2/App"
and "/src/project 2/App" already exists the result will be "/src/project 2/App/App"
Best not to specify the directory copied in the destination so that the command can be repeated over and over with the expected result.
Inside a bash script:
cp -R "${1}/App" "${2}"
There's a module for that: https://www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
To fix title label's spacing to the button, set titleEdgeInsets and other properties before setTitle:
let set = UIButton()
sut.titleLabel?.lineBreakMode = .byWordWrapping
sut.titleLabel?.numberOfLines = 0
sut.titleEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 20, right: 20)
sut.setTitle("Dummy button with long long long long long long long long title", for: .normal)
P.S. I tested setting titleLabel?.textAlignment is not necessary and the title aligns in .natural
.
8080 - JMX (remote)
8888 - Remote debugger (removed in 0.6.0)
7000 - Used internal by Cassandra
(7001 - Obsolete, removed in 0.6.0. Used for membership communication, aka gossip)
9160 - Thrift client API
Cassandra FAQ What ports does Cassandra use?
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
Try this in angular 8.0:
@ViewChild('result',{static: false}) resultElement: ElementRef;
You could better use the localStorage of the web browser.
You can find a reference here
Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).
javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456
Then load the properties to your environment from your code. This makes your application configurable.
FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
by installing AspNetMVC4Setup.exe ( Here is the link :https://www.microsoft.com/en-us/download/details.aspx?id=30683) solves the issue.
by restart/reinstalling Microsoft.AspNet.Mvc Package doesn't help me.
This works - https://stackoverflow.com/a/5437720/10219008.....but if you run into an issue 'Error Code: 1265. Data truncated for column 'id' at row 1'...Then run the following. Adding ignore on the update query.
SET @count = 0;
set sql_mode = 'STRICT_ALL_TABLES';
UPDATE IGNORE web_keyword SET id = @count := (@count+1);
You can use these functions to brutally remove everything Docker related:
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() {
removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
You can add those to your ~/Xrc
file, where X is your shell interpreter (~/.bashrc
if you're using bash) file and reload them via executing source ~/Xrc
. Also, you can just copy paste them to the console and afterwards (regardless the option you took before to get the functions ready) just run:
armageddon
It's also useful for just general Docker clean up. Have in mind that this will also remove your images, not only your containers (either running or not) and your volumes of any kind.
Just pass it as an argument of findAll
:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]
You can use HttpServletRequest.getScheme()
to retrieve either "http" or "https".
Using it along with HttpServletRequest.getServerName()
should be enough to rebuild the portion of the URL you need.
You don't need to explicitly put the port in the URL if you're using the standard ones (80 for http and 443 for https).
Edit: If your servlet container is behind a reverse proxy or load balancer that terminates the SSL, it's a bit trickier because the requests are forwarded to the servlet container as plain http. You have a few options:
1) Use HttpServletRequest.getHeader("x-forwarded-proto")
instead; this only works if your load balancer sets the header correctly (Apache should afaik).
2) Configure a RemoteIpValve in JBoss/Tomcat that will make getScheme()
work as expected. Again, this will only work if the load balancer sets the correct headers.
3) If the above don't work, you could configure two different connectors in Tomcat/JBoss, one for http and one for https, as described in this article.
The guide to getting fired: How to abuse function pointers in GCC on x86 machines by compiling your code by hand:
These string literals are bytes of 32-bit x86 machine code. 0xC3
is an x86 ret
instruction.
You wouldn't normally write these by hand, you'd write in assembly language and then use an assembler like nasm
to assemble it into a flat binary which you hexdump into a C string literal.
Returns the current value on the EAX register
int eax = ((int(*)())("\xc3 <- This returns the value of the EAX register"))();
Write a swap function
int a = 10, b = 20;
((void(*)(int*,int*))"\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b")(&a,&b);
Write a for-loop counter to 1000, calling some function each time
((int(*)())"\x66\x31\xc0\x8b\x5c\x24\x04\x66\x40\x50\xff\xd3\x58\x66\x3d\xe8\x03\x75\xf4\xc3")(&function); // calls function with 1->1000
You can even write a recursive function that counts to 100
const char* lol = "\x8b\x5c\x24\x4\x3d\xe8\x3\x0\x0\x7e\x2\x31\xc0\x83\xf8\x64\x7d\x6\x40\x53\xff\xd3\x5b\xc3\xc3 <- Recursively calls the function at address lol.";
i = ((int(*)())(lol))(lol);
Note that compilers place string literals in the .rodata
section (or .rdata
on Windows), which is linked as part of the text segment (along with code for functions).
The text segment has Read+Exec permission, so casting string literals to function pointers works without needing mprotect()
or VirtualProtect()
system calls like you'd need for dynamically allocated memory. (Or gcc -z execstack
links the program with stack + data segment + heap executable, as a quick hack.)
To disassemble these, you can compile this to put a label on the bytes, and use a disassembler.
// at global scope
const char swap[] = "\x8b\x44\x24\x04\x8b\x5c\x24\x08\x8b\x00\x8b\x1b\x31\xc3\x31\xd8\x31\xc3\x8b\x4c\x24\x04\x89\x01\x8b\x4c\x24\x08\x89\x19\xc3 <- This swaps the values of a and b";
Compiling with gcc -c -m32 foo.c
and disassembling with objdump -D -rwC -Mintel
, we can get the assembly, and find out that this code violates the ABI by clobbering EBX (a call-preserved register) and is generally inefficient.
00000000 <swap>:
0: 8b 44 24 04 mov eax,DWORD PTR [esp+0x4] # load int *a arg from the stack
4: 8b 5c 24 08 mov ebx,DWORD PTR [esp+0x8] # ebx = b
8: 8b 00 mov eax,DWORD PTR [eax] # dereference: eax = *a
a: 8b 1b mov ebx,DWORD PTR [ebx]
c: 31 c3 xor ebx,eax # pointless xor-swap
e: 31 d8 xor eax,ebx # instead of just storing with opposite registers
10: 31 c3 xor ebx,eax
12: 8b 4c 24 04 mov ecx,DWORD PTR [esp+0x4] # reload a from the stack
16: 89 01 mov DWORD PTR [ecx],eax # store to *a
18: 8b 4c 24 08 mov ecx,DWORD PTR [esp+0x8]
1c: 89 19 mov DWORD PTR [ecx],ebx
1e: c3 ret
not shown: the later bytes are ASCII text documentation
they're not executed by the CPU because the ret instruction sends execution back to the caller
This machine code will (probably) work in 32-bit code on Windows, Linux, OS X, and so on: the default calling conventions on all those OSes pass args on the stack instead of more efficiently in registers. But EBX is call-preserved in all the normal calling conventions, so using it as a scratch register without saving/restoring it can easily make the caller crash.
This also happened to me when a PercentageRelativeLayout https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html was used and the build was targeting Android 0 = 26. PercentageRelativeLayout layout is obsolete starting from Android O and obviously sometime was changed in the resource generation. Replacing the layout with a ConstraintLayout or just a RelativeLayout solved it.
if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
{
// code when element is disabled
}
git config --global core.editor notepad.exe
Hit Ctrl+S to save your commit message. To discard, just close the notepad window without saving.
In case you hit the shortcut for save, then decide to abort, go to File->Save as, and in the dialog that opens, change "Save as type" to "All files (*.*)". You will see a file named "COMMIT_EDITMSG". Delete it, and close notepad window.
Edit: Alternatively, and more easily, delete all the contents from the open notepad window and hit save. (thanks mwfearnley for the comment!)
I think for small write-ups such as commit messages notepad serves best, because it is simple, is there with windows, opens up in no time. Even your sublime may take a second or two to get fired up when you have a load of plugins and stuff.
That would be to make it difficult for a third-party to insert the JSON response into an HTML document with the <script>
tag. Remember that the <script>
tag is exempt from the Same Origin Policy.
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**_x000D_
* PT1H30M -> 0130_x000D_
* @param {ISO String} isoString_x000D_
* @return {string} absolute 4 digit number HH:mm_x000D_
*/_x000D_
_x000D_
const parseIsoToAbsolute = (isoString) => {_x000D_
_x000D_
const durations = moment.duration(isoString).as('seconds');_x000D_
const momentInSeconds = moment.duration(durations, 'seconds');_x000D_
_x000D_
let hours = momentInSeconds.asHours().toString().length < 2_x000D_
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();_x000D_
_x000D_
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);_x000D_
_x000D_
const minutes = momentInSeconds.minutes().toString().length < 2_x000D_
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();_x000D_
_x000D_
const absolute = hours + minutes;_x000D_
return absolute;_x000D_
};_x000D_
_x000D_
console.log(parseIsoToAbsolute('PT1H30M'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
If you like to keep it fixed width, for example 10 digits, do it like this
Key = i.ToString("0000000000");
Replace with as many digits as you like.
i = 123
will then result in Key = "0000000123"
.
When non of the above works, and still mails looks like ª הודפסה ×•× ×©×œ
:
$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->Subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';;
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
Check out DateTime.Compare method
You need to wrap the text in a div
element and include the absolutely positioned element inside of it.
<div class="container">
<div class="inner">
<div class="full-height"></div>
[Your text here]
</div>
</div>
Css:
.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }
Setting the inner div's position to relative
makes the absolutely position elements inside of it base their position and height on it rather than on the .container
div, which has a fixed height. Without the inner, relatively positioned div
, the .full-height
div will always calculate its dimensions and position based on .container
.
* {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
position: relative;_x000D_
border: solid 1px red;_x000D_
height: 256px;_x000D_
width: 256px;_x000D_
overflow: auto;_x000D_
float: left;_x000D_
margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 128px;_x000D_
bottom: 0;_x000D_
height: 100%;_x000D_
background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
<div class="inner">_x000D_
<div class="full-height">_x000D_
</div>_x000D_
_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
quidem._x000D_
</div>_x000D_
</div>
_x000D_
Compiler knows by type cast. Given a void *x
:
x+1
adds one byte to x
, pointer goes to byte x+1
(int*)x+1
adds sizeof(int)
bytes, pointer goes to byte x + sizeof(int)
(float*)x+1
addres sizeof(float)
bytes,
etc.Althought the first item is not portable and is against the Galateo of C/C++, it is nevertheless C-language-correct, meaning it will compile to something on most compilers possibly necessitating an appropriate flag (like -Wpointer-arith)
Add this to an htaccess file (and see edit notes added below):
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>
Additional resources and information:
2021 EDIT:
As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:
<IfModule
is loaded.mod_php5.c
in the first line. If you are using PHP 7, you would replace that with mod_php7.c
.php.ini
config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.try this code, it might work for you
$(this).find('input:text')[0].focus();
Selected answer and some others are all good. I just want give a more SQL pure explanation. It comes to same solution that there is no (valid) database owner.
Database owner account dbo
which is mentioned in error is always created with database. So it seems strange that it doesn't exist but you can check with two selects (or one but let's keep it simple).
SELECT [name],[sid]
FROM [DB_NAME].[sys].[database_principals]
WHERE [name] = 'dbo'
which shows SID of dbo
user in DB_NAME database and
SELECT [name],[sid]
FROM [sys].[syslogins]
to show all logins (and their SIDs) for this SQL server instance. Notice it didn't write any db_name prefix, that's because every database has same information in that view.
So in case of error above there will not be login with SID that is assigned to database dbo user.
As explained above that usually happens when restoring database from another computer (where database and dbo user were created by different login). And you can fix it by changing ownership to existing login.
The error shows up because we are using tensorflow version 2 and the command is from version 1. So if we use:
tf.compat.v1.summary.(method_name)
It'll work
Try:
dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')
According to the pandas documentation:
dtype : Type name or dict of column -> type
As for low_memory, it's True by default and isn't yet documented. I don't think its relevant though. The error message is generic, so you shouldn't need to mess with low_memory anyway. Hope this helps and let me know if you have further problems
Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.
You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.
If you allocate the array on the heap you should be fine, assuming your machine has enough memory.
int* array = new int[1000000];
But remember that this will require you to delete[]
the array. A better solution would be to use std::vector<int>
and resize it to 1000000 elements.
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
You can also use this code to get LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}
my_url("?z=z", { page_name : "pageX" /* no table_name and optionResult */ } );
/* Returns:
?z=z&page_name=pageX
*/
This avoids using typeof whatever === "undefined"
. (Also, there isn't any string concatenation.)
You are correct: calling finish()
will only exit the current activity, not the entire application. however, there is a workaround for this:
Every time you start an Activity, start it using startActivityForResult(...)
. When you want to close the entire app, you can do something like this:
setResult(RESULT_CLOSE_ALL);
finish();
Then define every activity's onActivityResult(...)
callback so when an activity returns with the RESULT_CLOSE_ALL
value, it also calls finish()
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(resultCode)
{
case RESULT_CLOSE_ALL:
setResult(RESULT_CLOSE_ALL);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
This will cause a cascade effect closing all activities.
Also, I support CommonsWare in his suggestion: store the password in a variable so that it will be destroyed when the application is closed.
To create an XMLdocument in PHP you should instance a DOMDocument class, create child nodes and append these nodes in the correct branch of the document tree.
For reference you can read http://it.php.net/manual/en/book.dom.php
Now we will take a quick tour of the code below.
These are the basics, you can create and append a node in just a line (13th, for example), you can do a lot of other things with the dom api. It is up to you.
<?php
/* create a dom document with encoding utf8 */
$domtree = new DOMDocument('1.0', 'UTF-8');
/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("xml");
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentTrack = $domtree->createElement("track");
$currentTrack = $xmlRoot->appendChild($currentTrack);
/* you should enclose the following two lines in a cicle */
$currentTrack->appendChild($domtree->createElement('path','song1.mp3'));
$currentTrack->appendChild($domtree->createElement('title','title of song1.mp3'));
$currentTrack->appendChild($domtree->createElement('path','song2.mp3'));
$currentTrack->appendChild($domtree->createElement('title','title of song2.mp3'));
/* get the xml printed */
echo $domtree->saveXML();
?>
Edit: Just one other hint: The main advantage of using an xmldocument (the dom document one or the simplexml one) instead of printing the xml,is that the xmltree is searchable with xpath query
you can use :
git clone <url> --branch <branch>
to clone/download only the contents of the branch.
This was helpful to me especially, since the contents of my branch were entirely different from the master branch (though this is not usually the case). Hence, the suggestions listed by others above didn't help me and I would end up getting a copy of the master even after I checked out the branch and did a git pull.
This command would directly give you the contents of the branch. It worked for me.
Create setenv.bat file in nib folder of Tomcat. Add SET JPDA_ADDRESS = 8787 ; Override the jpda port Open cmd, go to bin folder of Tomcat and Start tomcat using catalina jpda start Set up a debug point on eclipse Next compile your project. Check localhost:8080/ Deploy the war or jar under webapps folder and this must deploy war on Tomcat. Then send the request. the debug point will get hit NOTE : Don't edit catalina.bat file. make changes in setenv.bat file
None: The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
Compile: The file is compiled into the build output. This setting is used for code files.
Content: Allows you to retrieve a file (in the same directory as the assembly) as a stream via Application.GetContentStream(URI). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which Visual Studio graciously adds when you mark a file as "Content"
Embedded resource: Embeds the file in an exclusive assembly manifest resource.
Resource (WPF only): Embeds the file in a shared (by all files in the assembly with similar setting) assembly manifest resource named AppName.g.resources.
Page (WPF only): Used to compile a xaml
file into baml
. The baml
is then embedded with the same technique as Resource
(i.e. available as `AppName.g.resources)
ApplicationDefinition (WPF only): Mark the XAML/class file that defines your application. You specify the code-behind with the x:Class="Namespace.ClassName" and set the startup form/page with StartupUri="Window1.xaml"
SplashScreen (WPF only): An image that is marked as SplashScreen
is shown automatically when an WPF application loads, and then fades
DesignData: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses mock types)
DesignDataWithDesignTimeCreatableTypes: Compiles XAML viewmodels so that usercontrols can be previewed with sample data in Visual Studio (uses actual types)
EntityDeploy: (Entity Framework): used to deploy the Entity Framework artifacts
CodeAnalysisDictionary: An XML file containing custom word dictionary for spelling rules
I had the same problem and here is my solution (very humble, @george: this time compiling AND working ...).
My probem was inside an abstract class that implements Observer. The Observable fires method update(...) with Object class that can be any kind of Object.
I only want to handler Objects of type T
The solution is to pass the class to the constructor in order to be able to compare types at runtime.
public abstract class AbstractOne<T> implements Observer {
private Class<T> tClass;
public AbstractOne(Class<T> clazz) {
tClass = clazz;
}
@Override
public void update(Observable o, Object arg) {
if (tClass.isInstance(arg)) {
// Here I am, arg has the type T
foo((T) arg);
}
}
public abstract foo(T t);
}
For the implementation we just have to pass the Class to the constructor
public class OneImpl extends AbstractOne<Rule> {
public OneImpl() {
super(Rule.class);
}
@Override
public void foo(Rule t){
}
}
Depending on your platform you can use: sqlite3 file_name.db from the terminal. .tables will list the tables, .schema is full layout. SQLite commands like: select * from table_name; and such will print out the full contents. Type: ".exit" to exit. No need to download a GUI application.Use a semi-colon if you want it to execute a single command. Decent SQLite usage tutorial http://www.thegeekstuff.com/2012/09/sqlite-command-examples/
How about this one?
SELECT TO_CHAR(ASOFDATE, 'YYYY') FROM PSASOFDATE
Asus Nexus 7 on my Windows 7 64 bits computer for development purposes :
I tried to install the driver for the nexus 7 manually like explained in the official tutorial of Asus
Unfortunately, I had an error, Windows couldn't recognize the driver.
I tried to change the USB connection mode to PTP or MTP by going in the storage menu and clicking on the top right menu . In both cases, windows recognize the devices but it still didn't work in debugging mode.
The only way it worked for me is by installing : adb universal installer . I scanned it before clicking on the executable, it seems to be fine.
I think I tried everything mentioned here, and it still didn't work. Turns out it didn't recognize my domain login to the server as being in the Administrators group because it was implicit through my membership in another group ( Developers ) which is a member of the Administrators group.
I added my individual domain\login to the Administrators group explicitly, logged off and then logged back on to the box, and IE admitted me to the Report Manager homepage without requiring me to run IE as administrator.
If you want to restrict your search only to files you should consider to use -type f
in your search
try to use also -iname
for case-insensitive search
Example:
find /path -iname 'yourstring*' -type f
You could also perform some operations on results without pipe sign or xargs
Example:
Search for files and show their size in MB
find /path -iname 'yourstring*' -type f -exec du -sm {} \;
Please use below function if you don't want to round off.
function ConvertToDecimal(num) {
num = num.toString(); //If it's not already a String
num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
alert('M : ' + Number(num)); //If you need it back as a Number
}
Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
Making more general the @showdev answer.
var getObjectByValue = function (array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
};
Example:
getObjectByValue(data, "code", "DZ" );
In most languages i am aware of, the actual regex for validating should be
^[0-9]{1,10}$
; otherwise the matcher will also return positive matches if the to be validated number is part of a longer string.
You need to export the Customers Component not the CustomerList.
CustomersList = withRouter(Customers);
export default CustomersList;
With library(lubridate)
, numeric representations of date and time saved as the number of seconds since
1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime()
:
lubridate::as_datetime(1352068320)
[1] "2012-11-04 22:32:00 UTC"
@Manish Jain, I suggest to implement the method with boolean return:
public class UserManager
{
// Additional code here...
public async Task<bool> SignIn(HttpContext httpContext, UserDbModel user)
{
// Additional code here...
// Here the real authentication against a DB or Web Services or whatever
if (user.Email != null)
return false;
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
// This is for give the authentication cookie to the user when authentication condition was met
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return true;
}
}
To find the last filled column use the following :
lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Environment.NewLine should be used as Dan Rigby said but there is one problem with the String.Empty. It will remain always empty no matter if it is read before or after it reads. I had a problem in my project yesterday with that. I removed it and it worked the way it was supposed to. It's better to declare the variable and then call it when it's needed. String.Empty will always keep it empty unless the variable needs to be initialized which only then should you use String.Empty. Thought I would throw this tid-bit out for everyone as I've experienced it.
NULL has no value, and so cannot be compared using the scalar value operators.
In other words, no value can ever be equal to (or not equal to) NULL because NULL has no value.
Hence, SQL has special IS NULL and IS NOT NULL predicates for dealing with NULL.
SELECT NAME FROM v$database;
shows the database name in oracle
This worked for me:
string="1;2"
echo $string | cut -d';' -f1 # output is 1
echo $string | cut -d';' -f2 # output is 2
Another to answer this question available here answered by @nilesh https://stackoverflow.com/a/19934852/2079692
public void setAttributeValue(WebElement elem, String value){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
elem, "value", value
);
}
this takes advantage of selenium findElementBy function where xpath can be used also.
This is one more place that anaconda had an entry that was breaking my python install after removing Anaconda. Hoping this helps someone else.
If you are using yarn, I found this entry in my .yarn.rc file in ~/"username"
python "/Users/someone/anaconda3/bin/python3"
removing this line fixed one last place needed for complete removal. I am not sure how that entry was added but it helped
this code line could be a simpler way to acomplish the same:
public class ProductConfiguration : EntityTypeConfiguration<Product>
{
public ProductConfiguration()
{
this.Property(m => m.Price).HasPrecision(10, 2);
}
}
I had the same problem and managed to solve, it simply downgrade your gradle version like this:
dependencies {
classpath 'com.android.tools.build:gradle:YOUR_GRADLE_VERSION'
}
to
dependencies {
classpath 'com.android.tools.build:gradle:OLDER_GRADLE_VERSION_THAT_YOUR'
}
for example:
YOUR_GRADLE_VERSION = 3.0.0
OLDER_GRADLE_VERSION_THAT_YOUR = 2.3.2
The setHours
method can take optional minutes
, seconds
and ms
arguments, for example:
var d = new Date();
d.setHours(0,0,0,0);
That will set the time to 00:00:00.000
of your current timezone, if you want to work in UTC time, you can use the setUTCHours
method.
After some diving through some documentation and source code, I think I got it working. Perhaps this will be useful for someone else?
I added the following to my module configuration:
angular.module(...)
.config( ['$routeProvider', function($routeProvider) {...}] )
.run( function($rootScope, $location) {
// register listener to watch route changes
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
if ( $rootScope.loggedUser == null ) {
// no logged user, we should be going to #login
if ( next.templateUrl != "partials/login.html" ) {
// not going to #login, we should redirect now
$location.path( "/login" );
}
}
});
})
The one thing that seems odd is that I had to test the partial name (login.html
) because the "next" Route object did not have a url or something else. Maybe there's a better way?
Uploading Files using Retrofit is Quite Simple You need to build your api interface as
public interface Api {
String BASE_URL = "http://192.168.43.124/ImageUploadApi/";
@Multipart
@POST("yourapipath")
Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);
}
in the above code image is the key name so if you are using php you will write $_FILES['image']['tmp_name'] to get this. And filename="myfile.jpg" is the name of your file that is being sent with the request.
Now to upload the file you need a method that will give you the absolute path from the Uri.
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Now you can use the below code to upload your file.
private void uploadFile(Uri fileUri, String desc) {
//creating a file
File file = new File(getRealPathFromURI(fileUri));
//creating request body for file
RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);
//The gson builder
Gson gson = new GsonBuilder()
.setLenient()
.create();
//creating retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
//creating our api
Api api = retrofit.create(Api.class);
//creating a call and calling the upload image method
Call<MyResponse> call = api.uploadImage(requestFile, descBody);
//finally performing the call
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
if (!response.body().error) {
Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
For more detailed explanation you can visit this Retrofit Upload File Tutorial.
Using MVC5 you could use:
public enum UserPromotion
{
None = 0x0,
[Display(Name = "Send Job Offers By Mail")]
SendJobOffersByMail = 0x1,
[Display(Name = "Send Job Offers By Sms")]
SendJobOffersBySms = 0x2,
[Display(Name = "Send Other Stuff By Sms")]
SendPromotionalBySms = 0x4,
[Display(Name = "Send Other Stuff By Mail")]
SendPromotionalByMail = 0x8
}
then if you want to create a dropdown selector you can use:
@Html.EnumDropdownListFor(expression: model => model.PromotionSelector, optionLabel: "Select")
You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins
change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1
Not directly, no. Android's C runtime library, bionic, is not binary compatible with the GNU libc, which most Linux distributions use.
You can always try to recompile your binaries for Android and pray.
In a few words: The constructor is called first, then any @FXML
annotated fields are populated, then initialize()
is called.
This means the constructor does not have access to @FXML
fields referring to components defined in the .fxml file, while initialize()
does have access to them.
Quoting from the Introduction to FXML:
[...] the controller can define an initialize() method, which will be called once on an implementing controller when the contents of its associated document have been completely loaded [...] This allows the implementing class to perform any necessary post-processing on the content.
The tools sed
or tr
will do this for you by swapping the whitespace for nothing
sed 's/ //g'
tr -d ' '
Example:
$ echo " 3918912k " | sed 's/ //g'
3918912k
An other way of CASE:
SELECT *
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL THEN 1
WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1
WHEN @myParm = value3 THEN 1
END
This is a supplement answer related to the OP:
An easy and reliable solution to add Javadocs comments in Eclipse:
To use this tool, right-click on class and click on JAutodoc.
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
Mono contains an ADO.NET provider that should do this for you. I don't know if there is a command line utility for it, but you could definitely wrap up some C# to do the queries if there isn't.
Have a look at http://www.mono-project.com/TDS_Providers and http://www.mono-project.com/SQLClient
add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this
<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>
Distinct method returns distinct elements from a sequence.
If you take a look on its implementation with Reflector, you'll see that it creates DistinctIterator
for your anonymous type. Distinct iterator adds elements to Set
when enumerating over collection. This enumerator skips all elements which are already in Set
. Set
uses GetHashCode
and Equals
methods for defining if element already exists in Set
.
How GetHashCode
and Equals
implemented for anonymous type? As it stated on msdn:
Equals and GetHashCode methods on anonymous types are defined in terms of the Equals and GetHashcode methods of the properties, two instances of the same anonymous type are equal only if all their properties are equal.
So, you definitely should have distinct anonymous objects, when iterating on distinct collection. And result does not depend on how many fields you use for your anonymous type.
This topic is really confusing with Pandas. Luckily, it has a relatively simple solution.
The problem is that it is not always clear whether data filtering operations (e.g. loc) return a copy or a view of the DataFrame. Further use of such filtered DataFrame could therefore be confusing.
The simple solution is (unless you need to work with very large sets of data):
Whenever you need to update any values, always make sure that you explicitly copy the DataFrame before the assignment.
df # Some DataFrame
df = df.loc[:, 0:2] # Some filtering (unsure whether a view or copy is returned)
df = df.copy() # Ensuring a copy is made
df[df["Name"] == "John"] = "Johny" # Assignment can be done now (no warning)
In order to see the changes that have been staged already, you can pass the -–staged
option to git diff
(in pre-1.6 versions of Git, use –-cached
).
git diff --staged
git diff --cached
You can do this simply by :
select to_char(to_date(date_column, 'MM/DD/YYYY'), 'YYYY-MM-DD') from table
A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
When using a replicaset, writes must be done on the PRIMARY, so I usually use syntax like this which avoids having to figure out which host is the master:
mongo -host myReplicaset/anyKnownReplica
Using 'set -o vi' from the command line, or better, in .bashrc, puts you in vi editing mode on the command line. You start in 'insert' mode so you can type and backspace as normal, but if you make a 'large' mistake you can hit the esc key and then use 'b' and 'f' to move around as you do in vi. cw to change a word. Particularly useful after you've brought up a history command that you want to change.
Try using a div tag and block for span!
<div>
<span style="padding-right:3px; padding-top: 3px; display:block;">
<img class="manImg" src="images/ico_mandatory.gif"></img>
</span>
</div>
You can do so starting with Postgres 9.1:
with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows
In the meanwhile, if you're only interested in the id, you can do so with a trigger:
create function t1_ins_into_t2()
returns trigger
as $$
begin
insert into table2 (val) values (new.id);
return new;
end;
$$ language plpgsql;
create trigger t1_ins_into_t2
after insert on table1
for each row
execute procedure t1_ins_into_t2();
You're missing a return
statement.
When the compiler looks at your code, it's sees a third path (the else
you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value
.
For my suggested fix, I put a return
after your loop ends. The other obvious spot - adding an else
that had a return
value to the if-else-if
- would break the for
loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
I'd certainly look to TomEE since the idea behind is to keep Tomcat bringing all the JavaEE 6 integration missing by default. That's a kind of very good compromise
You can use the Test-Path
cmd-let. So something like...
if(!(Test-Path [oldLocation]) -and !(Test-Path [newLocation]))
{
Write-Host "$file doesn't exist in both locations."
}
I got this to work on all modern browsers, including IE9|IE8|IE7. The following code will open your YouTube video in a jQuery UI dialog modal, autoplay the video from 0:00 on dialog open, and stop video on dialog close.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("swfobject", "2.1");
function _run() {
/* YouTube player embed for modal dialog */
// The video to load.
var videoID = "INSERT YOUR YOUTUBE VIDEO ID HERE"
// Lets Flash from another domain call JavaScript
var params = { allowScriptAccess: "always" };
// The element id of the Flash embed
var atts = { id: "ytPlayer" };
// All of the magic handled by SWFObject (http://code.google.com/p/swfobject/)
swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?version=3&enablejsapi=1&playerapiid=player1&autoplay=1",
"videoDiv", "879", "520", "9", null, null, params, atts);
}
google.setOnLoadCallback(_run);
$(function () {
$("#big-video").dialog({
autoOpen: false,
close: function (event, ui) {
ytPlayer.stopVideo() // stops video/audio on dialog close
},
modal: true,
open: function (event, ui) {
ytPlayer.seekTo(0) // resets playback to beginning of video and then plays video
}
});
$("#big-video-opener").click(function () {
$("#big-video").dialog("open");
return false;
});
});
</script>
<div id="big-video" title="Video">
<div id="videoDiv">Loading...</div>
</div>
<a id="big-video-opener" class="button" href="#">Watch the short video</a>
A mutex is used for serial access to a resource while a semaphore limits access to a resource up to a set number. You can think of a mutex as a semaphore with an access count of 1. Whatever you set your semaphore count to, that may threads can access the resource before the resource is blocked.
del array[0]
where 0
is the index of the object in the list (there is no array in python)
I had this error and found the reason for the error in my case. I'm still answering to this old post because it ranks pretty high on Google.
The variables of both of the column I wanted to link were integers but one of the ints had 'unsigned' checked on. Simply un-checking that fixed my error.
This is a complete setup in Rails, for my own reference. I'm happy if it helps you too.
the query:
Product.where("lower(name) = ?", name.downcase).first
the validator:
validates :name, presence: true, uniqueness: {case_sensitive: false}
the index (answer from Case-insensitive unique index in Rails/ActiveRecord?):
execute "CREATE UNIQUE INDEX index_products_on_lower_name ON products USING btree (lower(name));"
I wish there was a more beautiful way to do the first and the last, but then again, Rails and ActiveRecord is open source, we shouldn't complain - we can implement it ourselves and send pull request.
You could
std::map<K,V>::iterator
std::transform
of your map.begin()
to map.end()
with a boost::bind( &pair::second, _1 )
functor->second
member while iterating with a for
loop.Could you not just try it?
myContent = '<div id="test">Hello <span>world!</span></div>';
console.log($(myContent).text()); //Prints "Hello world!"
Note that you need to wrap the string in a jQuery object, otherwise it won't have a text
method obviously.
I don't know if setLogLevel() will return in the final 2.0 version of Retrofit but for now you can use an interceptor for logging.
A good example can found in OkHttp wiki: https://github.com/square/okhttp/wiki/Interceptors
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.yourjsonapi.com")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Complete the following steps in Eclipse to get plugins for JavaScript files:
http://download.eclipse.org/releases/juno
To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"
To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )
I'm just learning this and what finally worked for me was to first make a table with three rows. Set the margin for the left and right rows to 50%. Then put a single row, fixed width table inside of the "table data" of the center "table row".
I have faced similar problem and it was returning #N/A
. That means matching data is present but you might having extra space in the M3 column record, that may prevent it from getting exact value. Because you have set last parameter as FALSE, it is looking for "exact match".
This formula is correct: =VLOOKUP(M3,Sheet1!$A$2:$Q$47,13,FALSE)
There is actually a default pattern that you can employ to achieve this result without having to implement IDesignTimeDbContextFactory
and do any config file copying.
It is detailed in this doc, which also discusses the other ways in which the framework will attempt to instantiate your DbContext
at design time.
Specifically, you leverage a new hook, in this case a static method of the form public static IWebHost BuildWebHost(string[] args)
. The documentation implies otherwise, but this method can live in whichever class houses your entry point (see src). Implementing this is part of the guidance in the 1.x to 2.x migration document and what's not completely obvious looking at the code is that the call to WebHost.CreateDefaultBuilder(args)
is, among other things, connecting your configuration in the default pattern that new projects start with. That's all you need to get the configuration to be used by the design time services like migrations.
Here's more detail on what's going on deep down in there:
While adding a migration, when the framework attempts to create your DbContext
, it first adds any IDesignTimeDbContextFactory
implementations it finds to a collection of factory methods that can be used to create your context, then it gets your configured services via the static hook discussed earlier and looks for any context types registered with a DbContextOptions
(which happens in your Startup.ConfigureServices
when you use AddDbContext
or AddDbContextPool
) and adds those factories. Finally, it looks through the assembly for any DbContext
derived classes and creates a factory method that just calls Activator.CreateInstance
as a final hail mary.
The order of precedence that the framework uses is the same as above. Thus, if you have IDesignTimeDbContextFactory
implemented, it will override the hook mentioned above. For most common scenarios though, you won't need IDesignTimeDbContextFactory
.
where java
works for me to list all java exe but java -verbose
tells you which rt.jar
is used and thus which jre (full path):
[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...
Edit: win7 and java:
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
You're in replace mode. Press the Insert
key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.
You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.
You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.
If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.
In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.
Set your PERL_UNICODE
envariable to AS
. This makes all Perl scripts decode @ARGV
as UTF-8 strings, and sets the encoding of all three of stdin, stdout, and stderr to UTF-8. Both these are global effects, not lexical ones.
At the top of your source file (program, module, library, do
hickey), prominently assert that you are running perl version 5.12 or better via:
use v5.12; # minimal for unicode string feature
use v5.14; # optimal for unicode string feature
Enable warnings, since the previous declaration only enables strictures and features, not warnings. I also suggest promoting Unicode warnings into exceptions, so use both these lines, not just one of them. Note however that under v5.14, the utf8
warning class comprises three other subwarnings which can all be separately enabled: nonchar
, surrogate
, and non_unicode
. These you may wish to exert greater control over.
use warnings;
use warnings qw( FATAL utf8 );
Declare that this source unit is encoded as UTF-8. Although once upon a time this pragma did other things, it now serves this one singular purpose alone and no other:
use utf8;
Declare that anything that opens a filehandle within this lexical scope but not elsewhere is to assume that that stream is encoded in UTF-8 unless you tell it otherwise. That way you do not affect other module’s or other program’s code.
use open qw( :encoding(UTF-8) :std );
Enable named characters via \N{CHARNAME}
.
use charnames qw( :full :short );
If you have a DATA
handle, you must explicitly set its encoding. If you want this to be UTF-8, then say:
binmode(DATA, ":encoding(UTF-8)");
There is of course no end of other matters with which you may eventually find yourself concerned, but these will suffice to approximate the state goal to “make everything just work with UTF-8”, albeit for a somewhat weakened sense of those terms.
One other pragma, although it is not Unicode related, is:
use autodie;
It is strongly recommended.
My own boilerplate these days tends to look like this:
use 5.014;
use utf8;
use strict;
use autodie;
use warnings;
use warnings qw< FATAL utf8 >;
use open qw< :std :utf8 >;
use charnames qw< :full >;
use feature qw< unicode_strings >;
use File::Basename qw< basename >;
use Carp qw< carp croak confess cluck >;
use Encode qw< encode decode >;
use Unicode::Normalize qw< NFD NFC >;
END { close STDOUT }
if (grep /\P{ASCII}/ => @ARGV) {
@ARGV = map { decode("UTF-8", $_) } @ARGV;
}
$0 = basename($0); # shorter messages
$| = 1;
binmode(DATA, ":utf8");
# give a full stack dump on any untrapped exceptions
local $SIG{__DIE__} = sub {
confess "Uncaught exception: @_" unless $^S;
};
# now promote run-time warnings into stack-dumped
# exceptions *unless* we're in an try block, in
# which case just cluck the stack dump instead
local $SIG{__WARN__} = sub {
if ($^S) { cluck "Trapped warning: @_" }
else { confess "Deadly warning: @_" }
};
while (<>) {
chomp;
$_ = NFD($_);
...
} continue {
say NFC($_);
}
__END__
Saying that “Perl should [somehow!] enable Unicode by default” doesn’t even start to begin to think about getting around to saying enough to be even marginally useful in some sort of rare and isolated case. Unicode is much much more than just a larger character repertoire; it’s also how those characters all interact in many, many ways.
Even the simple-minded minimal measures that (some) people seem to think they want are guaranteed to miserably break millions of lines of code, code that has no chance to “upgrade” to your spiffy new Brave New World modernity.
It is way way way more complicated than people pretend. I’ve thought about this a huge, whole lot over the past few years. I would love to be shown that I am wrong. But I don’t think I am. Unicode is fundamentally more complex than the model that you would like to impose on it, and there is complexity here that you can never sweep under the carpet. If you try, you’ll break either your own code or somebody else’s. At some point, you simply have to break down and learn what Unicode is about. You cannot pretend it is something it is not.
goes out of its way to make Unicode easy, far more than anything else I’ve ever used. If you think this is bad, try something else for a while. Then come back to : either you will have returned to a better world, or else you will bring knowledge of the same with you so that we can make use of your new knowledge to make better at these things.
At a minimum, here are some things that would appear to be required for to “enable Unicode by default”, as you put it:
All source code should be in UTF-8 by default. You can get that with use utf8
or export PERL5OPTS=-Mutf8
.
The DATA
handle should be UTF-8. You will have to do this on a per-package basis, as in binmode(DATA, ":encoding(UTF-8)")
.
Program arguments to scripts should be understood to be UTF-8 by default. export PERL_UNICODE=A
, or perl -CA
, or export PERL5OPTS=-CA
.
The standard input, output, and error streams should default to UTF-8. export PERL_UNICODE=S
for all of them, or I
, O
, and/or E
for just some of them. This is like perl -CS
.
Any other handles opened by should be considered UTF-8 unless declared otherwise; export PERL_UNICODE=D
or with i
and o
for particular ones of these; export PERL5OPTS=-CD
would work. That makes -CSAD
for all of them.
Cover both bases plus all the streams you open with export PERL5OPTS=-Mopen=:utf8,:std
. See uniquote.
You don’t want to miss UTF-8 encoding errors. Try export PERL5OPTS=-Mwarnings=FATAL,utf8
. And make sure your input streams are always binmode
d to :encoding(UTF-8)
, not just to :utf8
.
Code points between 128–255 should be understood by to be the corresponding Unicode code points, not just unpropertied binary values. use feature "unicode_strings"
or export PERL5OPTS=-Mfeature=unicode_strings
. That will make uc("\xDF") eq "SS"
and "\xE9" =~ /\w/
. A simple export PERL5OPTS=-Mv5.12
or better will also get that.
Named Unicode characters are not by default enabled, so add export PERL5OPTS=-Mcharnames=:full,:short,latin,greek
or some such. See uninames and tcgrep.
You almost always need access to the functions from the standard Unicode::Normalize
module various types of decompositions. export PERL5OPTS=-MUnicode::Normalize=NFD,NFKD,NFC,NFKD
, and then always run incoming stuff through NFD and outbound stuff from NFC. There’s no I/O layer for these yet that I’m aware of, but see nfc, nfd, nfkd, and nfkc.
String comparisons in using eq
, ne
, lc
, cmp
, sort
, &c&cc are always wrong. So instead of @a = sort @b
, you need @a = Unicode::Collate->new->sort(@b)
. Might as well add that to your export PERL5OPTS=-MUnicode::Collate
. You can cache the key for binary comparisons.
built-ins like printf
and write
do the wrong thing with Unicode data. You need to use the Unicode::GCString
module for the former, and both that and also the Unicode::LineBreak
module as well for the latter. See uwc and unifmt.
If you want them to count as integers, then you are going to have to run your \d+
captures through the Unicode::UCD::num
function because ’s built-in atoi(3) isn’t currently clever enough.
You are going to have filesystem issues on filesystems. Some filesystems silently enforce a conversion to NFC; others silently enforce a conversion to NFD. And others do something else still. Some even ignore the matter altogether, which leads to even greater problems. So you have to do your own NFC/NFD handling to keep sane.
All your code involving a-z
or A-Z
and such MUST BE CHANGED, including m//
, s///
, and tr///
. It’s should stand out as a screaming red flag that your code is broken. But it is not clear how it must change. Getting the right properties, and understanding their casefolds, is harder than you might think. I use unichars and uniprops every single day.
Code that uses \p{Lu}
is almost as wrong as code that uses [A-Za-z]
. You need to use \p{Upper}
instead, and know the reason why. Yes, \p{Lowercase}
and \p{Lower}
are different from \p{Ll}
and \p{Lowercase_Letter}
.
Code that uses [a-zA-Z]
is even worse. And it can’t use \pL
or \p{Letter}
; it needs to use \p{Alphabetic}
. Not all alphabetics are letters, you know!
If you are looking for variables with /[\$\@\%]\w+/
, then you have a problem. You need to look for /[\$\@\%]\p{IDS}\p{IDC}*/
, and even that isn’t thinking about the punctuation variables or package variables.
If you are checking for whitespace, then you should choose between \h
and \v
, depending. And you should never use \s
, since it DOES NOT MEAN [\h\v]
, contrary to popular belief.
If you are using \n
for a line boundary, or even \r\n
, then you are doing it wrong. You have to use \R
, which is not the same!
If you don’t know when and whether to call Unicode::Stringprep, then you had better learn.
Case-insensitive comparisons need to check for whether two things are the same letters no matter their diacritics and such. The easiest way to do that is with the standard Unicode::Collate module. Unicode::Collate->new(level => 1)->cmp($a, $b)
. There are also eq
methods and such, and you should probably learn about the match
and substr
methods, too. These are have distinct advantages over the built-ins.
Sometimes that’s still not enough, and you need the Unicode::Collate::Locale module instead, as in Unicode::Collate::Locale->new(locale => "de__phonebook", level => 1)->cmp($a, $b)
instead. Consider that Unicode::Collate::->new(level => 1)->eq("d", "ð")
is true, but Unicode::Collate::Locale->new(locale=>"is",level => 1)->eq("d", " ð")
is false. Similarly, "ae" and "æ" are eq
if you don’t use locales, or if you use the English one, but they are different in the Icelandic locale. Now what? It’s tough, I tell you. You can play with ucsort to test some of these things out.
Consider how to match the pattern CVCV (consonsant, vowel, consonant, vowel) in the string “niño”. Its NFD form — which you had darned well better have remembered to put it in — becomes “nin\x{303}o”. Now what are you going to do? Even pretending that a vowel is [aeiou]
(which is wrong, by the way), you won’t be able to do something like (?=[aeiou])\X)
either, because even in NFD a code point like ‘ø’ does not decompose! However, it will test equal to an ‘o’ using the UCA comparison I just showed you. You can’t rely on NFD, you have to rely on UCA.
And that’s not all. There are a million broken assumptions that people make about Unicode. Until they understand these things, their code will be broken.
Code that assumes it can open a text file without specifying the encoding is broken.
Code that assumes the default encoding is some sort of native platform encoding is broken.
Code that assumes that web pages in Japanese or Chinese take up less space in UTF-16 than in UTF-8 is wrong.
Code that assumes Perl uses UTF-8 internally is wrong.
Code that assumes that encoding errors will always raise an exception is wrong.
Code that assumes Perl code points are limited to 0x10_FFFF is wrong.
Code that assumes you can set $/
to something that will work with any valid line separator is wrong.
Code that assumes roundtrip equality on casefolding, like lc(uc($s)) eq $s
or uc(lc($s)) eq $s
, is completely broken and wrong. Consider that the uc("s")
and uc("?")
are both "S"
, but lc("S")
cannot possibly return both of those.
Code that assumes every lowercase code point has a distinct uppercase one, or vice versa, is broken. For example, "ª"
is a lowercase letter with no uppercase; whereas both "?"
and "?"
are letters, but they are not lowercase letters; however, they are both lowercase code points without corresponding uppercase versions. Got that? They are not \p{Lowercase_Letter}
, despite being both \p{Letter}
and \p{Lowercase}
.
Code that assumes changing the case doesn’t change the length of the string is broken.
Code that assumes there are only two cases is broken. There’s also titlecase.
Code that assumes only letters have case is broken. Beyond just letters, it turns out that numbers, symbols, and even marks have case. In fact, changing the case can even make something change its main general category, like a \p{Mark}
turning into a \p{Letter}
. It can also make it switch from one script to another.
Code that assumes that case is never locale-dependent is broken.
Code that assumes Unicode gives a fig about POSIX locales is broken.
Code that assumes you can remove diacritics to get at base ASCII letters is evil, still, broken, brain-damaged, wrong, and justification for capital punishment.
Code that assumes that diacritics \p{Diacritic}
and marks \p{Mark}
are the same thing is broken.
Code that assumes \p{GC=Dash_Punctuation}
covers as much as \p{Dash}
is broken.
Code that assumes dash, hyphens, and minuses are the same thing as each other, or that there is only one of each, is broken and wrong.
Code that assumes every code point takes up no more than one print column is broken.
Code that assumes that all \p{Mark}
characters take up zero print columns is broken.
Code that assumes that characters which look alike are alike is broken.
Code that assumes that characters which do not look alike are not alike is broken.
Code that assumes there is a limit to the number of code points in a row that just one \X
can match is wrong.
Code that assumes \X
can never start with a \p{Mark}
character is wrong.
Code that assumes that \X
can never hold two non-\p{Mark}
characters is wrong.
Code that assumes that it cannot use "\x{FFFF}"
is wrong.
Code that assumes a non-BMP code point that requires two UTF-16 (surrogate) code units will encode to two separate UTF-8 characters, one per code unit, is wrong. It doesn’t: it encodes to single code point.
Code that transcodes from UTF-16 or UTF-32 with leading BOMs into UTF-8 is broken if it puts a BOM at the start of the resulting UTF-8. This is so stupid the engineer should have their eyelids removed.
Code that assumes the CESU-8 is a valid UTF encoding is wrong. Likewise, code that thinks encoding U+0000 as "\xC0\x80"
is UTF-8 is broken and wrong. These guys also deserve the eyelid treatment.
Code that assumes characters like >
always points to the right and <
always points to the left are wrong — because they in fact do not.
Code that assumes if you first output character X
and then character Y
, that those will show up as XY
is wrong. Sometimes they don’t.
Code that assumes that ASCII is good enough for writing English properly is stupid, shortsighted, illiterate, broken, evil, and wrong. Off with their heads! If that seems too extreme, we can compromise: henceforth they may type only with their big toe from one foot. (The rest will be duct taped.)
Code that assumes that all \p{Math}
code points are visible characters is wrong.
Code that assumes \w
contains only letters, digits, and underscores is wrong.
Code that assumes that ^
and ~
are punctuation marks is wrong.
Code that assumes that ü
has an umlaut is wrong.
Code that believes things like ?
contain any letters in them is wrong.
Code that believes \p{InLatin}
is the same as \p{Latin}
is heinously broken.
Code that believe that \p{InLatin}
is almost ever useful is almost certainly wrong.
Code that believes that given $FIRST_LETTER
as the first letter in some alphabet and $LAST_LETTER
as the last letter in that same alphabet, that [${FIRST_LETTER}-${LAST_LETTER}]
has any meaning whatsoever is almost always complete broken and wrong and meaningless.
Code that believes someone’s name can only contain certain characters is stupid, offensive, and wrong.
Code that tries to reduce Unicode to ASCII is not merely wrong, its perpetrator should never be allowed to work in programming again. Period. I’m not even positive they should even be allowed to see again, since it obviously hasn’t done them much good so far.
Code that believes there’s some way to pretend textfile encodings don’t exist is broken and dangerous. Might as well poke the other eye out, too.
Code that converts unknown characters to ?
is broken, stupid, braindead, and runs contrary to the standard recommendation, which says NOT TO DO THAT! RTFM for why not.
Code that believes it can reliably guess the encoding of an unmarked textfile is guilty of a fatal mélange of hubris and naïveté that only a lightning bolt from Zeus will fix.
Code that believes you can use printf
widths to pad and justify Unicode data is broken and wrong.
Code that believes once you successfully create a file by a given name, that when you run ls
or readdir
on its enclosing directory, you’ll actually find that file with the name you created it under is buggy, broken, and wrong. Stop being surprised by this!
Code that believes UTF-16 is a fixed-width encoding is stupid, broken, and wrong. Revoke their programming licence.
Code that treats code points from one plane one whit differently than those from any other plane is ipso facto broken and wrong. Go back to school.
Code that believes that stuff like /s/i
can only match "S"
or "s"
is broken and wrong. You’d be surprised.
Code that uses \PM\pM*
to find grapheme clusters instead of using \X
is broken and wrong.
People who want to go back to the ASCII world should be whole-heartedly encouraged to do so, and in honor of their glorious upgrade they should be provided gratis with a pre-electric manual typewriter for all their data-entry needs. Messages sent to them should be sent via an ??????s telegraph at 40 characters per line and hand-delivered by a courier. STOP.
I don’t know how much more “default Unicode in ” you can get than what I’ve written. Well, yes I do: you should be using Unicode::Collate
and Unicode::LineBreak
, too. And probably more.
As you see, there are far too many Unicode things that you really do have to worry about for there to ever exist any such thing as “default to Unicode”.
What you’re going to discover, just as we did back in 5.8, that it is simply impossible to impose all these things on code that hasn’t been designed right from the beginning to account for them. Your well-meaning selfishness just broke the entire world.
And even once you do, there are still critical issues that require a great deal of thought to get right. There is no switch you can flip. Nothing but brain, and I mean real brain, will suffice here. There’s a heck of a lot of stuff you have to learn. Modulo the retreat to the manual typewriter, you simply cannot hope to sneak by in ignorance. This is the 21?? century, and you cannot wish Unicode away by willful ignorance.
You have to learn it. Period. It will never be so easy that “everything just works,” because that will guarantee that a lot of things don’t work — which invalidates the assumption that there can ever be a way to “make it all work.”
You may be able to get a few reasonable defaults for a very few and very limited operations, but not without thinking about things a whole lot more than I think you have.
As just one example, canonical ordering is going to cause some real headaches. "\x{F5}"
‘õ’, "o\x{303}"
‘õ’, "o\x{303}\x{304}"
‘?’, and "o\x{304}\x{303}"
‘o~’ should all match ‘õ’, but how in the world are you going to do that? This is harder than it looks, but it’s something you need to account for.
If there’s one thing I know about Perl, it is what its Unicode bits do and do not do, and this thing I promise you: “ _?_?_?_?_?_ _?_s_ _?_?_ _U_?_?_?_?_?_?_ _?_?_?_?_?_ _?_?_?_?_?_?_ _ ”
You cannot just change some defaults and get smooth sailing. It’s true that I run with PERL_UNICODE
set to "SA"
, but that’s all, and even that is mostly for command-line stuff. For real work, I go through all the many steps outlined above, and I do it very, ** very** carefully.
If $_SERVER['HTTP_REFERER']
variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.
Refering to the extension solution:
for(int i=1; i< newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n"];
should be replaced by
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n "];
Additional space is needed in every added newline, because iPhone UILabels
' trailing carriage returns seems to be ignored :(
Similarly, alignBottom should be updated too with a @" \n@%"
in place of "\n@%"
(for cycle initialization must be replaced by "for(int i=0..." too).
The following extension works for me:
// -- file: UILabel+VerticalAlign.h
#pragma mark VerticalAlign
@interface UILabel (VerticalAlign)
- (void)alignTop;
- (void)alignBottom;
@end
// -- file: UILabel+VerticalAlign.m
@implementation UILabel (VerticalAlign)
- (void)alignTop {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [self.text stringByAppendingString:@"\n "];
}
- (void)alignBottom {
CGSize fontSize = [self.text sizeWithFont:self.font];
double finalHeight = fontSize.height * self.numberOfLines;
double finalWidth = self.frame.size.width; //expected width of label
CGSize theStringSize = [self.text sizeWithFont:self.font constrainedToSize:CGSizeMake(finalWidth, finalHeight) lineBreakMode:self.lineBreakMode];
int newLinesToPad = (finalHeight - theStringSize.height) / fontSize.height;
for(int i=0; i<newLinesToPad; i++)
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
@end
Then call [yourLabel alignTop];
or [yourLabel alignBottom];
after each yourLabel text assignment.
You have
COPY files/* /test/
which expands toCOPY files/dir files/file1 files/file2 files/file /test/
.
If you split this up into individualCOPY
commands (e.g.COPY files/dir /test/
) you'll see that (for better or worse)COPY
will copy the contents of each argdir
into the destination directory. Not the argdir
itself, but the contents.I'm not thrilled with that fact that COPY doesn't preserve the top-level dir but its been that way for a while now.
so in the name of preserving a backward compatibility, it is not possible to COPY
/ADD
a directory structure.
The only workaround would be a series of RUN mkdir -p /x/y/z
to build the target directory structure, followed by a series of docker ADD
(one for each folder to fill).
(ADD
, not COPY
, as per comments)
composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Update memory on Server and require '4G' Change 4GB Ram [try to change server type or add more ram]
2 Files We need to edit
on command
# cd /var/www/html
# nano .htaccess
and edit "memory_limit 756M”
to 4G
Php ini on php 7.0
# cd ~
# php –-ini
# sudo nano /etc/php-7.0.ini
memory_limit = 128M to 4G
#AWS #AMAZONLINUX #MAGENTO2 #PHP7.0
You have referenced the image as a path on your computer (C:\etc\etc)......is it located there? You didn't answer what others have asked. I have taken your code, placed it in dreamweaver and it works apart from the image as I don't have that stored.
Check the location and then let us know.