In my case, during a merge, it seems the solution file was missing some project references. Manually re-adding the project to the solution fixed it. You can also manually edit the solution file but you need to be careful and know what you are doing.
completed = (id) => {
var details = {
'id': id,
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch(markcompleted, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson, 'res JSON');
if (responseJson.status == "success") {
console.log(this.state);
alert("your todolist is completed!!");
}
})
.catch((error) => {
console.error(error);
});
};
Here is the sort, depending on the length of a string with javascript as you asked:
[the solution of the problem by bubble sort][1]
[1]: http://jsfiddle.net/sssonline2/vcme3/2/enter code here
$data = '+11234567890';
if( preg_match( '/^\+\d(\d{3})(\d{3})(\d{4})$/', $data, $matches ) )
{
$result = $matches[1] . '-' .$matches[2] . '-' . $matches[3];
return $result;
}
const char* text_char = "example of mbstowcs";
size_t length = strlen(text_char );
Example of usage "mbstowcs"
std::wstring text_wchar(length, L'#');
//#pragma warning (disable : 4996)
// Or add to the preprocessor: _CRT_SECURE_NO_WARNINGS
mbstowcs(&text_wchar[0], text_char , length);
Example of usage "mbstowcs_s"
Microsoft suggest to use "mbstowcs_s" instead of "mbstowcs".
Links:
wchar_t text_wchar[30];
mbstowcs_s(&length, text_wchar, text_char, length);
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
In a nutshell, layout_weight
specifies how much of the extra space in the layout to be allocated to the View.
LinearLayout supports assigning a weight to individual children. This attribute assigns an "importance" value to a view, and allows it to expand to fill any remaining space in the parent view. Views' default weight is zero.
In general, the formula is:
space assigned to child = (child's individual weight) / (sum of weight of every child in Linear Layout)
If there are three text boxes and two of them declare a weight of 1, while the third one is given no weight (0), then remaining space is assigned as follows:
1st text box = 1/(1+1+0)
2nd text box = 1/(1+1+0)
3rd text box = 0/(1+1+0)
Let's say we have a text label and two text edit elements in a horizontal row. The label has no layout_weight
specified, so it takes up the minimum space required to render. If the layout_weight
of each of the two text edit elements is set to 1, the remaining width in the parent layout will be split equally between them (because we claim they are equally important).
Calculation:
1st label = 0/(0+1+1)
2nd text box = 1/(0+1+1)
3rd text box = 1/(0+1+1)
If, instead, the first one text box has a layout_weight
of 1, and the second text box has a layout_weight
of 2, then one third of the remaining space will be given to the first, and two thirds to the second (because we claim the second one is more important).
Calculation:
1st label = 0/(0+1+2)
2nd text box = 1/(0+1+2)
3rd text box = 2/(0+1+2)
def ipcheck():
# 1.Validate the ip adderess
input_ip = input('Enter the ip:')
flag = 0
pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(pattern, input_ip)
if (match):
field = input_ip.split(".")
for i in range(0, len(field)):
if (int(field[i]) < 256):
flag += 1
else:
flag = 0
if (flag == 4):
print("valid ip")
else:
print('No match for ip or not a valid ip')
Posting a java based solution, incase your team only uses java. The keyword inner
will ensure that matching rows only are present in the final dataframe.
Dataset<Row> joined = PersonDf.join(ProfileDf,
PersonDf.col("personId").equalTo(ProfileDf.col("personId")),
"inner");
joined.show();
Some of the answers I've seen explain how to make the contents of a cell invisible, but not how to hide the entire column, which is what I wanted to do.
If you have AutoGenerateColumns = "false"
and are actually using BoundField
for the column you want to hide, Bala's answer is slick. But if you are using TemplateField
for the column, you can handle the DataBound
event and do something like this:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
This may not be what the OP was looking for, but it's the solution I was looking for when I found myself asking the same question.
You can do something like this:
var newList = list.Where(w => w.Name == "height")
.Select(s => new {s.Name, s.Value= 30 }).ToList();
But I would rather choose to use foreach
because LINQ
is for querying while you
want to edit the data.
I think that in this question is missing one important information.
How many records will you insert?
Try switching to Logback and use
ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(Level.toLevel("info"));
I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.
Remember to set the log level back after you're done.
git pull origin master
will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master
.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master
is throwing the error.
To add to the above answer (do steps 1-5).
I don't know about MySQL, but in MS SQL, you can use the column index in the order by
clause. I've done this before when doing counts with group by
s as it tends to be easier to work with.
So
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
Becomes
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20
When you push a new branch the first time use: >git push -u origin
After that, you can just type a shorter command: >git push
The first-time -u option created a persistent upstream tracking branch with your local branch.
Just before </body>
is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.
import imp
imp.reload(script4)
1.make sure you ref jquery.js at first
2.check layout,make sure you call "~/bundles/bootstrap"
3.check layout,see render section Scripts position,it must be after "~/bundles/bootstrap"
4.add class "datepicker" to textbox
5.put $('.datepicker').datepicker(); in $(function(){...});
For me, there are some changes to make(ver. 2.20)
moment.locale('de')
, and you create a new object representing the date of now by moment()
(note the parenthesis) and then format('LLL')
it. The parenthesis is important.So that means:
moment.locale('de');
var now = moment();
now.format('LLL');
moment-with-locale.js
. The file contains all locale info and has a larger file size. Download the locale
folder is not enough. If necessary, change the name to be moment.js
. Django just refuses to load moment-with-locale.js
in my case.EDIT: It turned out that renaming the file is not necessary. I just forgot to invoke it in the page so Django does not think loading it is necessary, so my fault.
Slicing:
x = [0,1,2,3,4]
x = x[1:]
Which would actually return a subset of the original but not modify it.
Classic case for a recursive solution. Here's mine:
class JsonFormatter {
public static function prettyPrint(&$j, $indentor = "\t", $indent = "") {
$inString = $escaped = false;
$result = $indent;
if(is_string($j)) {
$bak = $j;
$j = str_split(trim($j, '"'));
}
while(count($j)) {
$c = array_shift($j);
if(false !== strpos("{[,]}", $c)) {
if($inString) {
$result .= $c;
} else if($c == '{' || $c == '[') {
$result .= $c."\n";
$result .= self::prettyPrint($j, $indentor, $indentor.$indent);
$result .= $indent.array_shift($j);
} else if($c == '}' || $c == ']') {
array_unshift($j, $c);
$result .= "\n";
return $result;
} else {
$result .= $c."\n".$indent;
}
} else {
$result .= $c;
$c == '"' && !$escaped && $inString = !$inString;
$escaped = $c == '\\' ? !$escaped : false;
}
}
$j = $bak;
return $result;
}
}
Usage:
php > require 'JsonFormatter.php';
php > $a = array('foo' => 1, 'bar' => 'This "is" bar', 'baz' => array('a' => 1, 'b' => 2, 'c' => '"3"'));
php > print_r($a);
Array
(
[foo] => 1
[bar] => This "is" bar
[baz] => Array
(
[a] => 1
[b] => 2
[c] => "3"
)
)
php > echo JsonFormatter::prettyPrint(json_encode($a));
{
"foo":1,
"bar":"This \"is\" bar",
"baz":{
"a":1,
"b":2,
"c":"\"3\""
}
}
Cheers
You are trying to load a XIB named DetailViewController
, but no such XIB exists or it's not member of your current target.
The C++ ? General ? Additional Include Directories parameter is for listing directories where the compiler will search for header files.
You need to tell the linker where to look for libraries to link to. To access this setting, right-click on the project name in the Solution Explorer window, then Properties ? Linker ? General ? Additional Library Directories. Enter <boost_path>\stage\lib
here (this is the path where the libraries are located if you build Boost using default options).
Create a Name.bat file that has the following line in it.
taskkill /F /IM wscript.exe /T
Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.
This issue happens as the code which is trying to connect to db, has a timezone which is not in db. It can also be resolved by setting the time zone as below or any valid time zone available in oracle db. valid time zone which can be found select * from v$version;
System.setProperty("user.timezone", "America/New_York"); TimeZone.setDefault(null);
asprintf
is not 100% standard, but it's available via the GNU and BSD standard C libraries, so you probably have it. It allocates the output, so you don't have to sit there and count characters.
char *hi="Hello";
char *ext = ".txt";
char *cat;
asprintf(&cat, "%s%s", hi, ext);
You can also use CURRENT_TIMESTAMP
, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate()
under the covers (see this question for more on that).
There's no ANSI equivalent for GetUTCDate()
, however, which is probably the one you should be using if your app operates in more than a single time zone ...
Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.
C:\Windows\SysWOW64>regsvr32 "c:\dll.name"
I tried to added those files into my .gitignore
and it was useless...
Nevertheless, as Petr Syrov said, you can use git rm -r --cached .idea
into your terminal and those files won't be a problem anymore!
I ignore all classes residing in target folder from git. add following line in open .gitignore file:
/.class
OR
*/target/**
It is working perfectly for me. try it.
You can easily do this using _.pick:
var model = {
fname: null,
lname: null
};
var credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
var result = _.pick(credentials, _.keys(model));
console.log('result =', result);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
But you can simply use pure JavaScript (specially if you use ECMAScript 6), like this:
const model = {
fname: null,
lname: null
};
const credentials = {
fname: 'abc',
lname: 'xyz',
age: 2
};
const newModel = {};
Object.keys(model).forEach(key => newModel[key] = credentials[key]);
console.log('newModel =', newModel);
_x000D_
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
Horrible, I know, but I just couldn't help myself:
namespace ConsoleApplication2
{
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
Random adomRng = new Random();
string rndString = string.Empty;
char c;
for (int i = 0; i < 8; i++)
{
while (!Regex.IsMatch((c=Convert.ToChar(adomRng.Next(48,128))).ToString(), "[A-Za-z0-9]"));
rndString += c;
}
Console.WriteLine(rndString + Environment.NewLine);
}
}
}
I did the same as @Moesio Above but in Kotlin it could be done this way:
class A<T : SomeClass>() {
var someClassType : T
init(){
this.someClassType = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
}
}
An answer that shouldn't be overlooked, because it's simple and presents advantages, is sampling of real life photos and paintings. sample as many random pixels as you want random colors on thumbnails of modern art pics, cezanne, van gogh, monnet, photos... the advantage is that you can get colors by theme and that they are organic colors. just put 20 - 30 pics in a folder and random sample a random pic every time.
Conversion to HSV values is a widespread code algorithm for psychologically based palette. hsv is easier to randomize.
Check out the substring function.
To get the last character:
id.substring(id.length - 1, id.length);
Got it working with
Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();
You can also use:
sdiff file1 file2
To display differences side by side within your terminal!
Wait!
There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password
To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer
"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user
name for which you want to retrieve password.Copy the password field (Hashed Code) and
paste here (in Hashed code Field) and click on start button to retrieve
I checked the tool on SQLServer 2000 and it's working fine.
If your equation does not fit on a single line, then the multline
environment probably is what you need:
\begin{multline}
first part of the equation \\
= second part of the equation
\end{multline}
If you also need some alignment respect to the first part, you can use split
:
\begin{equation}
\begin{split}
first part &= second part #1 \\
&= second part #2
\end{split}
\end{equation}
Both environments require the amsmath
package.
See also aligned
as pointed out in an answer below.
Because it is asynchronous, the $scope
is getting the data before the ajax call is complete.
You could use $q
in your service to create promise
and give it back to
controller, and controller obtain the result within then()
call against promise
.
In your service,
app.factory('myService', function($http, $q) {
var deffered = $q.defer();
var data = [];
var myService = {};
myService.async = function() {
$http.get('test.json')
.success(function (d) {
data = d;
console.log(d);
deffered.resolve();
});
return deffered.promise;
};
myService.data = function() { return data; };
return myService;
});
Then, in your controller:
app.controller('MainCtrl', function( myService,$scope) {
myService.async().then(function() {
$scope.data = myService.data();
});
});
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);
You can save an html file with the extension 'xls' and accents will work (pre 2007 at least).
Example: save this (using Save As utf8 in Notepad) as test.xls:
<html>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<table>
<tr>
<th>id</th>
<th>name</th>
</tr>
<tr>
<td>4</td>
<td>Hélène</td>
</tr>
</table>
</html>
git branch --set-upstream <remote-branch>
sets the default remote branch for the current local branch.
Any future git pull
command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch>
into the current local branch.
One way to avoid having to explicitly type --set-upstream
is to use its shorthand flag -u
as follows:
git push -u origin local-branch
This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.
To avoid confusion, recent versions of
git
deprecate this somewhat ambiguous--set-upstream
option in favour of a more verbose--set-upstream-to
option with identical syntax and behaviourgit branch --set-upstream-to <origin/remote-branch>
You can read here about the behaviour of attributes in many different browsers, including IE.
element.setAttribute()
should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value'
might work.
You can use the resulting xaml from the SVG as a drawing brush on a rectangle. Something like this:
<Rectangle>
<Rectangle.Fill>
--- insert the converted xaml's geometry here ---
</Rectangle.Fill>
</Rectangle>
A bit simplified you can think of it as arrays being a special case and not ordinary classes (a bit like primitives, but not). String and all the collections are classes, hence the methods to get size, length or similar things.
I guess the reason at the time of the design was performance. If they created it today they had probably come up with something like array-backed collection classes instead.
If anyone is interested, here is a small snippet of code to illustrate the difference between the two in generated code, first the source:
public class LengthTest {
public static void main(String[] args) {
int[] array = {12,1,4};
String string = "Hoo";
System.out.println(array.length);
System.out.println(string.length());
}
}
Cutting a way the not so important part of the byte code, running javap -c
on the class results in the following for the two last lines:
20: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
23: aload_1
24: arraylength
25: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
28: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
31: aload_2
32: invokevirtual #5; //Method java/lang/String.length:()I
35: invokevirtual #4; //Method java/io/PrintStream.println:(I)V
In the first case (20-25) the code just asks the JVM for the size of the array (in JNI this would have been a call to GetArrayLength()) whereas in the String case (28-35) it needs to do a method call to get the length.
In the mid 1990s, without good JITs and stuff, it would have killed performance totally to only have the java.util.Vector (or something similar) and not a language construct which didn't really behave like a class but was fast. They could of course have masked the property as a method call and handled it in the compiler but I think it would have been even more confusing to have a method on something that isn't a real class.
In case you would like to use timeout middleware and exclude a specific route:
var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests
app.use('/my_route', function(req, res, next) {
req.clearTimeout(); // clear request timeout
req.setTimeout(20000); //set a 20s timeout for this request
next();
}).get('/my_route', function(req, res) {
//do something that takes a long time
});
You should be able to use the format method:
"Location: {0:20} Revision {1}".format(Location,Revision)
You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines.
I'm completely revising my original answer because of points raised in the other questions and comments. Here is the new benchmark script:
import time
import numpy as np
def fancy_index_relu(m):
m[m < 0] = 0
relus = {
"max": lambda x: np.maximum(x, 0),
"in-place max": lambda x: np.maximum(x, 0, x),
"mul": lambda x: x * (x > 0),
"abs": lambda x: (abs(x) + x) / 2,
"fancy index": fancy_index_relu,
}
for name, relu in relus.items():
n_iter = 20
x = np.random.random((n_iter, 5000, 5000)) - 0.5
t1 = time.time()
for i in range(n_iter):
relu(x[i])
t2 = time.time()
print("{:>12s} {:3.0f} ms".format(name, (t2 - t1) / n_iter * 1000))
It takes care to use a different ndarray for each implementation and iteration. Here are the results:
max 126 ms
in-place max 107 ms
mul 136 ms
abs 86 ms
fancy index 132 ms
I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.
Something like this should work:
for line in infile:
next_lines = []
if line.strip():
for i in xrange(4):
try:
next_lines.append(infile.next())
except StopIteration:
break
# Do your calculation with "4 lines" here
Check out the Programmatically Displaying the Settings Page
startActivity(context, new Intent(Settings.ACTION_SETTINGS), /*options:*/ null);
In general, you use the predefined constant Settings.ACTION__SETTINGS
. The full list can be found here
I noticed a very anoying gotcha in moving to scss files!!! One MUST move from a simple: styleUrls: ['app.component.scss']
to styleUrls: ['./app.component.scss']
(add ./
) in app.component.ts
Which ng does when you generate a new project, but seemingly not when the default project is created. If you see resolve errors during ng build, check for this issue. It only took me ~ 1 hour.
If you want a "const string" like your question says, I would really go for the version you stated in your question:
/* first version */
const char *HELLO2 = "Howdy";
Particularly, I would avoid:
/* second version */
const char HELLO2[] = "Howdy";
Reason: The problem with second version is that compiler will make a copy of the entire string "Howdy", PLUS that string is modifiable (so not really const).
On the other hand, first version is a const string accessible by const pointer HELLO2, and there is no way anybody can modify it.
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);
}
There is a variation of private variables in the underscore convention.
In [5]: class Test(object):
...: def __private_method(self):
...: return "Boo"
...: def public_method(self):
...: return self.__private_method()
...:
In [6]: x = Test()
In [7]: x.public_method()
Out[7]: 'Boo'
In [8]: x.__private_method()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-fa17ce05d8bc> in <module>()
----> 1 x.__private_method()
AttributeError: 'Test' object has no attribute '__private_method'
There are some subtle differences, but for the sake of programming pattern ideological purity, its good enough.
There are examples out there of @private decorators that more closely implement the concept, but YMMV. Arguably one could also write a class defintion that uses meta
What I do is have a static class with the following code in my project:
#region Dataset -> Immediate Window
public static void printTbl(DataSet myDataset)
{
printTbl(myDataset.Tables[0]);
}
public static void printTbl(DataTable mytable)
{
for (int i = 0; i < mytable.Columns.Count; i++)
{
Debug.Write(mytable.Columns[i].ToString() + " | ");
}
Debug.Write(Environment.NewLine + "=======" + Environment.NewLine);
for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
{
for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
{
Debug.Write(mytable.Rows[rrr][ccc] + " | ");
}
Debug.Write(Environment.NewLine);
}
}
public static void ResponsePrintTbl(DataTable mytable)
{
for (int i = 0; i < mytable.Columns.Count; i++)
{
HttpContext.Current.Response.Write(mytable.Columns[i].ToString() + " | ");
}
HttpContext.Current.Response.Write("<BR>" + "=======" + "<BR>");
for (int rrr = 0; rrr < mytable.Rows.Count; rrr++)
{
for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
{
HttpContext.Current.Response.Write(mytable.Rows[rrr][ccc] + " | ");
}
HttpContext.Current.Response.Write("<BR>");
}
}
public static void printTblRow(DataSet myDataset, int RowNum)
{
printTblRow(myDataset.Tables[0], RowNum);
}
public static void printTblRow(DataTable mytable, int RowNum)
{
for (int ccc = 0; ccc < mytable.Columns.Count; ccc++)
{
Debug.Write(mytable.Columns[ccc].ToString() + " : ");
Debug.Write(mytable.Rows[RowNum][ccc]);
Debug.Write(Environment.NewLine);
}
}
#endregion
I then I will call one of the above functions in the immediate window and the results will appear there as well. For example if I want to see the contents of a variable 'myDataset' I will call printTbl(myDataset). After hitting enter, the results will be printed to the immediate window
Numpy solution. We will shuffle the whole dataset first (df.sample(frac=1, random_state=42)
) and then split our data set into the following parts:
In [305]: train, validate, test = \
np.split(df.sample(frac=1, random_state=42),
[int(.6*len(df)), int(.8*len(df))])
In [306]: train
Out[306]:
A B C D E
0 0.046919 0.792216 0.206294 0.440346 0.038960
2 0.301010 0.625697 0.604724 0.936968 0.870064
1 0.642237 0.690403 0.813658 0.525379 0.396053
9 0.488484 0.389640 0.599637 0.122919 0.106505
8 0.842717 0.793315 0.554084 0.100361 0.367465
7 0.185214 0.603661 0.217677 0.281780 0.938540
In [307]: validate
Out[307]:
A B C D E
5 0.806176 0.008896 0.362878 0.058903 0.026328
6 0.145777 0.485765 0.589272 0.806329 0.703479
In [308]: test
Out[308]:
A B C D E
4 0.521640 0.332210 0.370177 0.859169 0.401087
3 0.333348 0.964011 0.083498 0.670386 0.169619
[int(.6*len(df)), int(.8*len(df))]
- is an indices_or_sections
array for numpy.split().
Here is a small demo for np.split()
usage - let's split 20-elements array into the following parts: 80%, 10%, 10%:
In [45]: a = np.arange(1, 21)
In [46]: a
Out[46]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
In [47]: np.split(a, [int(.8 * len(a)), int(.9 * len(a))])
Out[47]:
[array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]),
array([17, 18]),
array([19, 20])]
The best way to do this is to sort the list before binding data source.
cars = cars.OrderBy(o => o.year).ThenBy(o => o.color).ToList();
adgCars.DataSource = cars;
Sorry for my bad english.
Try adding these two lines to your code. I hope it will work. It worked for me :)
display.setLineWrap(true);
display.setWrapStyleWord(true);
Picture of output is shown below
I think now Fragment nesting is available just update the back computability jar
now lets dig in the problem it self .
public void onClick2(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment1, fragment2);
fragmentTransaction.commit();
}
I think the R.id.fragment1
belongs to a TextView
which is not a good place to include child views in because its not a ViewGroup
, you can remove the textView
from the xml and replace it with a LinearLayout
lets say and it will work , if not tell me what the error .
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/fragment1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
/>
<Button
android:id="@+id/btn_frag2"
android:text="Call Fragment 2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Update for the error in the comment
public class Fragment1 extends Fragment implements OnClickListener{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
return v;
}
public void onClick(View view) {
Fragment2 fragment2 = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
You can now use the library called angular-print
One way is to use ANSI escape sequences:
import sys
import time
for i in range(10):
print("Loading" + "." * i)
sys.stdout.write("\033[F") # Cursor up one line
time.sleep(1)
Also sometimes useful (for example if you print something shorter than before):
sys.stdout.write("\033[K") # Clear to the end of line
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
create table a1
(weddingTable INT(3),
tableSeat INT(3),
tableSeatID INT(6),
Name varchar(10));
insert into a1
(weddingTable, tableSeat, tableSeatID, Name)
values (001,001,001001,'Bob'),
(001,002,001002,'Joe'),
(001,003,001003,'Dan'),
(002,001,002001,'Mark');
create table a2
(weddingTable int(3),
tableSeat int(3),
Meal varchar(10));
insert into a2
(weddingTable, tableSeat, Meal)
values
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');
select x.*, y.Meal
from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);
Wait until Powershell is executed and get the result in vbs
This is an improved version of the Omegastripes code Hide command prompt window when using Exec()
Splits the confused responses from cmd.exe into an array instead of putting everything into a hard-to-parse string.
In addition, if an error occurs during the execution of cmd.exe, a message about its occurrence will become known in vbs.
Option Explicit
Sub RunCScriptHidden()
strSignature = Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty strSignature, Me
objShell.Run ("""" & Replace(LCase(WScript.FullName), "wscript", "cscript") & """ //nologo """ & WScript.ScriptFullName & """ ""/signature:" & strSignature & """"), 0, True
End Sub
Sub WshShellExecCmd()
For Each objWnd In CreateObject("Shell.Application").Windows
If IsObject(objWnd.getProperty(WScript.Arguments.Named("signature"))) Then Exit For
Next
Set objParent = objWnd.getProperty(WScript.Arguments.Named("signature"))
objWnd.Quit
'objParent.strRes = CreateObject("WScript.Shell").Exec(objParent.strCmd).StdOut.ReadAll() 'simple solution
Set exec = CreateObject("WScript.Shell").Exec(objParent.strCmd)
While exec.Status = WshRunning
WScript.Sleep 20
Wend
Dim err
If exec.ExitCode = WshFailed Then
err = exec.StdErr.ReadAll
Else
output = Split(exec.StdOut.ReadAll,Chr(10))
End If
If err="" Then
objParent.strRes = output(UBound(output)-1) 'array of results, you can: output(0) Join(output) - Usually needed is the last
Else
objParent.wowError = err
End If
WScript.Quit
End Sub
Const WshRunning = 0,WshFailed = 1:Dim i,name,objShell
Dim strCmd, strRes, objWnd, objParent, strSignature, wowError, output, exec
Set objShell = WScript.CreateObject("WScript.Shell"):wowError=False
strCmd = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass Write-Host Hello-World."
If WScript.Arguments.Named.Exists("signature") Then WshShellExecCmd
RunCScriptHidden
If wowError=False Then
objShell.popup(strRes)
Else
objShell.popup("Error=" & wowError)
End If
you don't.
the constructor is part of the class that can implement an interface. The interface is just a contract of methods the class must implement.
Your going to use the checkbox1.checked
property in your if statement, this returns true or false depending on weather it is checked or not.
Think of it like this:
Whenever you create an object in ECMAscript, this object is formed in a mystique ECMAscript universal place where no man will ever be able to get. All you get back is a reference to that object in this mystique place.
var obj = { };
Even obj
is only a reference to the object (which is located in that special wonderful place) and hence, you can only pass this reference around. Effectively, any piece of code which accesses obj will modify the object which is far, far away.
You can't really force the optimizer to do anything, but you can guide it.
UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93
$user->data
is an array of objects. Each element in the array has a name
and value
property (as well as others).
Try putting the 2nd foreach
inside the 1st.
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
Here's my solution when working with hex integers and not hex strings:
def convert_hex_to_ascii(h):
chars_in_reverse = []
while h != 0x0:
chars_in_reverse.append(chr(h & 0xFF))
h = h >> 8
chars_in_reverse.reverse()
return ''.join(chars_in_reverse)
print convert_hex_to_ascii(0x7061756c)
Added below "Conclusion" paragraph
I've went down the pipenv
rabbit hole (it's a deep and dark hole indeed...) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I've found.
This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It's about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.
As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: "Changed in version 3.5: The use of venv is now recommended for creating virtual environments".
pipenv- like venv - can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt
, pipenv
delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile
is to supplant requirements.txt
.
HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.
So if settling on a virtual envelope solution wasn't difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.
The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:
prefer built-in venv: if the target python has venv we'll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)
So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv- which uses virtualenv
- varies materially from venv
.
Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.
An oft repeated criticism of Pipenv I saw when producing this analysis was that it was not actively maintained. Indeed, what's the point of using a solution whose future could be seen questionable due to lack of continuous development? After a dry spell of about 18 months, Pipenv is once again being actively developed. Indeed, large and material updates have since been released.
I don't think this is possible in Sequelize's order clause, because as far as I can tell, those clauses are meant to be binary operations applicable to every element in your list. (This makes sense, too, as it's generally how sorting a list works.)
So, an order clause can do something like order a list by recursing over it asking "which of these 2 elements is older?" Whereas your ordering is not reducible to a binary operation (compare_bigger(1,2) => 2
) but is just an arbitrary sequence (2,4,11,2,9,0
).
When I hit this issue with findAll
, here was my solution (sub in your returned results for numbers
):
var numbers = [2, 20, 23, 9, 53];
var orderIWant = [2, 23, 20, 53, 9];
orderIWant.map(x => { return numbers.find(y => { return y === x })});
Which returns [2, 23, 20, 53, 9]
. I don't think there's a better tradeoff we can make. You could iterate in place over your ordered ids with findOne
, but then you're doing n queries when 1 will do.
The original answer from https://github.com/philipwalton/flexbugs/issues/231#issuecomment-362790042
.flex-container{
min-height:100px;
display:flex;
align-items:center;
}
.flex-container:after{
content:'';
min-height:inherit;
font-size:0;
}
Why not just INNER JOIN the table with itself?
SELECT a.firstname, a.lastname, a.address
FROM list a
INNER JOIN list b ON a.address = b.address
WHERE a.id <> b.id
A DISTINCT is needed if the address could exist more than two times.
I think this is what you need:
At first you need to install sshpass
on your machine.
then you can write your own script:
while read pass port user ip; do
sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
COMMAND 1
.
.
.
COMMAND n
ENDSSH1
done <<____HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
____HERE
What's the difference: See other answers.
When use +
instead of %20
? Use +
if, for some reason, you want to make the URL query string (?.....
) or hash fragment (#....
) more readable. Example: You can actually read this:
https://www.google.se/#q=google+doesn%27t+encode+:+and+uses+%2B+instead+of+spaces
(%2B
= +)
But the following is a lot harder to read: (at least to me)
I would think +
is unlikely to break anything, since Google uses +
(see the 1st link above) and they've probably thought about this. I'm going to use +
myself just because readable + Google thinks it's OK.
Although converting the ArrayList
to a HashSet
effectively removes duplicates, if you need to preserve insertion order, I'd rather suggest you to use this variant
// list is some List of Strings
Set<String> s = new LinkedHashSet<>(list);
Then, if you need to get back a List
reference, you can use again the conversion constructor.
On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:
view.settings().get('font_face')
You will find your default font.
Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\
. One of these must be true:
Version
value in that key should be 3.5.30729.01SP
value in the same key should be 1In C# (taken from the first comment), you could do something along these lines:
const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();
This works for me. Hope it will work for you too.
ScriptManager.RegisterStartupScript(this, this.GetType(), "isActive", "Test();", true);
I have edited the html page which you have provided. The updated page is as below
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>My Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function Test() {
alert("Hello Test!!!!");
$('#ButtonRow').css("display", "block");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:RadioButtonList ID="SearchCategory" runat="server" RepeatDirection="Horizontal"
BorderStyle="Solid">
<asp:ListItem>Merchant</asp:ListItem>
<asp:ListItem>Store</asp:ListItem>
<asp:ListItem>Terminal</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr id="ButtonRow" style="display: none">
<td>
<asp:Button ID="MyButton" runat="server" Text="Click Here" OnClick="MyButton_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$("#<%=SearchCategory.ClientID%> input").change(function () {
alert("hi");
$("#ButtonRow").show();
});
</script>
You need the textFX plugin. Then, just follow these instructions:
Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.
Personally, I would use sort -i -u source >dest instead of notepad++
You can use this with only two parameter
function whatever($array, $val) {
foreach ($array as $item)
if (isset($item) && in_array($val,$item))
return 1;
return 0;
}
From this post: How to deal with floating point number precision in JavaScript?
You have a few options:
(Math.floor(y/x) * x).toFixed(2)
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
Based on Nicolas Gauthier answer:
var strng = 'someobj.someCallback';
var data = 'someData';
var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
//We maybe can check typeof and break the bucle if typeof != function
func = func[funcSplit[i]];
}
func(data);
Recursive way to retrieve all the errors from an Angular form, after creating any kind of formulary structure there's no way to retrieve all the errors from the form. This is very useful for debugging purposes but also for plotting those errors.
Tested for Angular 9
getFormErrors(form: AbstractControl) {
if (form instanceof FormControl) {
// Return FormControl errors or null
return form.errors ?? null;
}
if (form instanceof FormGroup) {
const groupErrors = form.errors;
// Form group can contain errors itself, in that case add'em
const formErrors = groupErrors ? {groupErrors} : {};
Object.keys(form.controls).forEach(key => {
// Recursive call of the FormGroup fields
const error = this.getFormErrors(form.get(key));
if (error !== null) {
// Only add error if not null
formErrors[key] = error;
}
});
// Return FormGroup errors or null
return Object.keys(formErrors).length > 0 ? formErrors : null;
}
}
Try the following snippet. You can call the the below stored procedure from your application, so that NoOfUses
in the coupon table will be updated.
CREATE PROCEDURE [dbo].[sp_UpdateCouponCount]
AS
Declare @couponCount int,
@CouponName nvarchar(50),
@couponIdFromQuery int
Declare curP cursor For
select COUNT(*) as totalcount , Name as name,couponuse.couponid as couponid from Coupon as coupon
join CouponUse as couponuse on coupon.id = couponuse.couponid
where couponuse.id=@cuponId
group by couponuse.couponid , coupon.Name
OPEN curP
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
While @@Fetch_Status = 0 Begin
print @couponCount
print @CouponName
update Coupon SET NoofUses=@couponCount
where couponuse.id=@couponIdFromQuery
Fetch Next From curP Into @couponCount, @CouponName,@couponIdFromQuery
End -- End of Fetch
Close curP
Deallocate curP
Hope this helps!
zoom is a css3 spec for the @viewport descriptor, as described here
http://dev.w3.org/csswg/css-device-adapt/#zoom-desc
used to zoom the entire viewport ('screen'). it also happens to zoom individuals elements in a lot of browsers, but not all. css3 specifies transform:scale should be used to achieve such an effect:
http://www.w3.org/TR/css3-transforms/#transform-functions
but it works a little different than the 'element zoom' in those browsers that support it.
I had similar issue for android-29. My issue occurred because when AS was unzipping one downloaded SDK I had stopped it. For solving the issue disable gradle offline mode then sync with gradle files. You may need to set proxy and enable it.
Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2
in dependency section of your build.gradl
e .
To download ISIN code data the only place I see this is on the ISIN organizations website, www.isin.org. try http://isin.org, they should have a function where you can easily download.
In case of a List of type Long, Adding L to end of each Integer value
List<Long> list = new ArrayList<Long>();
list = Arrays.asList(1L, 2L, 3L, 4L);
I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.
Validating it is a valid address is one thing.
But if you're trying to validate a given person lives at a given address, your only almost-guarantee would be a test mail to the address, and even that is not certain if the person is organised or knows somebody at that address.
Otherwise people could just specify an arbitrary random address which they know exists and it would mean nothing to you.
The best you can do for immediate results is request the user send a photographed / scanned copy of the head of their bank statement or some other proof-of-recent-residence, because at least then they have to work harder to forget it, and forging said things show up easily with a basic level of image forensic analysis.
If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.
CREATE TABLE #Table(C1 int,
C2 NVarchar(100) , C3 varchar(100)
UNIQUE CLUSTERED (c1)
);
Create table with unique clustered index
Insert data into Temp "#Table" table
Create non clustered indexes.
CREATE NONCLUSTERED INDEX IX1 ON #Table (C2,C3);
` Please include either of these:
`#include<sstream>`
using std::istringstream;
This is because you have not compiled it. Click 'Project > compile'. Then, either click 'start debugging', or 'start without debugging'.
Hope this will help you
Cast(columnName as Numeric(10,2))
or
Cast(@s as decimal(10,2))
I am not getting why you want to cast to varchar?.If you cast to varchar again convert back to decimail for two
decimal points
work for me...
<android.support.v7.widget.Toolbar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/toolBar"
android:background="@color/colorGreen"
app:title="Title"
app:titleTextColor="@color/colorBlack"
app:navigationIcon="@drawable/ic_action_back"/>
insert into run(id,name,dob)values(&id,'&name',[what should I write here?]);
insert into run(id,name,dob)values(&id,'&name',TO_DATE('&dob','YYYY-MM-DD'));
there is another technique
use
background-size:cover
That is it full set of css is
body {
background: url('images/body-bg.jpg') no-repeat center center fixed;
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Latest browsers support the default property.
The current(initial) directory of shell script is the directory from which you have called the script.
As you've discovered, you can't do that. You can do:
libtest_LIBS =
...
if HAVE_CLIENT
libtest_LIBS += libclient.la
endif
if HAVE_SERVER
libtest_LIBS += libserver.la
endif
How about using the CSS3 flex model:
HTML Code:
<div id="wrapper">
<div id="c1">c1</div>
<div id="c2">c2</div>
<div id="c3">c3</div>
</div>
CSS Code:
*{
margin:0;
padding:0;
}
#wrapper{
display:-webkit-flex;
-webkit-justify-content:center;
display:flex;
justify-content:center;
}
#wrapper div{
-webkit-flex:1;
flex:1;
border:thin solid #777;
}
First up, you seem to be mixing table variables and tables.
Either way, You can't pass in the table's name like that. You would have to use dynamic TSQL to do that.
If you just want to declare a table variable:
CREATE PROC sp_createATable
@name VARCHAR(10),
@properties VARCHAR(500)
AS
declare @tablename TABLE
(
id CHAR(10) PRIMARY KEY
);
The fact that you want to create a stored procedure to dynamically create tables might suggest your design is wrong.
Nothing can be more simple than this
#include <stdio.h>
int main()
{
int i;
for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/
{
printf("ASCII value of character %c = %d\n", i, i);
}
return 0;
}
If you prefer to edit the file php.ini
in your favorite editor than the Editor created by MAMP, you would need to stop the Servers first.
Then head to Library->Application Support->appsolute->MAMP PRO->templates->php{version_number}.ini.temp
and effect any change you would want to have especially the below
max_execution_time = 3000
max_input_time = 60
memory_limit = 128M
post_max_size = 256M
upload_max_filesize 256M
And also make changes in your PHPMyAdmin if it is what you are using in Cpanel.
$cfg['ExecTimeLimit'] = 300;
Make sure you make a copy of the original file. You can navigate under conf
!here
You can try this if you want to override
var newArray= [444,555,666];
var oldArray =[11,22,33];
oldArray.forEach((name, index) => oldArray [index] = newArray[index]);
console.log(newArray);
Below are the steps to install Android Studio in Ubuntu system:
1. Install JDK 6 or later
First, install Oracle JDK 8 (although you could also choose OpenJDK but it has some UI/performance issues) using WebUpd8 PPA.
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
sudo apt-get install oracle-java8-set-default
To make sure, it’s installed successfully, open a terminal and type (you should get the version number of the jdk you’ve installed e.g javac 1.8.0_11)
javac -version
2. Download and install Android Studio
Download the Android Studio package for Linux and extract it somewhere (e.g home directory). Then type :
cd android-studio/bin
./studio.sh
3. Install SDK Platforms
You need to install some SDK before you jump into building android apps. Click on Configure -> SDK Manage
r to open Android SDK Manager. Select the latest API (to test against target build, e.g API 19 (Android 4.4.2)) and some packages in Extras (Android Support Library and Android Support Repository). Then install the selected packages.
I`d like to add to the already good answers:
The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".
Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!
int main ()
{
std::cout << "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
std::cout << "true - false = " << true - false << std::endl;
std::cout << "false - true = " << false - true << std::endl;
std::cout << "false - false = " << false - false << std::endl << std::endl;
std::cout << "true + true = " << true + true << std::endl;
std::cout << "true + false = " << true + false << std::endl;
std::cout << "false + true = " << false + true << std::endl;
std::cout << "false + false = " << false + false << std::endl << std::endl;
std::cout << "true * true = " << true * true << std::endl;
std::cout << "true * false = " << true * false << std::endl;
std::cout << "false * true = " << false * true << std::endl;
std::cout << "false * false = " << false * false << std::endl << std::endl;
std::cout << "true / true = " << true / true << std::endl;
// std::cout << true / false << std::endl; ///-Wdiv-by-zero
std::cout << "false / true = " << false / true << std::endl << std::endl;
// std::cout << false / false << std::endl << std::endl; ///-Wdiv-by-zero
std::cout << "(true || true) = " << (true || true) << std::endl;
std::cout << "(true || false) = " << (true || false) << std::endl;
std::cout << "(false || true) = " << (false || true) << std::endl;
std::cout << "(false || false) = " << (false || false) << std::endl << std::endl;
std::cout << "(true && true) = " << (true && true) << std::endl;
std::cout << "(true && false) = " << (true && false) << std::endl;
std::cout << "(false && true) = " << (false && true) << std::endl;
std::cout << "(false && false) = " << (false && false) << std::endl << std::endl;
}
yields :
true - true = 0
true - false = 1
false - true = -1
false - false = 0
true + true = 2
true + false = 1
false + true = 1
false + false = 0
true * true = 1
true * false = 0
false * true = 0
false * false = 0
true / true = 1
false / true = 0
(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0
(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0
It can also be done using the IsSelected property of the TreeView item. Here's how I managed it,
public delegate void TreeviewItemSelectedHandler(TreeViewItem item);
public class TreeViewItem
{
public static event TreeviewItemSelectedHandler OnItemSelected = delegate { };
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
if (value)
OnItemSelected(this);
}
}
}
Then in the ViewModel that contains the data your TreeView is bound to, just subscribe to the event in the TreeViewItem class.
TreeViewItem.OnItemSelected += TreeViewItemSelected;
And finally, implement this handler in the same ViewModel,
private void TreeViewItemSelected(TreeViewItem item)
{
//Do something
}
And the binding of course,
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
if( strpos( $url, $word ) !== false ) {
// Do something
}
import { AfterViewInit, Component, ElementRef} from '@angular/core';
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.querySelector('my-element')
.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
console.log(event);
}
Read this if you are populating your mat-select asyncronously via an http request.
If you are using a service to make an api call to return the mat-select options values, you must set the 'selected value' on your form control as part of the 'complete' section of your service api call subscribe().
For example:
this.customerService.getCustomers().subscribe(
customers => this.customers = customers ,
error => this.errorMessage = error as any,
() => this.customerSelectControl.setValue(this.mySelectedValue));
I had ran into this similar problem as well. In my case, my resolution is quite different. Here's my spring context xml file:
...
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
...
I'm not specifying any xsd version as I want spring to use the latest xsd version inside spring dependencies. The spring version my application used was spring-beans-4.3.1.RELEASE.jar:4.3.1.RELEASE and when I assembly my application into jar, all spring dependencies exist in my classpath. However, I received following error during startup of my spring application context:
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.springframework.org/schema/beans/spring-beans.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
After some hard time troubleshooting, I found the issue is due to the index.list inside the META-INF folder of my jar file. With index.list file, spring namespace handlers cannot be located to parse the spring application context xml correctly. You can read more about this spring issue SPR-5705
By removing indexing from my maven-jar-plugin, I manage to resolve the issue. Hope this will save some times for people having the same problem.
GridView
is used for implementing material grid lists. If you know you have a fixed number of items and it's not very many (16 is fine), you can use GridView.count
. However, you should note that a GridView
is scrollable, and if that isn't what you want, you may be better off with just rows and columns.
import 'dart:collection';
import 'package:flutter/scheduler.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/foundation.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.orange,
),
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
title: new Text('Grid Demo'),
),
body: new GridView.count(
crossAxisCount: 4,
children: new List<Widget>.generate(16, (index) {
return new GridTile(
child: new Card(
color: Colors.blue.shade200,
child: new Center(
child: new Text('tile $index'),
)
),
);
}),
),
);
}
}
You may use AddWithValue
method like:
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();
OR
Try with ?
instead of @
, like:
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(?person, ?address)";
comm.Parameters.Add("?person", "Myname");
comm.Parameters.Add("?address", "Myaddress");
comm.ExecuteNonQuery();
conn.Close();
Hope it helps...
You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.
If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.
CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);
The bellow link contains the code that read a piece of file easily:
Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
using(SqlCommand cmd = new SqlCommand(sql,connection))
{
cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;
cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
That doesn't work because distToPoint
is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p)
. You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p)
.
If you're having problems related to dependencies not appearing in the WEB-INF/lib file when running on a Tomcat server in Eclipse, take a look at this:
You simply had to add the Maven Dependencies in Project Properties > Deployment Assembly.
From this forum:
parseInt()
returns primitive integer type (int), wherebyvalueOf
returns java.lang.Integer, which is the object representative of the integer. There are circumstances where you might want an Integer object, instead of primitive type.Of course, another obvious difference is that intValue is an instance method whereby parseInt is a static method.
I successfully used "soap" package (https://www.npmjs.com/package/soap) on more than 10 tracking WebApis (Tradetracker, Bbelboon, Affilinet, Webgains, ...).
Problems usually come from the fact that programmers does not investigate to much about what remote API needs in order to connect or authenticate.
For instance PHP resends cookies from HTTP headers automatically, but when using 'node' package, it have to be explicitly set (for instance by 'soap-cookie' package)...
Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc
I wrote this function:
public static String encode(@NonNull String uriString) {
if (TextUtils.isEmpty(uriString)) {
Assert.fail("Uri string cannot be empty!");
return uriString;
}
// getQueryParameterNames is not exist then cannot iterate on queries
if (Build.VERSION.SDK_INT < 11) {
return uriString;
}
// Check if uri has valid characters
// See https://tools.ietf.org/html/rfc3986
Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
"=-]|%[0-9a-fA-F]{2})+");
Matcher matcher = allowedUrlCharacters.matcher(uriString);
String validUri = null;
if (matcher.find()) {
validUri = matcher.group();
}
if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
return uriString;
}
// The uriString is not encoded. Then recreate the uri and encode it this time
Uri uri = Uri.parse(uriString);
Uri.Builder uriBuilder = new Uri.Builder()
.scheme(uri.getScheme())
.authority(uri.getAuthority());
for (String path : uri.getPathSegments()) {
uriBuilder.appendPath(path);
}
for (String key : uri.getQueryParameterNames()) {
uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
}
String correctUrl = uriBuilder.build().toString();
return correctUrl;
}
The best way depends on whether you have a project with a package manager like npm.
Package manager
If you're using a package manager, use it to get popper.js like this:
npm install popper.js --save
CDN
For a prototype or playground environment (like http://codepen.io) or may just want a url to a CDN file:
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js
note: Bootstrap 4 requires the versions under the umd path (more info on popper/bs4).
Local file
Just save one of the CDN files to use locally. For example, paste one of these URLs in a browser, then Save As... to get a local copy.
https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.js https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.5/umd/popper.min.js
For checking one date is after another by using isAfter()
method.
moment('2020-01-20').isAfter('2020-01-21'); // false
moment('2020-01-20').isAfter('2020-01-19'); // true
For checking one date is before another by using isBefore()
method.
moment('2020-01-20').isBefore('2020-01-21'); // true
moment('2020-01-20').isBefore('2020-01-19'); // false
For checking one date is same as another by using isSame()
method.
moment('2020-01-20').isSame('2020-01-21'); // false
moment('2020-01-20').isSame('2020-01-20'); // true
I had the exact same problem with my instance. My problem was that I forgot to allow port 80 access to the server. Maybe that's your issue as well?
Check with your WHM and make sure that port is open for the IP address of your site,
There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils
now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");
I think this needs benchmarking. Using OP's original DataFrame,
df = pd.DataFrame({
'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': range(1, 7) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]
})
As commented on his answer, Andy takes full advantage of vectorisation and pandas indexing.
c = df.groupby(['state', 'office_id'])['sales'].sum().rename("count")
c / c.groupby(level=0).sum()
3.42 ms ± 16.7 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)
state_office = df.groupby(['state', 'office_id']).agg({'sales': 'sum'})
state = df.groupby(['state']).agg({'sales': 'sum'})
state_office.div(state, level='state') * 100
4.66 ms ± 24.4 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)
This is the slowest answer as it calculates x.sum()
for each x
in level 0.
For me, this is still a useful answer, though not in its current form. For quick EDA on smaller datasets, apply
allows you use method chaining to write this in a single line. We therefore remove the need decide on a variable's name, which is actually very computationally expensive for your most valuable resource (your brain!!).
Here is the modification,
(
df.groupby(['state', 'office_id'])
.agg({'sales': 'sum'})
.groupby(level=0)
.apply(lambda x: 100 * x / float(x.sum()))
)
10.6 ms ± 81.5 µs per loop
(mean ± std. dev. of 7 runs, 100 loops each)
So no one is going care about 6ms on a small dataset. However, this is 3x speed up and, on a larger dataset with high cardinality groupbys this is going to make a massive difference.
Adding to the above code, we make a DataFrame with shape (12,000,000, 3) with 14412 state categories and 600 office_ids,
import string
import numpy as np
import pandas as pd
np.random.seed(0)
groups = [
''.join(i) for i in zip(
np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
np.random.choice(np.array([i for i in string.ascii_lowercase]), 30000),
)
]
df = pd.DataFrame({'state': groups * 400,
'office_id': list(range(1, 601)) * 20000,
'sales': [np.random.randint(100000, 999999)
for _ in range(12)] * 1000000
})
Using Andy's,
2 s ± 10.4 ms per loop
(mean ± std. dev. of 7 runs, 1 loop each)
and exp1orer
19 s ± 77.1 ms per loop
(mean ± std. dev. of 7 runs, 1 loop each)
So now we see x10 speed up on large, high cardinality datasets.
Be sure to UV these three answers if you UV this one!!
For professional and nice looking buttons, you may check this custom button component. You can use it directly in your views and tableviews or modify the source code to make it meet your needs. Hope this helps.
In my case, I had an invalid package name. I wasn't able to pick up on the error code right away, because I didn't scroll up far enough, but the error was:
remote: $ NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client
remote: npm ERR! code EINVALIDPACKAGENAME // <-- this was hard to find
remote: npm ERR! Invalid package name "react-loader-spinne r": name can only contain URL-friendly characters
Normally, it should work.
But can you try this? I don't have SQL on my home PC, I can't try myself
UPDATE table
SET EndDate = '2009-05-25 00:00:00.000'
WHERE Id = 1
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
here's another way just to see the indices in the db:
curl -sG somehost-dev.example.com:9200/_status --user "credentials:password" | sed 's/,/\n/g' | grep index | grep -v "size_in" | uniq
{ "index":"tmpdb"}
{ "index":"devapp"}
There are three likely causes for this error message
For more detail read >>
Cause 2 :
SET GLOBAL interactive_timeout=60;
from its default of 30 seconds to 60 seconds or longer
Cause 3 :
SET GLOBAL connect_timeout=60;
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
sys.path
might include items that aren't specifically in your PYTHONPATH
environment variable. To query the variable directly, use:
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
I was trying to connect an old phone that I use to test apps on older API versions. Today adb was not finding it.
After trying pretty much everything here, I figured out that the phone was not even showing the system notification about the USB connection going on.
So I looked around for that issue, and found the solution here (credits to the original source):
- Remove phone from PC and remove battery to shut off phone.
- Plug USB cable into PC.
- Plug USB cable (other end) into phone.
- The PC install new hardware appropriate drivers for a few minutes (phone without battery)
- Unplug USB cable from phone
- Put battery back in and turn on phone
- As the phone boots, hold down Volume up and down. Phone boots into safe mode.
- Plug USB cable into phone.
- I saw notification about USB MTP-connecting on the phone. PC have found my phone!
- After the reboot in normal mode problem was fixed
Not sure step 4. is of any use here on macOS, however I did all the steps and it worked well.
SELECT owner, table_name
FROM dba_constraints
WHERE constraint_name = <<your constraint name>>
will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS
view, ALL_CONSTRAINTS
or USER_CONSTRAINTS
should work as well.
For DataTables >=1.10, use:
$('table').dataTable({searching: false, paging: false, info: false});
For DataTables <1.10, use:
$('table').dataTable({bFilter: false, bInfo: false});
or using pure CSS:
.dataTables_filter, .dataTables_info { display: none; }
This Python-script[*] does exactly that:
"""
Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.
First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and
if not accessible due to admin-rights missing, fails-back
to HKEY_CURRENT_USER.
Write and Delete operations do not proceed to user-tree if all-users succeed.
Syntax:
{prog} : Print all env-vars.
{prog} VARNAME : Print value for VARNAME.
{prog} VARNAME VALUE : Set VALUE for VARNAME.
{prog} +VARNAME VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`).
{prog} -VARNAME : Delete env-var value.
Note that the current command-window will not be affected,
changes would apply only for new command-windows.
"""
import winreg
import os, sys, win32gui, win32con
def reg_key(tree, path, varname):
return '%s\%s:%s' % (tree, path, varname)
def reg_entry(tree, path, varname, value):
return '%s=%s' % (reg_key(tree, path, varname), value)
def query_value(key, varname):
value, type_id = winreg.QueryValueEx(key, varname)
return value
def yield_all_entries(tree, path, key):
i = 0
while True:
try:
n,v,t = winreg.EnumValue(key, i)
yield reg_entry(tree, path, n, v)
i += 1
except OSError:
break ## Expected, this is how iteration ends.
def notify_windows(action, tree, path, varname, value):
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)
def manage_registry_env_vars(varname=None, value=None):
reg_keys = [
('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
('HKEY_CURRENT_USER', r'Environment'),
]
for (tree_name, path) in reg_keys:
tree = eval('winreg.%s'%tree_name)
try:
with winreg.ConnectRegistry(None, tree) as reg:
with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
if not varname:
for regent in yield_all_entries(tree_name, path, key):
print(regent)
else:
if not value:
if varname.startswith('-'):
varname = varname[1:]
value = query_value(key, varname)
winreg.DeleteValue(key, varname)
notify_windows("Deleted", tree_name, path, varname, value)
break ## Don't propagate into user-tree.
else:
value = query_value(key, varname)
print(reg_entry(tree_name, path, varname, value))
else:
if varname.startswith('+'):
varname = varname[1:]
value = query_value(key, varname) + ';' + value
winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
notify_windows("Updated", tree_name, path, varname, value)
break ## Don't propagate into user-tree.
except PermissionError as ex:
print("!!!Cannot access %s due to: %s" %
(reg_key(tree_name, path, varname), ex), file=sys.stderr)
except FileNotFoundError as ex:
print("!!!Cannot find %s due to: %s" %
(reg_key(tree_name, path, varname), ex), file=sys.stderr)
if __name__=='__main__':
args = sys.argv
argc = len(args)
if argc > 3:
print(__doc__.format(prog=args[0]), file=sys.stderr)
sys.exit()
manage_registry_env_vars(*args[1:])
Below are some usage examples, assuming it has been saved in a file called setenv.py
somewhere in your current path.
Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:
> REM ## Print all env-vars
> setenv.py
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
HKEY_CURRENT_USER\Environment:PATH=...
...
> REM ## Query env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified
> REM ## Set env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo
> REM ## Append env-var:
> setenv.py +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar
> REM ## Delete env-var:
> setenv.py -PATH
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH
[*] Adapted from: http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/
One statement can be written as such:
someValues.forEach(x => console.log(x));
or multiple statements can be enclosed in {}
like this:
someValues.forEach(x => { let a = 2 + x; console.log(a); });
I usually overload my method with IEnumerable and IList in this situation.
public static IEnumerable<T> Method<T>( this IList<T> source ){... }
public static IEnumerable<T> Method<T>( this IEnumerable<T> source )
{
/*input checks on source parameter here*/
return Method( source.ToList() );
}
I take care to explain in the summary comments of the methods that calling IEnumerable will perform a .ToList().
The programmer can choose to .ToList() at a higher level if multiple operations are being concatenated and then call the IList overload or let my IEnumerable overload take care of that.
I struggled with this, too. My specific setup is: Your host.ini (with the modern names):
[test3]
test3-1 ansible_host=abc.def.ghi.pqr ansible_port=1212
test3-2 ansible_host=abc.def.ghi.stu ansible_port=1212
plus a play fill_file.yml
---
- remote_user: ec2-user
hosts: test3
tasks:
- name: fill file
template:
src: file.j2
dest: filled_file.txt
plus a template file.j2 , like
{% for host in groups['test3'] %}
{{ hostvars[host].ansible_host }}
{% endfor %}
This worked for me, the result is
abc.def.ghi.pqr
abc.def.ghi.stu
I have to admit it's ansible 2.7, not 2.1. The template is a variation of an example in https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html.
The accepted answer didn't work in my setup. With a template
{{ hostvars['test3'].ansible_host }}
my play fails with "AnsibleUndefinedVariable: \"hostvars['test3']\" is undefined" .
Remark: I tried some variations, but failed, occasionally with "ansible.vars.hostvars.HostVars object has no element "; Some of this might be explained by what they say. in https://github.com/ansible/ansible/issues/13343#issuecomment-160992631
hostvars emulates a dictionary [...]. hostvars is also lazily loaded
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
I'm using the latest Bootstrap 3 DateTime Picker (http://eonasdan.github.io/bootstrap-datetimepicker/)
This is how you should use DateTime Picker inline:
var selectedDate = $("#datetimepicker").find(".active").data("day");
The above returned: 03/23/2017
Another javascript library worth mentioning is pdfmake.
The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.
Simply use :
"SELECT * FROM `trees` WHERE LOWER(trees.`title`) LIKE '%elm%'";
Or Use
"SELECT * FROM `trees` WHERE LCASE(trees.`title`) LIKE '%elm%'";
Both functions works same
One-liner version of Ramana's answer.
python -c 'import pip, subprocess; [subprocess.call("pip install -U " + d.project_name, shell=1) for d in pip.get_installed_distributions()]'
Javascript is unpredictable and funny here.
onchange
occurs only when you blur the textboxonkeyup
& onkeypress
doesn't always occur on text changeonkeydown
occurs on text change (but cannot track cut & paste with mouse click)onpaste
& oncut
occurs with keypress and even with the mouse right click.So, to track the change in textbox, we need onkeydown
, oncut
and onpaste
. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.
This is a dirty hack but this is the only way, as I researched.
Here is an example. http://jsfiddle.net/2BfGC/12/
Using the Call Stack Window
To open the Call Stack window in Visual Studio, from the Debug menu, choose Windows>Call Stack. To set the local context to a particular row in the stack trace display, double click the first column of the row.
http://msdn.microsoft.com/en-us/library/windows/hardware/hh439516(v=vs.85).aspx
I'm adding this as I haven't seen it in any of the other answers and it might be useful for someone struggling with something similar. The globals()
function returns a mutable global symbol dictionary where you can "magically" make data available for the rest of your code.
For example:
from pickle import load
def loaditem(name):
with open(r"C:\pickle\file\location"+"\{}.dat".format(name), "rb") as openfile:
globals()[name] = load(openfile)
return True
and
from pickle import dump
def dumpfile(name):
with open(name+".dat", "wb") as outfile:
dump(globals()[name], outfile)
return True
Will just let you dump/load variables out of and into the global namespace. Super convenient, no muss, no fuss. Pretty sure it's Python 3 only.
You need to use view INFORMATION_SCHEMA.COLUMNS
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = my_table_name AND COLUMN_NAME like 'a%'
TO inline rows you can use PIVOT and for execution EXEC() function.
Simple solution:
<style>
.center {
margin: auto;
}
</style>
<div class="center">
<p> somthing goes here </p>
</div>
All the answers here use JSON objects. This gave us problems with the
$this->input->post()
methods of our Codeigniter controllers. The CI_Controller
cannot read JSON directly.
We used this method to do it WITHOUT JSON
func postRequest() {
// Create url object
guard let url = URL(string: yourURL) else {return}
// Create the session object
let session = URLSession.shared
// Create the URLRequest object using the url object
var request = URLRequest(url: url)
// Set the request method. Important Do not set any other headers, like Content-Type
request.httpMethod = "POST" //set http method as POST
// Set parameters here. Replace with your own.
let postData = "param1_id=param1_value¶m2_id=param2_value".data(using: .utf8)
request.httpBody = postData
// Create a task using the session object, to run and return completion handler
let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
guard error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
guard let serverData = data else {
print("server data error")
return
}
do {
if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
print("Response: \(requestJson)")
}
} catch let responseError {
print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
let message = String(bytes: serverData, encoding: .ascii)
print(message as Any)
}
// Run the task
webTask.resume()
}
Now your CI_Controller will be able to get param1
and param2
using $this->input->post('param1')
and $this->input->post('param2')
count the carriage returns/line feeds. I believe in unicode they are still 0x000D and 0x000A respectively. that way you can be as efficient or as inefficient as you want, and decide if you have to deal with both characters or not
In my case, i started device from genymotion and then started the device from Virtualbox as well. It helped me.
I know this is a bit late, but if this helps anybody, I think you could add a column to your data that calculates if the probability is ">='PivotSheet'$D$2"
(reference a cell on the pivot table
sheet).
Then, add that column to your pivot table and use the new column as a true/false
filter.
You can then change the value stored in the referenced cell to update your probability threshold.
If I understood your question right, this may get you what you wanted. The filter value would be displayed on the sheet with the pivot and can be changed to suit any quick changes to your probability threshold. The T/F Filter can be labeled "Above/At Probability Threshold" or something like that.
I've used this to do something similar. It was handy to have the cell reference on the Pivot table sheet so I could update the value and refresh the pivot to quickly modify the results. The people I did that for couldn't make up their minds on what that threshold should be.
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
There are 3 different methods depending on what I is my requirement and which version I am using.
Here are the methods..
1) Using Convert
DECLARE @DateTime DATETIME = GETDATE();
--Using Convert
SELECT
CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'
2) Using Cast (SQL Server 2008 and beyond)
SELECT
CAST(@DateTime AS DATETIME2) AS 'myDateTime'
,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
,CAST(@DateTime AS DATE) AS 'myDate'
,CAST(@DateTime AS TIME) AS 'myTime'
,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'
3) Using Fixed-length character data type
DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);
SELECT
@myDateTime AS 'myDateTime'
,@myDate AS 'myDate'
This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.
for row in df.itertuples(index=False, name=None):
for k,v in enumerate(row):
print("column: {0}".format(df.columns.values[k]))
print("value: {0}".format(v)
From what I know, respond_to is a method attached to the ActionController, so you can use it in every single controller, because all of them inherits from the ActionController. Here is the Rails respond_to method:
def respond_to(&block)
responder = Responder.new(self)
block.call(responder)
responder.respond
end
You are passing it a block, like I show here:
respond_to <<**BEGINNING OF THE BLOCK**>> do |format|
format.html
format.xml { render :xml => @whatever }
end <<**END OF THE BLOCK**>>
The |format| part is the argument that the block is expecting, so inside the respond_to method we can use that. How?
Well, if you notice we pass the block with a prefixed & in the respond_to method, and we do that to treat that block as a Proc. Since the argument has the ".xml", ".html" we can use that as methods to be called.
What we basically do in the respond_to class is call methods ".html, .xml, .json" to an instance of a Responder class.
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'xxx',
'smtp_pass' => 'xxx',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$result = $this->email->send();
From the CodeIgniter Forums
I modified the /etc/sysconfig/ip6tables-config
file changing:
IP6TABLES_SAVE_ON_STOP="no"
To:
IP6TABLES_SAVE_ON_STOP="yes"
And this:
IP6TABLES_SAVE_ON_RESTART="no"
To:
IP6TABLES_SAVE_ON_RESTART="yes"
This seemed to save the changes I made using the iptables commands through a reboot.
You can use define window.myvar = {}
.
When you want to use it, you can use like window.myvar = 1
To avoid hyphenation in already hyphenated word I used non-breaking space ~
in combination with backward space \!
. For example, command
3~\!\!\!\!-~\!\!\!D
used in the text, suppress hyphenation in word 3-D. Probably not the best solution, but it worked for me!
Strings are immutable, meaning their contents cannot change. When you call replace(this,that)
you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that)
or a new reference as seen below:
public class Test{
public static void main(String[] args) {
String sentence = "Define, Measure, Analyze, Design and Verify";
String replaced = sentence.replace("and", "");
System.out.println(replaced);
}
}
As an aside, note that I've removed the contains()
check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.
You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)
Check Creating github repositories with command line | Do it yourself Android for example usage.
Upto five team members it is free. Try it :)
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate
AngularJS extends this events-loop, creating something called AngularJS context
.
$watch()
Every time you bind something in the UI you insert a $watch
in a $watch
list.
User: <input type="text" ng-model="user" />
Password: <input type="password" ng-model="pass" />
Here we have $scope.user
, which is bound to the first input, and we have $scope.pass
, which is bound to the second one. Doing this we add two $watch
es to the $watch
list.
When our template is loaded, AKA in the linking phase, the compiler will look for every directive and creates all the $watch
es that are needed.
AngularJS provides $watch
, $watchcollection
and $watch(true)
. Below is a neat diagram explaining all the three taken from watchers in depth.
angular.module('MY_APP', []).controller('MyCtrl', MyCtrl)
function MyCtrl($scope,$timeout) {
$scope.users = [{"name": "vinoth"},{"name":"yusuf"},{"name":"rajini"}];
$scope.$watch("users", function() {
console.log("**** reference checkers $watch ****")
});
$scope.$watchCollection("users", function() {
console.log("**** Collection checkers $watchCollection ****")
});
$scope.$watch("users", function() {
console.log("**** equality checkers with $watch(true) ****")
}, true);
$timeout(function(){
console.log("Triggers All ")
$scope.users = [];
$scope.$digest();
console.log("Triggers $watchCollection and $watch(true)")
$scope.users.push({ name: 'Thalaivar'});
$scope.$digest();
console.log("Triggers $watch(true)")
$scope.users[0].name = 'Superstar';
$scope.$digest();
});
}
$digest
loopWhen the browser receives an event that can be managed by the AngularJS context the $digest
loop will be fired. This loop is made from two smaller loops. One processes the $evalAsync
queue, and the other one processes the $watch list
. The $digest
will loop through the list of $watch
that we have
app.controller('MainCtrl', function() {
$scope.name = "vinoth";
$scope.changeFoo = function() {
$scope.name = "Thalaivar";
}
});
{{ name }}
<button ng-click="changeFoo()">Change the name</button>
Here we have only one $watch
because ng-click doesn’t create any watches.
We press the button.
$digest
loop will run and will ask every $watch for changes.$watch
which was watching for changes in $scope.name
reports a change, it will force another $digest
loop.$digest
loop. That means that every time we write a letter in an input, the loop will run checking every $watch
in this page.If you call $apply
when an event is fired, it will go through the angular-context, but if you don’t call it, it will run outside it. It is as easy as that. $apply
will call the $digest()
loop internally and it will iterate over all the watches to ensure the DOM is updated with the newly updated value.
The $apply()
method will trigger watchers on the entire $scope
chain whereas the $digest()
method will only trigger watchers on the current $scope
and its children
. When none of the higher-up $scope
objects need to know about the local changes, you can use $digest()
.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
found = binarySearch(first, last, search4, &random);
Notice the &
.
New versions of Chrome have a feature called workspaces which addresses this issue. You can define which paths on your webserver correspond to which paths on your system, then edit and save with just ctrl-s.
See: http://www.html5rocks.com/en/tutorials/developertools/revolutions2013/
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
If you're trying to style dynamically added HTML elements inside an Angular component, this might be helpful:
// inside component class...
constructor(private hostRef: ElementRef) { }
getContentAttr(): string {
const attrs = this.hostRef.nativeElement.attributes
for (let i = 0, l = attrs.length; i < l; i++) {
if (attrs[i].name.startsWith('_nghost-c')) {
return `_ngcontent-c${attrs[i].name.substring(9)}`
}
}
}
ngAfterViewInit() {
// dynamically add HTML element
dynamicallyAddedHtmlElement.setAttribute(this.getContentAttr(), '')
}
My guess is that the convention for this attribute is not guaranteed to be stable between versions of Angular, so that one might run into problems with this solution when upgrading to a new version of Angular (although, updating this solution would likely be trivial in that case).
To expound more on @vrian's answer
To view the bootstrap version of a website in your web browser, do the following:
First Method:
boostrap.min.js
or boostrap.min.css
. It should look like this <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
Bootstrap v4.4.1 (https://getbootstrap.com/)
Second Method:
boostrap.min.css
Bootstrap v4.4.1 (https://getbootstrap.com/)
That's all
I hope this helps
To me its all about knowing your data. If I am continuing to expand my code on the basis of efficiency, I would have to choose the List option as a way of deciphering of my data w/o the unnecessary step of always wondering about types, especially 'Custom Types'. If the machine understands the difference and can determine on it's on what type of data I'm actually dealing with then why should I get in the way and waste time going thru the gyrations of 'IF THEN ELSE' determinations? My philosophy is to let the machine work for me instead of me working on the machine? Knowing the unique differences of different object code commands goes a long way in making your code as efficient.
Tom Johnson (One Entry ... One Exit)
The objdump
tool can tell you this information. If you invoke objdump
with the -x
option, to get it to output all headers then you'll find the shared object dependencies right at the start in the "Dynamic Section".
For example running objdump -x /usr/lib/libXpm.so.4
on my system gives the following information in the "Dynamic Section":
Dynamic Section:
NEEDED libX11.so.6
NEEDED libc.so.6
SONAME libXpm.so.4
INIT 0x0000000000002450
FINI 0x000000000000e0e8
GNU_HASH 0x00000000000001f0
STRTAB 0x00000000000011a8
SYMTAB 0x0000000000000470
STRSZ 0x0000000000000813
SYMENT 0x0000000000000018
PLTGOT 0x000000000020ffe8
PLTRELSZ 0x00000000000005e8
PLTREL 0x0000000000000007
JMPREL 0x0000000000001e68
RELA 0x0000000000001b38
RELASZ 0x0000000000000330
RELAENT 0x0000000000000018
VERNEED 0x0000000000001ad8
VERNEEDNUM 0x0000000000000001
VERSYM 0x00000000000019bc
RELACOUNT 0x000000000000001b
The direct shared object dependencies are listing as 'NEEDED' values. So in the example above, libXpm.so.4
on my system just needs libX11.so.6
and libc.so.6
.
It's important to note that this doesn't mean that all the symbols needed by the binary being passed to objdump
will be present in the libraries, but it does at least show what libraries the loader will try to load when loading the binary.
You can use [];
var indexValue = Index[1];
For clear frame, first need to destroy all widgets inside the frame,. it will clear frame.
import tkinter as tk
from tkinter import *
root = tk.Tk()
frame = Frame(root)
frame.pack(side="top", expand=True, fill="both")
lab = Label(frame, text="hiiii")
lab.grid(row=0, column=0, padx=10, pady=5)
def clearFrame():
# destroy all widgets from frame
for widget in frame.winfo_children():
widget.destroy()
# this will clear frame and frame will be empty
# if you want to hide the empty panel then
frame.pack_forget()
frame.but = Button(frame, text="clear frame", command=clearFrame)
frame.but.grid(row=0, column=1, padx=10, pady=5)
# then whenever you add data in frame then you can show that frame
lab2 = Label(frame, text="hiiii")
lab2.grid(row=1, column=0, padx=10, pady=5)
frame.pack()
root.mainloop()
you should change like this:
private string getValue(float price)
{
if(price >0)
return "debit";
return "credit";
}
//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};
Because when I use one or another I get a window prompt asking me to download the file for both of them.
This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.
For example, if you have a PDF file and Firefox/Adobe Reader, an inline disposition will open the PDF within Firefox, whereas attachment will force it to download.
If you're serving a .ZIP file, browsers won't be able to display it inline, so for inline and attachment dispositions, the file will be downloaded.
The function to make the API call with axios:
function getFileToDownload (apiUrl) {
return axios.get(apiUrl, {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json'
}
})
}
Call the function and then download the excel file you get:
getFileToDownload('putApiUrlHere')
.then (response => {
const type = response.headers['content-type']
const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'file.xlsx'
link.click()
})
An issue that DO arise in practical Android code is that comparing them with CharSequence.equals is valid but does not necessarily work as intended.
EditText t = (EditText )getView(R.id.myEditText); // Contains "OK"
Boolean isFalse = t.getText().equals("OK"); // will always return false.
Comparison should be made by
("OK").contentEquals(t.GetText());
If you're using less , and it's not loading the icons font you must check out the font path go to the file variable.less and change the @icon-font-path path , that worked for me.
First, if you branch was created within gc.reflogexpire
days (default 90 days, i.e. around 3 months), you can use git log -g <branch>
or git reflog show <branch>
to find first entry in reflog, which would be creation event, and looks something like below (for git log -g
):
Reflog: <branch>@{<nn>} (C R Eator <[email protected]>)
Reflog message: branch: Created from <some other branch>
You would get who created a branch, how many operations ago, and from which branch (well, it might be just "Created from HEAD", which doesn't help much).
That is what MikeSep said in his answer.
Second, if you have branch for longer than gc.reflogexpire
and you have run git gc
(or it was run automatically), you would have to find common ancestor with the branch it was created from. Take a look at config file, perhaps there is branch.<branchname>.merge
entry, which would tell you what branch this one is based on.
If you know that the branch in question was created off master branch (forking from master branch), for example, you can use the following command to see common ancestor:
git show $(git merge-base <branch> master)
You can also try git show-branch <branch> master
, as an alternative.
This is what gbacon said in his response.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
When you say #include "foop.cpp"
, it is as if you had copied the entire contents of foop.cpp
and pasted it into main.cpp
.
So when you compile main.cpp
, the compiler emits a main.obj
that contains the executable code for two functions: main
and foo
.
When you compile foop.cpp
itself, the compiler emits a foop.obj
that contains the executable code for function foo
.
When you link them together, the compiler sees two definitions for function foo
(one from main.obj
and the other from foop.obj
) and complains that you have multiple definitions.
In my case, I had a similar issue after full installation of Debian 10.
Commandline:
php -v
show I am using php7.4
but print phpinfo()
gives me php7.3
Solution: Disable php7.3 Enable php7.4
$ a2dismod php7.3
$ a2enmod php7.4
$ update-alternatives --set php /usr/bin/php7.4
$ update-alternatives --set phar /usr/bin/phar7.4
$ update-alternatives --set phar.phar /usr/bin/phar.phar7.4
$ update-alternatives --set phpize /usr/bin/phpize7.4
$ update-alternatives --set php-config /usr/bin/php-config7.4
If you don't have DBA rights then you can use user_segments table:
select bytes/1024/1024 MB from user_segments where segment_name='Table_name'