This is a simple solution that worked for me with the same problem (I think):
mv /var/lib/mongodb /var/lib/mongodb_backup
mkdir /var/lib/mongodb
chmod 700 /var/lib/mongodb
chown mongodb:daemon /var/lib/mongodb
systemctl restart mongodb or service mongod restart
I had a same issue on ubuntu 14.04 Here is a solution
sudo service docker start
or you can list images
docker images
The latest docker supports setting ulimits through the command line and the API. For instance, docker run
takes --ulimit <type>=<soft>:<hard>
and there can be as many of these as you like. So, for your nofile, an example would be --ulimit nofile=262144:262144
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
This webpage have an explanation and a solution.
The solution is:
To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:
vm.overcommit_memory = 2
vm.overcommit_ratio = 80
These answers are a bit dated. Therefore I give you:
hash = JSON.parse string
Rails should automagically load the json
module for you, so you don't need to add require 'json'
.
You just have to partition the problem into some bite-sized steps and solve each one by one
First, get the maximum score in each subject:
select SubjectID, max(MarkRate)
from Mark
group by SubjectID;
Then query who are those that has SubjectID with max MarkRate:
select SubjectID, MarkRate, StudentID
from Mark
where (SubjectID,MarkRate)
in
(
select SubjectID, max(MarkRate)
from Mark
group by SubjectID
)
order by SubjectID, StudentID;
Then obtain the Student's name, instead of displaying just the StudentID:
select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)
where (SubjectID,MarkRate)
in
(
select SubjectID, max(MarkRate)
from Mark
group by SubjectID
)
order by SubjectName, StudentName
Database vendors' artificial differences aside with regards to joining and correlating results, the basic step is the same; first, partition the problem in a bite-sized parts, and then integrate them as you solved each one of them, so it won't be as confusing.
Sample data:
CREATE TABLE Student
(StudentID int, StudentName varchar(6), Details varchar(1));
INSERT INTO Student
(StudentID, StudentName, Details)
VALUES
(1, 'John', 'X'),
(2, 'Paul', 'X'),
(3, 'George', 'X'),
(4, 'Paul', 'X');
CREATE TABLE Subject
(SubjectID varchar(1), SubjectName varchar(7));
INSERT INTO Subject
(SubjectID, SubjectName)
VALUES
('M', 'Math'),
('E', 'English'),
('H', 'History');
CREATE TABLE Mark
(StudentID int, SubjectID varchar(1), MarkRate int);
INSERT INTO Mark
(StudentID, SubjectID, MarkRate)
VALUES
(1, 'M', 90),
(1, 'E', 100),
(2, 'M', 95),
(2, 'E', 70),
(3, 'E', 95),
(3, 'H', 98),
(4, 'H', 90),
(4, 'E', 100);
Live test here: http://www.sqlfiddle.com/#!1/08728/3
IN tuple test is still a join by any other name:
Convert this..
select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)
where (SubjectID,MarkRate)
in
(
select SubjectID, max(MarkRate)
from Mark
group by SubjectID
)
order by SubjectName, StudentName
..to JOIN:
select SubjectName, MarkRate, StudentName
from Mark
join Student using(StudentID)
join Subject using(SubjectID)
join
(
select SubjectID, max(MarkRate) as MarkRate
from Mark
group by SubjectID
) as x using(SubjectID,MarkRate)
order by SubjectName, StudentName
Contrast this code with the code immediate it. See how JOIN on independent query look like an IN construct? They almost look the same, and IN was just replaced with JOIN keyword; and the replaced IN keyword with JOIN is in fact longer, you need to alias the independent query's column result(max(MarkRate) AS MarkRate
) and also the subquery itself (as x
). Anyway, this are just matter of style, I prefer IN clause, as the intent is clearer. Using JOINs merely to reflect the data relationship.
Anyway, here's the query that works on all databases that doesn't support tuple test(IN
):
select sb.SubjectName, m.MarkRate, st.StudentName
from Mark as m
join Student as st on st.StudentID = m.StudentID
join Subject as sb on sb.SubjectID = m.SubjectID
join
(
select SubjectID, max(MarkRate) as MaxMarkRate
from Mark
group by SubjectID
) as x on m.SubjectID = x.SubjectID AND m.MarkRate = x.MaxMarkRate
order by sb.SubjectName, st.StudentName
Live test: http://www.sqlfiddle.com/#!1/08728/4
Now, in Django 1.9 you have first()
method for querysets.
YourModel.objects.all().first()
This is a better way than .get()
or [0]
because it does not throw an exception if queryset is empty, Therafore, you don't need to check using exists()
As mentioned in other people's comments, the top solution given here was not working for me in Ansible 2.2, particularly when also using with_items
.
It appears that OP's intended approach does work now with a slight change to the quoting of item
.
- set_fact: something="{{ something + [ item ] }}"
with_items:
- one
- two
- three
And a longer example where I've handled the initial case of the list being undefined and added an optional when
because that was also causing me grief:
- set_fact: something="{{ something|default([]) + [ item ] }}"
with_items:
- one
- two
- three
when: item.name in allowed_things.item_list
<div class="scrollingDiv">foo</div>
div.scrollingDiv
{
overflow:scroll;
}
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s="000101";
cout<<s<<"\n";
int a = stoi(s);
cout<<a<<"\n";
s=to_string(a);
s+='1';
cout<<s;
return 0;
}
Output:
used !important
in CSS property
<div style="color: red;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
}
':'.join(x.encode('hex') for x in 'Hello World!')
public static bool CheckURLValid(this string source)
{
Uri uriResult;
return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
}
Usage:
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
//valid process
}
UPDATE: (single line of code) Thanks @GoClimbColorado
public static bool CheckURLValid(this string source) => Uri.TryCreate(source, UriKind.Absolute, out Uri uriResult) && uriResult.Scheme == Uri.UriSchemeHttps;
Usage:
string url = "htts://adasd.xc.";
if(url.CheckUrlValid())
{
//valid process
}
Just put the CSS outside the PHP Tag. Here:
<html>
<head>
<title>Title</title>
<style type="text/css">
table {
margin: 8px;
}
</style>
</head>
<body>
<table>
<tr><th>ID</th><th>hashtag</th></tr>
<?php
while($row = mysql_fetch_row($result))
{
echo "<tr onmouseover=\"hilite(this)\" onmouseout=\"lowlite(this)\"><td>$row[0]</td> <td>$row[1]</td></tr>\n";
}
?>
</table>
</body>
</html>
Take note that the PHP tags are <?php
and ?>
.
I created a GitHub repo with an script to solve this problem quickly. Just change a couple variables and run it (First, the script creates a backup of your database).
I hope this help you (and others people too).
>>> d={'a':1,'b':2,'c':3}
>>> for kv in d.items():
... print kv[0],'\t',kv[1]
...
a 1
c 3
b 2
TESTED with jquery 1.11.3 & jquery-ui 1.11.4
$(function() {
$("#draggable").draggable({
revert : function(event, ui) {
// on older version of jQuery use "draggable"
// $(this).data("draggable")
// on 2.x versions of jQuery use "ui-draggable"
// $(this).data("ui-draggable")
$(this).data("uiDraggable").originalPosition = {
top : 0,
left : 0
};
// return boolean
return !event;
// that evaluate like this:
// return event !== false ? false : true;
}
});
$("#droppable").droppable();
});
Persistence Context is an environment or cache where entity instances(which are capable of holding data and thereby having the ability to be persisted in a database) are managed by Entity Manager.It syncs the entity with database.All objects having @Entity annotation are capable of being persisted. @Entity is nothing but a class which helps us create objects in order to communicate with the database.And the way the objects communicate is using methods.And who supplies those methods is the Entity Manager.
In the POSIX standard, which /bin/sh
is supposed to respect, the command is .
(a single dot), not source
. The source
command is a csh
-ism that has been pulled into bash
.
Try
. $env_name/bin/activate
Or if you must have non-POSIX bash
-isms in your code, use #!/bin/bash
.
Eclipse is suggesting you to define generic type
so that you can have type safety
. You can write
Map m = new HashMap();
which does not ensure type safety but following will ensure type safety
Map<Object,Object> = new HashMap<Object,Object>();
The Object
can be any type such as String
, Integer
etc.
In my case I imported pyxlsd module before module wich works with db Mysql. After I did put Mysql module first(upper in code) it became to work like a clock. Think there was some namespace issue.
To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.
In you command line. Use
java -cp "path/to/your/jar:." main
rather than just
java main
The option tells Java where to search for libraries.
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
SELECT @EmployeeList
source: http://www.sqlteam.com/article/using-coalesce-to-build-comma-delimited-string
for (int i=0; i<dt_pattern.Rows.Count; i++)
{
DataRow dr = dt_pattern.Rows[i];
}
In the loop, you can now reference row i+1 (assuming there is an i+1)
String temp = passwordSalt;
byte[] byteSalt = temp.getBytes();
int start = 32;
for (int i = 0; i < byteData.length; i ++)
{
byteData[start + i] = byteSalt[i];
}
The problem with your code here is that the variable i that is being used to index the arrays is going past both the byteSalt array and the byteData array. So, Make sure that byteData is dimensioned to be at least the maximum length of the passwordSalt string plus 32. What will correct it is replacing the following line:
for (int i = 0; i < byteData.length; i ++)
with:
for (int i = 0; i < byteSalt.length; i ++)
You can of course format the result of current_timestamp()
.
Please have a look at the various formatting functions in the official documentation.
I had such problem. Solution was simple :
P.S. Sorry, for bad grammar.
Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:
create index arrival_year on reservations ( extract(year from arrival) );
That will open PostgreSQL with the possibility to use an index for
select *
FROM reservations
WHERE extract(year from arrival) = 2012;
Note that the expression in the index must be exactly the same expression as used in the where
clause to make this work.
Instead of gdb
, run gdbtui
. Or run gdb
with the -tui
switch. Or press C-x C-a after entering gdb
. Now you're in GDB's TUI mode.
Enter layout asm
to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish
etc. are abbreviated to a single key, allowing you to walk through your program very quickly.
+---------------------------------------------------------------------------+ B+>|0x402670 <main> push %r15 | |0x402672 <main+2> mov %edi,%r15d | |0x402675 <main+5> push %r14 | |0x402677 <main+7> push %r13 | |0x402679 <main+9> mov %rsi,%r13 | |0x40267c <main+12> push %r12 | |0x40267e <main+14> push %rbp | |0x40267f <main+15> push %rbx | |0x402680 <main+16> sub $0x438,%rsp | |0x402687 <main+23> mov (%rsi),%rdi | |0x40268a <main+26> movq $0x402a10,0x400(%rsp) | |0x402696 <main+38> movq $0x0,0x408(%rsp) | |0x4026a2 <main+50> movq $0x402510,0x410(%rsp) | +---------------------------------------------------------------------------+ child process 21518 In: main Line: ?? PC: 0x402670 (gdb) file /opt/j64-602/bin/jconsole Reading symbols from /opt/j64-602/bin/jconsole...done. (no debugging symbols found)...done. (gdb) layout asm (gdb) start (gdb)
The ZXing project provides a standalone barcode reader application which — via Android's intent mechanism — can be called by other applications who wish to integrate barcode scanning.
The easiest way to do this is to call the ZXing SCAN
Intent
from your application, like this:
public Button.OnClickListener mScan = new Button.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
};
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
Pressing the button linked to mScan
would launch directly into the ZXing barcode scanner screen (or crash if ZXing isn't installed). Once a barcode has been recognised, you'll receive the result in your Activity
, here in the contents
variable.
To avoid the crashing and simplify things for you, ZXing have provided a utility class which you could integrate into your application to make the installation of ZXing smoother, by redirecting the user to the Android Market if they don't have it installed already.
Finally, if you want to integrate barcode scanning directly into your application without relying on having the separate ZXing application installed, well then it's an open source project and you can do so! :)
Edit: Somebody edited this guide into this answer (it sounds a bit odd, I can't vouch as to its accuracy, and I'm not sure why they're using Eclipse in 2015):
Step by step to setup zxing 3.2.1 in eclipse
http://sourceforge.net/projects/pywin32/files/ - 3rd .exe down
For Change The color
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:background="?attr/colorPrimary"
/>
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
myToolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(), R.color.Auth_Background));
setSupportActionBar(myToolbar);
In React, the component will re-render (or update) only if the state or the prop changes.
In your case you have to update the state immediately after the change so that the component will re-render with the updates state value.
onTodoChange(event) {
// update the state
this.setState({name: event.target.value});
}
After your insert query, use this command $this->db->insert_id();
to return the last inserted id.
For example:
$this->db->insert('Your_tablename', $your_data);
$last_id = $this->db->insert_id();
echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.
With vim from command line:
vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename
If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.
struct.pack('B', 65)
(And yes, 65 is \x41, not \x65.)
The struct class will also conveniently handle endianness for communication or other uses.
The simplest way to read each line of a file into a bash
array is this:
IFS=$'\n' read -d '' -r -a lines < /etc/passwd
Now just index in to the array lines
to retrieve each line, e.g.
printf "line 1: %s\n" "${lines[0]}"
printf "line 5: %s\n" "${lines[4]}"
# all lines
echo "${lines[@]}"
I got few links sometime back while reading on ExtJS full framework in itself is JSON.
http://www.thomasfrank.se/xml_to_json.html
http://camel.apache.org/xmljson.html
online XML to JSON converter : http://jsontoxml.utilities-online.info/
UPDATE BTW, To get JSON as added in question, HTML need to have type & content tags in it too like this or you need to use some xslt transformation to add these elements while doing JSON conversion
<?xml version="1.0" encoding="UTF-8" ?>
<type>div</type>
<content>
<type>span</type>
<content>Text2</content>
</content>
<content>Text2</content>
SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
-- <add any columns to outer select from inner query>
FROM
( -- your query here --
select 'CARAT Issue Open' issue_comment, ...., ...,
substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
from ....
where UPPER(ISSUE_STATUS) like '%OPEN%'
)
WHERE... -- optional --
Here's a slightly modified version of @David Brainer-Bankers answer that sorts alphabetically by string, or numerically by number, and ensures that words beginning with Capital letters don't sort above words starting with a lower case letter (e.g "apple,Early" would be displayed in that order).
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
if (typeof x == "string")
{
x = (""+x).toLowerCase();
}
if (typeof y == "string")
{
y = (""+y).toLowerCase();
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
In my case the issue was caused by custom ActionFilterAttribute which was a kind of global filter attribute. The attribute instantiated a service through Autofac but the service crashed in constructor:
public ActionFilterAttribute()
{
_service = ContainerManager.Resolve<IService>();
}
public class Service: IService
{
public Service()
{
throw new Exception('Oops!');
}
}
There is no built-in function in Javascript to perform this search.
If you are using jQuery you could do a jQuery.inArray(element,array)
.
In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").
Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.
I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.
On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.
Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.
Let me add a little detail to this.
these two calls are almost equivalent:
func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args); // is same as using apply
There’s only a minor difference:
- The
spread
operator ... allows passing iterableargs
as the list to call.- The
apply
accepts only array-like args.
So, these calls complement each other. Where we expect an iterable, call
works, where we expect an array-like, apply
works.
And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but apply will probably be faster because most JavaScript engines internally optimize it better.
#include <vector>
#include <algorithm>
int main()
{
int arr[5] = {4, 1, 3, 2, 6};
int x = -1;
std::vector<int> testVector(arr, arr + sizeof(arr) / sizeof(int) );
std::vector<int>::iterator it = std::find(testVector.begin(), testVector.end(), 3);
if (it != testVector.end())
{
x = it - testVector.begin();
}
return 0;
}
Or you can just build a vector in a normal way, without creating it from an array of ints and then use the same solution as shown in my example.
Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.
For unordered scripts generated by SSMS you can go following
a) Execute script (some objects will be inserted some wont, there will be some errors)
b) Remove all objects from the script that have been added to database
c) Go back to a) until everything is eventually executed
Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).
All of these will take care of the dependencies for you and save you even more time.
A7Soft provide XML comparison tools freeware and shareware:
You can find out what library depends on a wrong version of the support library and exclude it like this:
compile ('com.stripe:stripe-android:5.1.1') {
exclude group: 'com.android.support'
}
stripe-android
in my case.
Try using ReadSettings:
from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"
Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:
Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.
function Copy-File {
# ref: https://stackoverflow.com/a/55527732/3626361
param([string]$From, [string]$To)
try {
$job = Start-BitsTransfer -Source $From -Destination $To `
-Description "Moving: $From => $To" `
-DisplayName "Backup" -Asynchronous
# Start stopwatch
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Write-Progress -Activity "Connecting..."
while ($job.JobState.ToString() -ne "Transferred") {
switch ($job.JobState.ToString()) {
"Connecting" {
break
}
"Transferring" {
$pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
$elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000
if ($elapsed -eq 0) {
$xferrate = 0.0
}
else {
$xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
}
if ($job.BytesTransferred % 1mb -eq 0) {
if ($pctcomp -gt 0) {
$secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
}
else {
$secsleft = 0
}
Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft
}
break
}
"Transferred" {
break
}
Default {
throw $job.JobState.ToString() + " unexpected BITS state."
}
}
}
$sw.Stop()
$sw.Reset()
}
finally {
Complete-BitsTransfer -BitsJob $job
Write-Progress -Activity "Completed" -Completed
}
}
The HttpWebRequest modifies the CookieContainer assigned to it. There is no need to process returned cookies. Simply assign your cookie container to every web request.
public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; } = new CookieContainer();
protected override WebRequest GetWebRequest(Uri uri)
{
WebRequest request = base.GetWebRequest(uri);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = CookieContainer;
}
return request;
}
}
Inside Layout Xml File We can Change Color of Hint.....
android:textColorHint="@android:color/*****"
you can replace * with color or color code.
This problem is related to missing the Visual Studio "redistributable package." It is not obvious which one is missing based on the dependency walk, but I would try the one that corresponds with your compiler version first and see if things run properly:
I ran into this problem because I am using the Visual Studio compilers, but not the full Visual Studio environment.
Going to dare to inject a new link here: The latest supported Visual C++ downloads. Stein Åsmul, 29.11.2018.
You just need to add 'table-layout: fixed;'
.table {
display: table;
height: 100px;
width: 100%;
table-layout: fixed;
}
You could try using the below extension method:
public static T? GetValueOrNull<T>(this string valueAsString)
where T : struct
{
if (string.IsNullOrEmpty(valueAsString))
return null;
return (T) Convert.ChangeType(valueAsString, typeof(T));
}
This way you can do this:
double? amount = strAmount.GetValueOrNull<double>();
int? amount = strAmount.GetValueOrNull<int>();
decimal? amount = strAmount.GetValueOrNull<decimal>();
If you're new
ing up an element with initializer syntax, you can do something like this:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Attributes = { ["style"] = "min-width: 35px;" }
},
}
};
Or if using the CssStyleCollection
specifically:
var row = new HtmlTableRow
{
Cells =
{
new HtmlTableCell
{
InnerText = text,
Style = { ["min-width"] = "35px" }
},
}
};
I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")
You are doing it right; every time you need to add a row, simply so new TableRow()
, etc. It might be easier for you to inflate
the new row from XML
though.
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
asarray(x)
is like array(x, copy=False)
Use asarray(x)
when you want to ensure that x
will be an array before any other operations are done. If x
is already an array then no copy would be done. It would not cause a redundant performance hit.
Here is an example of a function that ensure x
is converted into an array first.
def mysum(x):
return np.asarray(x).sum()
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them
You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built
If you need pip and setup tool , please install openssl and opessl-devl before making python2.7
yum install openssl-devel
Then follow https://stackoverflow.com/a/4149444/429476
Then https://pypi.python.org/pypi/setuptools
wget https://bootstrap.pypa.io/ez_setup.py
python2.7 ez_setup.py
Then to install pip
wget https://bootstrap.pypa.io/get-pip.py
python2.7 get-pip.py
Then to install other packages pip2.7 install package_name
For Android there is the addition of target-density tag.
target-densitydpi=device-dpi
So, the code would look like
<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />
Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.
Error control operator
In case the warning is expected you can use the error control operator @
to suppress thrown messages.
$role_arr = getRole(@$response->records);
While this reduces clutter in your code you should use it with caution as it may make debugging future errors harder. An example where using @
may be useful is when creating an object from user input and running it through a validation method before using it in further logic.
Null Coalesce Operator
Another alternative is using the isset_ternary operator ??
. This allows you to avoid warnings and assign default value in a short one line fashion.
$role_arr = getRole($response->records ?? null);
Try collapse::unlist2d
(shorthand for 'unlist to data.frame'):
l <- replicate(
132,
list(sample(letters, 20)),
simplify = FALSE
)
library(collapse)
head(unlist2d(l))
.id.1 .id.2 V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
1 1 1 e x b d s p a c k z q m u l h n r t o y
2 2 1 r t i k m b h n s e p f o c x l g v a j
3 3 1 t r v z a u c o w f m b d g p q y e n k
4 4 1 x i e p f d q k h b j s z a t v y l m n
5 5 1 d z k y a p b h c v f m u l n q e i w j
6 6 1 l f s u o v p z q e r c h n a t m k y x
head(unlist2d(l, idcols = FALSE))
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20
1 e x b d s p a c k z q m u l h n r t o y
2 r t i k m b h n s e p f o c x l g v a j
3 t r v z a u c o w f m b d g p q y e n k
4 x i e p f d q k h b j s z a t v y l m n
5 d z k y a p b h c v f m u l n q e i w j
6 l f s u o v p z q e r c h n a t m k y x
Actually, to query the team_name
, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.
from urllib2 import urlopen
import json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)
for i in json_obj['team']:
print i['team_name']
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
This behaviour is now part of the component lifecycle.
A component can implement the ngOnChanges method in the OnChanges interface to get access to input changes.
Example:
import {Component, Input, OnChanges} from 'angular2/core';
@Component({
selector: 'hero-comp',
templateUrl: 'app/components/hero-comp/hero-comp.html',
styleUrls: ['app/components/hero-comp/hero-comp.css'],
providers: [],
directives: [],
pipes: [],
inputs:['hero', 'real']
})
export class HeroComp implements OnChanges{
@Input() hero:Hero;
@Input() real:string;
constructor() {
}
ngOnChanges(changes) {
console.log(changes);
}
}
let dateTimeStamp = NSDate(timeIntervalSince1970:Double(currentTimeInMiliseconds())/1000) //UTC time //YOUR currentTimeInMiliseconds METHOD
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
print("Local Time", strDateSelect) //Local time
let dateFormatter2 = NSDateFormatter()
dateFormatter2.timeZone = NSTimeZone(name: "UTC") as NSTimeZone!
dateFormatter2.dateFormat = "yyyy-MM-dd"
let date3 = dateFormatter.dateFromString(strDateSelect)
print("DATE",date3)
Iterables are nicer:
const matches = (text, pattern) => ({
[Symbol.iterator]: function * () {
const clone = new RegExp(pattern.source, pattern.flags);
let match = null;
do {
match = clone.exec(text);
if (match) {
yield match;
}
} while (match);
}
});
Usage in a loop:
for (const match of matches('abcdefabcdef', /ab/g)) {
console.log(match);
}
Or if you want an array:
[ ...matches('abcdefabcdef', /ab/g) ]
If you could not find Local DTC in the component services try to run this PowerShell script first:
$DTCSettings = @(
"NetworkDtcAccess", # Network DTC Access
"NetworkDtcAccessClients", # Allow Remote Clients ( Client and Administration)
"NetworkDtcAccessAdmin", # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions", # (Transaction Manager Communication )
"NetworkDtcAccessInbound", # Allow Inbound (Transaction Manager Communication )
"NetworkDtcAccessOutbound" , # Allow Outbound (Transaction Manager Communication )
"XaTransactions", # Enable XA Transactions
"LuTransactions" # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
}
Restart-Service msdtc
And it appears!
Source: The partner transaction manager has disabled its support for remote/network transactions
One way usefull when you work with images, but can be used as workaround otherwise:
<html>
<head>
</head>
<style>
#someContainer {
width:50%;
position: relative;
}
#par {
width: 100%;
background-color:red;
}
#image {
width: 100%;
visibility: hidden;
}
#myContent {
position:absolute;
}
</style>
<div id="someContainer">
<div id="par">
<div id="myContent">
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>
</div>
<img src="yourImage" id="image"/>
</div>
</div>
</html>
To use replace yourImage with your image url. You use image with width / height ratio you desire.
div id="myContent" is here as example of workaround where myContent will overlay over image.
This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.
Your problem is simple:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
This code first declares a global variable called names
. Then, you start a for loop. The for loop declares a local variable that just happens to be called names
too; the fact that a variable had previously been defined with names
is entirely irrelevant. Any use of names
inside the for loop will refer to the local one, not the global one.
The for loop says that the inner part of the loop will be called with names = 1
, then names = 2
, and finally names = 3
. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.
What you actually wanted was something like this:
names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
print (names[nameCount])
end
The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).
Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.
However, this has a flaw. What happens if you remove one of the elements from the list?
names = {'John', 'Joe'}
for nameCount = 1, 3 do
print (names[nameCount])
end
Now, we get John Joe nil
, because attempting to access values from a table that don't exist results in nil
. To prevent this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'}
for nameCount = 1, #names do
print (names[nameCount])
end
The #
is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names
gets, this will always work.
However, there is a more convenient way to iterate through an array of items:
names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
print (name)
end
ipairs
is a Lua standard function that iterates over a list. This style of for
loop, the iterator for loop, uses this kind of iterator function. The i
value is the index of the entry in the array. The name
value is the value at that index. So it basically does a lot of grunt work for you.
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
Using Collections to shuffle an array of primitive types is a bit of an overkill...
It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle:
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
The best way to enable the production mode for an Angular 2 application, is to use angular-cli and build the application with ng build --prod
. This will build the application with production profile. Using angular-cli has the benefit of being able to use development mode using ng serve
or ng build
while developing without altering the code all the time.
$utfEncodedArray = array_map("utf8_encode", $inputArray );
Does the job and returns a serialized array with numeric keys (not an assoc).
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of month, day, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields.
In other words: just write anything and it will work.
Or check this table with all the unambiguous formats.
<ul>
<li ng-repeat=interface in interfaces>
<img src='green-checkmark.png' ng-show="interface=='UP'" />
<img src='big-black-X.png' ng-show="interface=='DOWN'" />
</li>
</ul>
Convert the array into a hash. Then look for the key.
array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a] # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1
I have a very simple solution for this problem. You don't need to use the console.
TLDR: Create repo, move files to existing projects folder, SourceTree will ask you where his files are, locate the files. Done, your repo is in another folder.
Long answer:
Tips: Clone in SourceTree option is not available right after you create new repository so you first have to click on Create Readme File for that option to become available.
Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.
You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:
set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"
Strings in java are immutable. That means you need to create a new string or overwrite your old string to achieve the desired affect:
id = id.replace(".xml", "");
htmlFor
to replace for
!you can find more info by following the below links.
https://facebook.github.io/react/docs/dom-elements.html#htmlfor
I came across the same issue. My aim is to test PHP scripts with Oracle on Windows 7 Home and without thinking installed IIS7 express and as an afterthought considered Apache as a simpler approach. I will explore IIS express's capabilities seperately.
The challenge was after installing IIS7 express the Apache installation was playing second fiddle to IIS express and bringing up the Microsoft Homepage.
I resolved the port 80 issue by :-
Multiple text-shadows..
Something like this:
var steps = 10,
i,
R = 0.6,
x,
y,
theStyle = '1vw 1vw 3vw #005dab';
for (i = -steps; i <= steps; i += 1) {
x = (i / steps) / 2;
y = Math.sqrt(Math.pow(R, 2) - Math.pow(x, 2));
theStyle = theStyle + ',' + x.toString() + 'vw ' + y.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',' + x.toString() + 'vw -' + y.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
theStyle = theStyle + ',-' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
}
document.getElementsByTagName("H1")[0].setAttribute("style", "text-shadow:" + theStyle);
<?php
class abs
{
public function volume($arg1=null, $arg2=null, $arg3=null)
{
if($arg1 == null && $arg2 == null && $arg3 == null)
{
echo "function has no arguments. <br>";
}
else if($arg1 != null && $arg2 != null && $arg3 != null)
{
$volume=$arg1*$arg2*$arg3;
echo "volume of a cuboid ".$volume ."<br>";
}
else if($arg1 != null && $arg2 != null)
{
$area=$arg1*$arg2;
echo "area of square = " .$area ."<br>";
}
else if($arg1 != null)
{
$volume=$arg1*$arg1*$arg1;
echo "volume of a cube = ".$volume ."<br>";
}
}
}
$obj=new abs();
echo "For no arguments. <br>";
$obj->volume();
echo "For one arguments. <br>";
$obj->volume(3);
echo "For two arguments. <br>";
$obj->volume(3,4);
echo "For three arguments. <br>";
$obj->volume(3,4,5);
?>
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This produces:
[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
Here are some suggestions:
For Android phones, any network: Root your phone, then install tcpdump on it. This app is a tcpdump wrapper that will install tcpdump and enable you to start captures using a GUI. Tip: You will need to make sure you supply the right interface name for the capture and this varies from one device to another, eg -i eth0 or -i tiwlan0 - or use -i any to log all interfaces
For Android 4.0+ phones: Android PCAP from Kismet uses the USB OTG interface to support packet capture without requiring root. I haven't tried this app, and there are some restrictions on the type of devices supported (see their page)
For Android phones: tPacketCapture uses the Android VPN service to intercept packets and capture them. I have used this app successfully, but it also seems to affect the performance with large traffic volumes (eg video streaming)
For IOS 5+ devices, any network: iOS 5 added a remote virtual interface (RVI) facility that lets you use Mac OS X packet trace programs to capture traces from an iOS device. See here for more details
For all phones, wi-fi only: Set up your PC as a wireless access point, then run wireshark on the PC
For all phones, wi-fi only: Get a capture device that can sniff wi-fi. This has the advantage of giving you 802.11x headers as well, but you may miss some of the packets
Capture using a VPN server: Its fairly easy to set-up your own VPN server using OpenVPN. You can then route your traffic through your server by setting up the mobile device as a VPN client and capture the traffic on the server end.
Another option is winsw: https://github.com/kohsuke/winsw/
Configure an xml file to specify the service name, what to execute, any arguments etc. And use the exe to install. Example xml: https://github.com/kohsuke/winsw/tree/master/examples
I prefer this to nssm, because it is one lightweight exe; and the config xml is easy to share/commit to source code.
PS the service is installed by running your-service.exe install
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production
calls my production task and sets a flag for any conditionals.
From CLI:
$ su - postgres
$ psql template1
template1=# CREATE USER tester WITH PASSWORD 'test_password';
template1=# GRANT ALL PRIVILEGES ON DATABASE "test_database" to tester;
template1=# \q
PHP (as tested on localhost, it works as expected):
$connString = 'port=5432 dbname=test_database user=tester password=test_password';
$connHandler = pg_connect($connString);
echo 'Connected to '.pg_dbname($connHandler);
Unable to replicate. It worked fine for me:
mysql> CALL my_sqrt(4, @out_value);
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @out_value;
+------------+
| @out_value |
+------------+
| 2 |
+------------+
1 row in set (0.00 sec)
Perhaps you should paste the entire error message instead of summarizing it.
I'll add on to mike3875's answer for future readers using Laravel 5.1 and onward.
To make things quicker, you can use the flag "--table" like this:
php artisan make:migration add_paid_to_users --table="users"
This will add the up
and down
method content automatically:
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
//
});
}
Similarily, you can use the --create["table_name"]
option when creating new migrations which will add more boilerplate to your migrations. Small point, but helpful when doing loads of them!
Go for stable version or gradle in app level gradle file
in my case it was
classpath 'com.android.tools.build:gradle:2.2.0-alpha3'
I changed it with
classpath 'com.android.tools.build:gradle:2.1.2'
For those who have mentioned a reconciliation as a potential future for Hudson and Jenkins, with the fact that Jenkins will be joining SPI, it is unlikely at this point they will reconcile.
Those error messages
CMake Error at ... (project):
No CMAKE_C_COMPILER could be found.
-- Configuring incomplete, errors occurred!
See also ".../CMakeFiles/CMakeOutput.log".
See also ".../CMakeFiles/CMakeError.log".
or
CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.
Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
...
-- Configuring incomplete, errors occurred!
just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).
The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.
Preconditions
You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree
Windows cmd.exe
> rmdir /s /q VS2015
> mkdir VS2015
> cd VS2015
Bash shell
$ rm -rf MSYS
$ mkdir MSYS
$ cd MSYS
and make sure your command shell points to your newly created binary output directory.
General things you can/should try
Is CMake able find and run with any/your default compiler? Run without giving a generator
> cmake ..
-- Building for: Visual Studio 14 2015
...
Perfect if it correctly determined the generator to use - like here Visual Studio 14 2015
What was it that actually failed?
In the previous build output directory look at CMakeFiles\CMakeError.log
for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles\[Version]\CompilerIdC
|CompilerIdCXX
directly from the command line (as found in the error log).
CMake can't find Visual Studio
Try to select the correct generator version:
> cmake --help
> cmake -G "Visual Studio 14 2015" ..
If that doesn't help, try to set the Visual Studio environment variables first (the path could vary):
> "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
> cmake ..
or use the Developer Command Prompt for VS2015
short-cut in your Windows Start Menu under All Programs
/Visual Studio 2015
/Visual Studio Tools
(thanks at @Antwane for the hint).
Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[Version];InstallDir
), system environment variables and - if none of the others did come up with something - plainly try to call the compiler.
CMake can't find GCC (MinGW/MSys)
You start the MSys bash
shell with msys.bat
and just try to directly call gcc
$ gcc
gcc.exe: fatal error: no input files
compilation terminated.
Here it did find gcc
and is complaining that I didn't gave it any parameters to work with.
So the following should work:
$ cmake -G "MSYS Makefiles" ..
-- The CXX compiler identification is GNU 4.8.1
...
$ make
If GCC was not found call export PATH=...
to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.
If it's still not working, try to set the CXX
compiler path directly by exporting it (path may vary)
$ export CC=/c/MinGW/bin/gcc.exe
$ export CXX=/c/MinGW/bin/g++.exe
$ cmake -G "MinGW Makefiles" ..
-- The CXX compiler identification is GNU 4.8.1
...
$ mingw32-make
For more details see How to specify new GCC path for CMake
Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make
program distributed with MinGW
Still not working? That's weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).
Otherwise the last resort of CMake is to not try any compiler search itself and set CMake's internal variables directly by
$ cmake -DCMAKE_C_COMPILER=/c/MinGW/bin/gcc.exe -DCMAKE_CXX_COMPILER=/c/MinGW/bin/g++.exe ..
For more details see Cmake doesn't honour -D CMAKE_CXX_COMPILER=g++ and Cmake error setting compiler
Alternatively those variables can also be set via cmake-gui.exe
on Windows. See Cmake cannot find compiler
Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain (ar
, ranlib
, strip
, ld
, nm
, objdump
, and objcopy
).
import os
os.system("pip install beautifulsoup4")
or
import subprocess
exe = subprocess.Popen("pip install beautifulsoup4")
exe_out = exe.communicate()
print(exe_out)
Edit — Thanks to Janus Troelsen's comment, I found a better solution:
indeterminate
See w3c reference guide. To make checkbox appear visually indeterminate set it to true:
element.indeterminate = true;
Here is Janus Troelsen's fiddle. Note, however, that:
The indeterminate
state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)
This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.
Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.
Previous answer
Another alternative would be to play with the checkbox transparency for the "some selected" state (as Gmail
doesused to do in previous versions). It will require some javascript and a CSS class. Here I put a particular example that handles a list with checkable items and a checkbox that allows to select all/none of them. This checkbox shows a "some selected" state when some of the list items are selected.Given a checkbox with an ID
#select_all
and several checkboxes with a class.select_one
,The CSS class that fades the "select all" checkbox would be the following:
.some_selected { opacity: 0.5; filter: alpha(opacity=50); }
And the JS code that handles the tri-state of the select all checkbox is the following:
$('#select_all').change (function () { //Check/uncheck all the list's checkboxes $('.select_one').attr('checked', $(this).is(':checked')); //Remove the faded state $(this).removeClass('some_selected'); }); $('.select_one').change (function () { if ($('.select_one:checked').length == 0) $('#select_all').removeClass('some_selected').attr('checked', false); else if ($('.select_one:not(:checked)').length == 0) $('#select_all').removeClass('some_selected').attr('checked', true); else $('#select_all').addClass('some_selected').attr('checked', true); });
You can try it here: http://jsfiddle.net/98BMK/
Hope that helps!
In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.
Here is link to my project: https://sourceforge.net/projects/pyproperties/. It is a library with methods for working with *.properties files for Python 3.x.
But it is not based on java.util.Properties
Because I haven't seen this answer:
Uninstall and reinstall your podfiles! Remove or uninstall library previously added : cocoapods
I've run into this issue over 3 times building my app and every time this is what fixes it. :)
I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
I'll try to explain as good as possible, hope I help some of you out there:
(1) app.js: Creation of authentication constants on app definition
var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
all : '*',
admin : 'admin',
editor : 'editor',
guest : 'guest'
}).constant('AUTH_EVENTS', {
loginSuccess : 'auth-login-success',
loginFailed : 'auth-login-failed',
logoutSuccess : 'auth-logout-success',
sessionTimeout : 'auth-session-timeout',
notAuthenticated : 'auth-not-authenticated',
notAuthorized : 'auth-not-authorized'
})
(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.
angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS',
function($http, $rootScope, $window, Session, AUTH_EVENTS) {
authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]
return authService;
} ]);
(3) Session: A singleton to keep user data. The implementation here depends on you.
angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {
this.create = function(user) {
this.user = user;
this.userRole = user.userRole;
};
this.destroy = function() {
this.user = null;
this.userRole = null;
};
return this;
});
(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.
<body ng-controller="ParentController">
[...]
</body>
(5) Access control: To deny access on certain routes 2 steps have to be implemented:
a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).
.config(function ($stateProvider, USER_ROLES) {
$stateProvider.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard/index.html',
data: {
authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
}
});
})
b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.
$rootScope.$on('$stateChangeStart', function (event, next) {
var authorizedRoles = next.data.authorizedRoles;
if (!Auth.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (Auth.isAuthenticated()) {
// user is not allowed
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
} else {
// user is not logged in
$rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
}
}
});
(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.
angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
return {
responseError : function(response) {
$rootScope.$broadcast({
401 : AUTH_EVENTS.notAuthenticated,
403 : AUTH_EVENTS.notAuthorized,
419 : AUTH_EVENTS.sessionTimeout,
440 : AUTH_EVENTS.sessionTimeout
}[response.status], response);
return $q.reject(response);
}
};
} ]);
P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.
P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.
A possible alternative approach in Excel 2010 or later versions:
AGGREGATE(6,6,A1,B1)
In AGGREGATE
function the first 6
indicates PRODUCT
operation and the second 6
denotes "ignore errors"
[untested]
edit the project's settings.gradle file: delete the module name (, ':xxxxx') where xxxxx is the module name to be deleted
using the file explorer delete the module folder
by the way, the current version of the Android Studio (v3.1.2) throws an exception and exits the removing with an error while I'm removing the module through Module Settings => selected module => - (minus)
Best Regards, thanks)
For me below worked:
Step 1: Downloaded and installed the web Installer exe from https://www.microsoft.com/en-us/download/details.aspx?id=48137 on the application server. Rebooted the application server after installation was completed.
Step 2: Added below changes in the web.config
<system.web>
<compilation targetFramework="4.6"/> <!-- Changed framework 4.0 to 4.6 -->
<!--Added this httpRuntime -->
<httpRuntime targetFramework="4.6" />
</system.web>
Step 3: After completing step 1 and 2, it gave an error, "WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)" and to resolve this error, I added below key in appsettings in my web.config file
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.
See also these very similar questions:
Here's an example, as demonstrated in this jsFiddle:
<html><head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
<a class="checked" href="http://www.google.com">Click here</a>
<script type="text/javascript">
$(function() {
$('.checked').click(function(e) {
e.preventDefault();
var dialog = $('<p>Are you sure?</p>').dialog({
buttons: {
"Yes": function() {alert('you chose yes');},
"No": function() {alert('you chose no');},
"Cancel": function() {
alert('you chose cancel');
dialog.dialog('close');
}
}
});
});
});
</script>
</body><html>
Had a similar issue in adding "Start Command Prompt with Ruby" to context menu as it involves passing parameters along with the patch of cmd. Followed a similar procedure as the solution above
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\*\shell\Cmd With Ruby\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\""
[HKEY_CLASSES_ROOT\Directory\shell\bash]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\Directory\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%1\"\""
[HKEY_CLASSES_ROOT\Directory\Background\shell\bash]
@="Cmd With Ruby"
"Icon"="C:\\Windows\\System32\\cmd.exe"
[HKEY_CLASSES_ROOT\Directory\Background\shell\bash\command]
@="\"C:\\Windows\\System32\\cmd.exe\" \"/E:ON /K
\"C:\\Ruby25-x64\\bin\\setrbvars.cmd\"\" \"--cd=%v.\"\""
`gcc -print-prog-name=cc1plus` -v
This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.
You will get a reliable answer for your specific setup.
Likewise, for the C preprocessor:
`gcc -print-prog-name=cpp` -v
In most languages i am aware of, the actual regex for validating should be
^[0-9]{1,10}$
; otherwise the matcher will also return positive matches if the to be validated number is part of a longer string.
This is an answer to a slightly modified version of your question. If you can abandon the use of a stored procedure for a user-defined function, you can use an inline table-valued user-defined function. This is essentially a stored procedure (will take parameters) that returns a table as a result set; and therefore will place nicely with an INTO statement.
Here's a good quick article on it and other user-defined functions. If you still have a driving need for a stored procedure, you can wrap the inline table-valued user-defined function with a stored procedure. The stored procedure just passes parameters when it calls select * from the inline table-valued user-defined function.
So for instance, you'd have an inline table-valued user-defined function to get a list of customers for a particular region:
CREATE FUNCTION CustomersByRegion
(
@RegionID int
)
RETURNS TABLE
AS
RETURN
SELECT *
FROM customers
WHERE RegionID = @RegionID
GO
You can then call this function to get what your results a such:
SELECT * FROM CustomersbyRegion(1)
Or to do a SELECT INTO:
SELECT * INTO CustList FROM CustomersbyRegion(1)
If you still need a stored procedure, then wrap the function as such:
CREATE PROCEDURE uspCustomersByRegion
(
@regionID int
)
AS
BEGIN
SELECT * FROM CustomersbyRegion(@regionID);
END
GO
I think this is the most 'hack-less' method to obtain the desired results. It uses the existing features as they were intended to be used without additional complications. By nesting the inline table-valued user-defined function in the stored procedure, you have access to the functionality in two ways. Plus! You have only one point of maintenance for the actual SQL code.
The use of OPENROWSET has been suggested, but this is not what the OPENROWSET function was intended to be used for (From Books Online):
Includes all connection information that is required to access remote data from an OLE DB data source. This method is an alternative to accessing tables in a linked server and is a one-time, ad hoc method of connecting and accessing remote data by using OLE DB. For more frequent references to OLE DB data sources, use linked servers instead.
Using OPENROWSET will get the job done, but it will incur some additional overhead for opening up local connections and marshalling data. It also may not be an option in all cases since it requires an ad hoc query permission which poses a security risk and therefore may not be desired. Also, the OPENROWSET approach will preclude the use of stored procedures returning more than one result set. Wrapping multiple inline table-value user-defined functions in a single stored procedure can achieve this.
You have to tell replace() to repeat the regex:
.replace(/ /g,'')
The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.
If you want to match all whitespace, and not just the literal space character, use \s
instead:
.replace(/\s/g,'')
You can also use .replaceAll
if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll
, it must be global, so you just end up with extra typing:
.replaceAll(/\s/g,'')
I had this problem as I created a class "Response.cs" inside a folder named "Response". So VS was catching the new Response ()
as Folder/namespace.
So I changed the class name to StatusResponse.cs and called new StatusResponse()
.This solved the issue.
Instead of passing an anonymous type, pass a List of a dynamic type:
var dynamicResult = anonymousQueryResult.ToList<dynamic>();
DoSomething(List<dynamic> _dynamicResult)
DoSomething(dynamicResult);
Thanks to Petar Ivanov!
An alternative to overriding VerifyRenderingInServerForm is to remove the grid from the controls collection while you do the render, and then add it back when you are finished before the page loads. This is helpful if you want to have some generic helper method to get grid html because you don't have to remember to add the override.
Control parent = grid.Parent;
int GridIndex = 0;
if (parent != null)
{
GridIndex = parent.Controls.IndexOf(grid);
parent.Controls.Remove(grid);
}
grid.RenderControl(hw);
if (parent != null)
{
parent.Controls.AddAt(GridIndex, grid);
}
Another alternative to avoid the override is to do this:
grid.RenderBeginTag(hw);
grid.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grid.Rows)
{
row.RenderControl(hw);
}
grid.FooterRow.RenderControl(hw);
grid.RenderEndTag(hw);
Thanks to all, for me this solution worked: Magento 404 page in backoffice after login
"As of Android 1.6, incoming SMS message broadcasts (android.provider.Telephony.SMS_RECEIVED
) are delivered as an "ordered broadcast" — meaning that you can tell the system which components should receive the broadcast first."
This means that you can intercept incoming message and abort broadcasting of it further on.
In your AndroidManifest.xml
file, make sure to have priority set to highest:
<receiver android:name=".receiver.SMSReceiver" android:enabled="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
In your BroadcastReceiver
, in onReceive()
method, before performing anything with your message, simply call abortBroadcast();
EDIT: As of KitKat, this doesn't work anymore apparently.
EDIT2: More info on how to do it on KitKat here:
Delete SMS from android on 4.4.4 (Affected rows = 0(Zero), after deleted)
This is how I solved this problem. I created a special event handler that went into the code behind:
private void TextBox_KeyEnterUpdate(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TextBox tBox = (TextBox)sender;
DependencyProperty prop = TextBox.TextProperty;
BindingExpression binding = BindingOperations.GetBindingExpression(tBox, prop);
if (binding != null) { binding.UpdateSource(); }
}
}
Then I just added this as a KeyUp event handler in the XAML:
<TextBox Text="{Binding TextValue1}" KeyUp="TextBox_KeyEnterUpdate" />
<TextBox Text="{Binding TextValue2}" KeyUp="TextBox_KeyEnterUpdate" />
The event handler uses its sender
reference to cause it's own binding to get updated. Since the event handler is self-contained then it should work in a complex DataTemplate. This one event handler can now be added to all the textboxes that need this feature.
To add to the above answer (do steps 1-5).
First you need to set equal width and height for getting Circular ImageView.Below I set width and height as 100,100.If you want to set equal width and height according to your required size,set here.
var imageCircle = UIImageView(frame: CGRectMake(0, 0, 100, 100))
Then you need to set height/2 for corner radius
imageCircle.layer.cornerRadius = imageCircle.frame.size.height/2
imageCircle.layer.borderWidth = 1
imageCircle.layer.borderColor = UIColor.blueColor().CGColor
imageCircle.clipsToBounds = true
self.view.addSubview(imageCircle)
This is how I do it in Laravel 5
return Response::json(['hello' => $value],201);
Or using a helper function:
return response()->json(['hello' => $value], 201);
Please note that you should not use any png when you are testing this , first work with jpg .
$myImage = "images/logos/mylogo.jpg"; // this is where you get your Image
$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);
vowels = ["a","e","i","o","u"]
def checkForVowels(some_string):
#will save all counted vowel variables as key/value
amountOfVowels = {}
for i in vowels:
# check for lower vowel variables
if i in some_string:
amountOfVowels[i] = some_string.count(i)
#check for upper vowel variables
elif i.upper() in some_string:
amountOfVowels[i.upper()] = some_string.count(i.upper())
return amountOfVowels
print(checkForVowels("sOmE string"))
You can test this code here : https://repl.it/repls/BlueSlateblueDecagons
So have fun hope helped a lil bit.
I had the same problem while connecting from Android client to Kurento server. Kurento server use jks certificates, so I had to convert pem to it. As input for conversion I used cert.pem file and it lead to such errors. But if use fullchain.pem instead of cert.pem - all is OK.
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
In my case it was an accidentally turned on option. I'm using common root .xcconfig files both for iOS and macOS, for the iOS target the Enable hardened runtime option remained on so replacing the line
ENABLE_HARDENED_RUNTIME = YES
by the
ENABLE_HARDENED_RUNTIME[sdk=macosx*] = YES
in the .xcconfig file solved the issue
They are independent languages with unrelated lineages. Brendan Eich created Javascript originally at Netscape. It was initially called Mocha. The choice of Javascript as a name was a nod, if you will, to the then ascendant Java programming language, developed at Sun by Patrick Naughton, James Gosling, et. al.
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
Error
and Exception
both extend Throwable
, but mostly Error
is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error. For instance OutOfMemoryError
.
Though even application can raise an Error
but its just not a good a practice, instead applications should use checked exceptions for recoverable conditions and runtime exceptions for programming errors.
if you want to 'add to the id' rather than replace it
capture the current id first, then append your new id. especially useful for twitter bootstrap which uses input states on their forms.
new_id = '{{old_id}} inputSuccess';
old_id = that.attr('id');
that.attr('id', new_id.replace( /{{old_id}}/ig,old_id));
if you do not - you will lose any properties you previous set.
hth,
If you add Lombok to your project you can use its val keyword.
To anyone interested, here's a class I created using inazaruk's code that creates everything needed (I called it UIUpdater because I use it to periodically update the UI, but you can call it anything you like):
import android.os.Handler;
/**
* A class used to perform periodical updates,
* specified inside a runnable object. An update interval
* may be specified (otherwise, the class will perform the
* update every 2 seconds).
*
* @author Carlos Simões
*/
public class UIUpdater {
// Create a Handler that uses the Main Looper to run in
private Handler mHandler = new Handler(Looper.getMainLooper());
private Runnable mStatusChecker;
private int UPDATE_INTERVAL = 2000;
/**
* Creates an UIUpdater object, that can be used to
* perform UIUpdates on a specified time interval.
*
* @param uiUpdater A runnable containing the update routine.
*/
public UIUpdater(final Runnable uiUpdater) {
mStatusChecker = new Runnable() {
@Override
public void run() {
// Run the passed runnable
uiUpdater.run();
// Re-run it after the update interval
mHandler.postDelayed(this, UPDATE_INTERVAL);
}
};
}
/**
* The same as the default constructor, but specifying the
* intended update interval.
*
* @param uiUpdater A runnable containing the update routine.
* @param interval The interval over which the routine
* should run (milliseconds).
*/
public UIUpdater(Runnable uiUpdater, int interval){
UPDATE_INTERVAL = interval;
this(uiUpdater);
}
/**
* Starts the periodical update routine (mStatusChecker
* adds the callback to the handler).
*/
public synchronized void startUpdates(){
mStatusChecker.run();
}
/**
* Stops the periodical update routine from running,
* by removing the callback.
*/
public synchronized void stopUpdates(){
mHandler.removeCallbacks(mStatusChecker);
}
}
You can then create a UIUpdater object inside your class and use it like so:
...
mUIUpdater = new UIUpdater(new Runnable() {
@Override
public void run() {
// do stuff ...
}
});
// Start updates
mUIUpdater.startUpdates();
// Stop updates
mUIUpdater.stopUpdates();
...
If you want to use this as an activity updater, put the start call inside the onResume() method and the stop call inside the onPause(), so the updates start and stop according to the activity visibility.
Short and sweet :). what I believe in.
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; // List of permissions required
public void askPermission()
{
for (String permission : PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
return;
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case 1:{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
//Do your work.
} else {
Toast.makeText(this, "Until you grant the permission, we cannot proceed further", Toast.LENGTH_SHORT).show();
}
return;
}
}
To sum it up for vb.net users, the free option (must have office installed):
Microsoft office assembies download:
Add reference to Microsoft.Office.Interop.Word.Application
Add using or import (vb.net) statement to Microsoft.Office.Interop.Word.Application
VB.NET example:
Dim word As Application = New Application()
Dim doc As Document = word.Documents.Open("c:\document.docx")
doc.Activate()
doc.SaveAs2("c:\document.pdf", WdSaveFormat.wdFormatPDF)
doc.Close()
Create a Route attribute for your method.
example
[Route("api/Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
You can call like these http://localhost/api/Get
The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.
LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.
LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.
Key features of LXD are:
There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.
However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.
The OpenStack nclxd plugin a list of features supported include:
stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support
By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.
For class and text xpath-
//div[contains(@class,'Caption') and (text(),'Model saved')]
and
For class and id xpath-
//div[contains(@class,'gwt-HTML') and @id="alertLabel"]
If you have luasocket installed:
local socket = require 'socket'
socket.sleep(0.2)
Think about using nosql tools like neo4j for hierarchial structures. e.g a networked application like linkedin uses couchbase (another nosql solution)
But use nosql only for data-mart level queries and not to store / maintain transactions
What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):
C#
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
VB
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
math.log2(x)
import math
log2 = math.log(x, 2.0)
log2 = math.log2(x) # python 3.3 or later
math.frexp(x)
If all you need is the integer part of log base 2 of a floating point number, extracting the exponent is pretty efficient:
log2int_slow = int(math.floor(math.log(x, 2.0)))
log2int_fast = math.frexp(x)[1] - 1
Python frexp() calls the C function frexp() which just grabs and tweaks the exponent.
Python frexp() returns a tuple (mantissa, exponent). So [1]
gets the exponent part.
For integral powers of 2 the exponent is one more than you might expect. For example 32 is stored as 0.5x26. This explains the - 1
above. Also works for 1/32 which is stored as 0.5x2?4.
Floors toward negative infinity, so log231 computed this way is 4 not 5. log2(1/17) is -5 not -4.
x.bit_length()
If both input and output are integers, this native integer method could be very efficient:
log2int_faster = x.bit_length() - 1
- 1
because 2n requires n+1 bits. Works for very large integers, e.g. 2**10000
.
Floors toward negative infinity, so log231 computed this way is 4 not 5.
Just got this, we can achieve it using onpaste:"return false"
, thanks to: http://sumtips.com/2011/11/prevent-copy-cut-paste-text-field.html
We have various other options available as listed below.
<input type="text" onselectstart="return false" onpaste="return false;" onCopy="return false" onCut="return false" onDrag="return false" onDrop="return false" autocomplete=off/><br>
As soon as a WHEN statement is true the break is implicit.
You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.
More information here: break in case statement in T-SQL
You would never want to run that, but you may want to source it.
. ~/.bash_profile
source ~/.bash_profile
both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
Closing Visual Studio and re-opening worked for me. Must be a weird bug.
\b in regular expressions match word boundaries (i.e. the location between the first word character and non-word character):
$ echo "bar embarassment" | sed "s/\bbar\b/no bar/g"
no bar embarassment
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19
It's just a colon delimited key-value.
ETag: "xyzzy"
It can be any type of text data - I generally include a JSON string with the identifier of the item created. The ease of testing alone makes including it worthwhile.
ETag: "{ id: 1234, uri: 'http://domain.com/comments/1234', type: 'comment' }"
In this example, the identifier, the uri, and type of the created item are the "resource characteristics and location".
you can use Https url to login
i guess you are trying to login with ssh url when you say git push if it as asking only password consider you are connecting through ssh.better you use http url.
array_splice($array, 0, 1);
I think the easiest workaround would be to use 'select' with 'multiple' specified:
<select ng-model="selectedfruit" multiple ng-options="v for v in fruit"></select>
Otherwise, I think you'll have to process the list to construct the list
(by $watch()
ing the model array bind with checkboxes).
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
x is already integer(x=0) and again you trying to make x again integer and also you gave indexing which is beyound the limit because x already has only one indexing (0) and you are trying to give indexing same as age so thats why you get this error. use this simple code
name1 = input("What's your name? ")
age1 = int(input ("how old are you?" ))
x=0
twentyone = str(21-age1)
print("Hi, " +name1+ " you will be 21 in: " + twentyone + " years.")
Checking the file extension is not considered best practice. The preferred method of accomplishing this task is by checking the files MIME type.
From PHP:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
The above example will output something similar to which you should be checking.
text/html
image/gif
application/vnd.ms-excel
Although MIME types can also be tricked (edit the first few bytes of a file and modify the magic numbers), it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.
Typically the register key and value are constants in the program. If so, here is an example how to read a DWORD registry value Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled
:
#include <windows.h>
DWORD val;
DWORD dataSize = sizeof(val);
if (ERROR_SUCCESS == RegGetValueA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\FileSystem", "LongPathsEnabled", RRF_RT_DWORD, nullptr /*type not required*/, &val, &dataSize)) {
printf("Value is %i\n", val);
// no CloseKey needed because it is a predefined registry key
}
else {
printf("Error reading.\n");
}
To adapt for other value types, see https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-reggetvaluea for complete spec.
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
SVN seems like a good choice under Windows, as pointed by other people.
If some of your developper wants to try GIT, it may always use GIT-SVN where the SVN repository is recreated in a GIT repository. Then he should be able to work locally with GIT and then use SVN to publish its changes to the main repository.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
You will find most likely your DB name is not correct, you will see the server name in VS like "DESKTOP-0I14BKI" but if you open up SSMS you will see DESKTOP-0I14BKI\SQLBLAHBLAH , simply add "\SQLBLAHBLAH" (instance name) to your "server name" in VS connection properties.
Here is sample usage using expect
:
#!/usr/bin/expect
set timeout 360
spawn my_command # Replace with your command.
expect "Do you want to continue?" { send "\r" }
Check: man expect
for further information.
Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
}else{
geocoder = new Geocoder(activity);
try {
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lat=(double)user.get(0).getLatitude();
lng=(double)user.get(0).getLongitude();
System.out.println(" DDD lat: " +lat+", longitude: "+lng);
}catch (Exception e) {
e.printStackTrace();
}
}
Watch that your file name doesn't have :
in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt
and then scp no-colons.txt server:
then don't forget to mv
back on the server. Just in case this was an issue.
If accessing/printing single element lists (e.g., sequentially or filtered):
my_list = [u'String'] # sample element
my_list = [str(my_list[0])]
printf
allows formatting with width specifiers. For example,
printf( "%-30s %s\n", "Starting initialization...", "Ok." );
You would use a negative width specifier to indicate left-justification because the default is to use right-justification.
/html/body/table/tbody/tr[9]/td[1]
In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.
You can call another action inside a action as follows:
redirect_to action: 'action_name'
class MyController < ApplicationController
def action1
redirect_to action: 'action2'
end
def action2
end
end
If you are using CORS middleware and you want to send withCredentials
boolean true, you can configure CORS like this:
var cors = require('cors'); _x000D_
app.use(cors({credentials: true, origin: 'http://localhost:5000'}));
_x000D_
`
You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)
It seems you don't even have to specify the compression any more. The following snippet loads the data from filename.zip into df.
import pandas as pd
df = pd.read_csv('filename.zip')
(Of course you will need to specify separator, header, etc. if they are different from the defaults.)
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
Simplest Answer -----------------------------------------
[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults !visiblepw
Defaults always_set_home
Defaults match_group_by_gid
Defaults always_query_group_plugin
Defaults env_reset
Defaults env_keep = "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root ALL=(ALL) ALL
%wheel ALL=(ALL) ALL
[root@node1 ~]#
According to the site I'll post below, it's all how you set up your server. One example they show is this:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
and their route function:
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
This is one way. http://www.nodebeginner.org/
From another site, they create a page and then load it. This might be more of what you're looking for.
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
Just wanted to add a little bit more on this.
With the new angular 2.0.0 final release (sept 14, 2016), if you use custom html tags then it will report that Template parse errors
. A custom tag is a tag you use in your HTML that's not one of these tags.
It looks like the line schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
need to be added to each component where you are using custom HTML tags.
EDIT: The schemas
declaration needs to be in a @NgModule
decorator. The example below shows a custom module with a custom component CustomComponent
which allows any html tag in the html template for that one component.
custom.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomComponent } from './custom.component';
@NgModule({
declarations: [ CustomComponent ],
exports: [ CustomComponent ],
imports: [ CommonModule ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class CustomModule {}
custom.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-custom-component',
templateUrl: 'custom.component.html'
})
export class CustomComponent implements OnInit {
constructor () {}
ngOnInit () {}
}
custom.component.html
In here you can use any HTML tag you want.
<div class="container">
<boogey-man></boogey-man>
<my-minion class="one-eyed">
<job class="plumber"></job>
</my-minion>
</div>
Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix
package for e.g.) for sparse matrices.
Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc()
to clear now unused memory, or, better only create the object you need in one session.
If the above cannot help, get a 64-bit machine with as much RAM as you can afford, and install 64-bit R.
If you cannot do that there are many online services for remote computing.
If you cannot do that the memory-mapping tools like package ff
(or bigmemory
as Sascha mentions) will help you build a new solution. In my limited experience ff
is the more advanced package, but you should read the High Performance Computing
topic on CRAN Task Views.
It's not a bug, it's a feature :-)
When you look at the '=' operator in Python, don't think in terms of assignment. You don't assign things, you bind them. = is a binding operator.
So in your code, you are giving the value 1 a name: a. Then, you are giving the value in 'a' a name: b. Then you are binding the value 2 to the name 'a'. The value bound to b doesn't change in this operation.
Coming from C-like languages, this can be confusing, but once you become accustomed to it, you find that it helps you to read and reason about your code more clearly: the value which has the name 'b' will not change unless you explicitly change it. And if you do an 'import this', you'll find that the Zen of Python states that Explicit is better than implicit.
Note as well that functional languages such as Haskell also use this paradigm, with great value in terms of robustness.
You could easily use:
label1.Text = dateTimePicker1.Value.Date.ToString("dd/MM/yyyy")
and if you want to change '/' or '-', just add this:
label1.Text = label1.Text.Replace(".", "-")
More info about DateTimePicker.CustomFormat Property: Link
I had the same problem, USB debugging enabled, device showing up in windows but I never got the question about RSA fingerprint when I connected my Nexus (6) device, nor did it show up in the Android Device Manager.
BUT In the windows device manager I did have an entry saying it was an android device and Composite ADB interface etc. Still didn't work. When I tried the previous tips about manually updating the drivers, Windows 8.1 just responded that "Windows has determined that the driver software for your device is up to date" this was not true. Looking at the driver details I saw that the driver was published by "ClockworkMod". I realized this must be because I had installed the Helium app sometime last year. So I uninstalled that, still had the same problem. Checked again, this time it was indeed google drivers, but version 7 published in 2012 (and not version 11 published 2014). I uninstalled these AS WELL and then tried the trick of reinstalling the driver from the SDK located in: %localappdata%\Android\sdk\extras\google\usb_driver
Now when I replugged my device it finally works and can be debugged with Android Studio. Indeed a driver problem.
Sounds like you may already have your answer but in case you need one more place to look you may want to check out the size and activity of your temp DB. We had an issue like this once at a client site where a few times a day their performance would horribly degrade and occasionally timeout. The problem turned out to be a separate application that was thrashing the temp DB so much it was affecting overall server performance.
Good luck with the continued troubleshooting!
You can resolve this issue with php.
$mydate = strtotime($startdate);
$newformat = date('d-m-Y',$mydate);
echo '<tr>';
echo ' <td data-sort="'. $mydate .'">'.$newformat .'</td>';
You can use Vmware player to resize a vmdk. This removes the round trip conversion (noted in other posts) if you want to keep it in vmdk format. Just make sure that when you add the vmdk into vmware, don't click upgrade format when prompted, keep the current one in case VirtualBox doesn't accept it.
Try like this:
I think you need to use the full path at the command line, something like this, perhaps:
C:\xampp\mysql\bin\mysql -u {username} -p {databasename} < file_name.sql
Refer this link also:
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
It is done to maintain the arrangement of bytes which is sent in the network(Endianness). Depending upon architecture of your device,data can be arranged in the memory either in the big endian format or little endian format. In networking, we call the representation of byte order as network byte order and in our host, it is called host byte order. All network byte order is in big endian format.If your host's memory computer architecture is in little endian format,htons() function become necessity but in case of big endian format memory architecture,it is not necessary.You can find endianness of your computer programmatically too in the following way:->
int x = 1;
if (*(char *)&x){
cout<<"Little Endian"<<endl;
}else{
cout<<"Big Endian"<<endl;
}
and then decide whether to use htons() or not.But in order to avoid the above line,we always write htons() although it does no changes for Big Endian based memory architecture.
One way to make sense of null and undefined is to understand where each occurs.
Expect a null return value in the following situations:
Methods that query the DOM
console.log(window.document.getElementById("nonExistentElement"));
//Prints: null
JSON responses received from an Ajax request
{
name: "Bob",
address: null
}
New functionality that is in a state of flux. The following returns null:
var proto = Object.getPrototypeOf(Object.getPrototypeOf({}));
// But this returns undefined:
Object.getOwnPropertyDescriptor({}, "a");
All other cases of non-existence are denoted by undefined (as noted by @Axel). Each of the following prints "undefined":
var uninitalised;
console.log(uninitalised);
var obj = {};
console.log(obj.nonExistent);
function missingParam(missing){
console.log(missing);
}
missingParam();
var arr = [];
console.log(arr.pop());
Of course if you decide to write var unitialised = null; or return null from a method yourself then you have null occurring in other situations. But that should be pretty obvious.
A third case is when you want to access a variable but you don't even know if it has been declared. For that case use typeof to avoid a reference error:
if(typeof unknown !== "undefined"){
//use unknown
}
In summary check for null when you are manipulating the DOM, dealing with Ajax, or using certain ECMAScript 5 features. For all other cases it is safe to check for undefined with strict equality:
if(value === undefined){
// stuff
}
let uuid = ((new Date().getTime()).toString(36))+'_'+(Date.now() + Math.random().toString()).split('.').join("_")
sample result "k3jobnvt_15750033412250_18299601769317408"
Use:
File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }
where your options are:
r
- Read only. The file must exist. w
- Create an empty file for writing. a
- Append to a file.The file is created if it does not exist. r+
- Open a file for update both reading and writing. The file must exist. w+
- Create an empty file for both reading and writing. a+
- Open a file for reading and appending. The file is created if it does not exist. In your case, 'w'
is preferable.
OR you could have:
out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close
I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html
The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.
According to How to convert Strings to and from UTF8 byte arrays in Java:
String s = "some text here";
byte[] b = s.getBytes("UTF-8");
System.out.println(b.length);
I tested all the answers here, but for me, none worked. So I studied a bit the problem, and finally I found the connection string needed. To get this string, you do:
1. in you project name:
a. right click the project name,
b. click Add,
c. select SQL Server Database (obviously you can rename it as you wish).
Now the new desired database will be added to your project.
2. The database is visible in the Server Explorer window.
3. Left click the database name in the Server Explorer window; now check the Solution Explorer window, and you will find the "Connection String", along side with Provider, State, Type, Version.
4. Copy the connection string provided, and put it in the Page_Load method:
string source = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\x\x\documents\visual studio 2013\Projects\WebApplication3\WebApplication3\App_Data\Product.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//your code here;
conn.Close();
I renamed my database as Product. Also, in the "AttachDbFilename", you must replace "c:\x\x\documents\" with your path to the phisical address of the .mdf file.
It worked for me, but I must mention this method works for VS2012 and VS2013. Don't know about other versions.
given the sorted content of your array, there is an even faster method: searchsorted.
import time
N = 10000
aa = np.arange(-N,N)
%timeit np.searchsorted(aa, N/2)+1
%timeit np.argmax(aa>N/2)
%timeit np.where(aa>N/2)[0][0]
%timeit np.nonzero(aa>N/2)[0][0]
# Output
100000 loops, best of 3: 5.97 µs per loop
10000 loops, best of 3: 46.3 µs per loop
10000 loops, best of 3: 154 µs per loop
10000 loops, best of 3: 154 µs per loop
Kind of a confusing group of answers, in part because the title of the question is actually much larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.
Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.
public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
string newValue)
{
return Regex.Replace(str,
Regex.Escape(findMe),
Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
RegexOptions.IgnoreCase);
}
So...
"œ".ReplaceCaseInsensitiveFind("oe", "")
, though he may have had a slightly different behavior in mind.Unfortunately, @HA 's comment that you have to Escape
all three isn't correct. The initial value and newValue
doesn't need to be.
Note: You do, however, have to escape $
s in the new value that you're inserting if they're part of what would appear to be a "captured value" marker. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...
"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")
Here's the error:
An unhandled exception of type 'System.ArgumentException' occurred in System.dll
Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.
Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read Spolsky on encodings) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on "insecure regular expressions" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is $10
really a valid "capture value" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.
That weird $
escaping (and that Regex.Escape
didn't escape captured value patterns like $0
as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842
You should replace the old OpenSSL binary file by the new one via a symlink:
sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`
Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.
I suppose you have figured it out by now. The answer is hidden in your first mail itself.
The make
command by default looks for makefile
, Makefile
, and GNUMakefile
as the input file and you are having Makefile.txt
in your folder. Just remove the file extension (.txt
) and it should work.
from pip.req import parse_requirements
did not work for me and I think it's for the blank lines in my requirements.txt, but this function does work
def parse_requirements(requirements):
with open(requirements) as f:
return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]
reqs = parse_requirements(<requirements_path>)
setup(
...
install_requires=reqs,
...
)
I'm not able to get my Chrome to autofill automatically on page load to test this, but you can try adding autocomplete="off"
to your fields, then removing the attribute on load:
$(window).load(function() { // can also try on document ready
$('input[autocomplete]').removeAttr('autocomplete');
});
I Think It Is Best!
And Use The Simple JS to make this work.
<script>
function privacypolicy(){
var privacypolicy1 = document.getElementById('privacypolicy');
var privacypolicy2 = ('display: inline;');
privacypolicy1.style= privacypolicy2;
}
function hideprivacypolicy(){
var privacypolicy1 = document.getElementById('privacypolicy');
var privacypolicy2 = ('display: none;');
privacypolicy1.style= privacypolicy2;
}
</script>
<style type="text/css">
.orthi-textlightbox-background{
background-color: rgba(30, 23, 23, 0.82);
font-family: siyam rupali;
position: fixed; top:0px;
bottom:0px;
right:0px;
width: 100%;
border: none;
margin:0;
padding:0;
overflow: hidden;
z-index:999999;
height: 100%;
}
.orthi-textlightbox-area {
background-color: #fff;
position: absolute;
width: 50%;
left: 300px;
top: 200px;
padding: 20px 10px;
border-radius: 6px;
}
.orthi-textlightbox-area-close{
font-weight: bold;
background-color:black;
color: white;
border-radius: 50%;
padding: 10px;
float: right;
border: 1px solid black;
box-shadow: 0 0 10px 0 rgba(33, 157, 216, 0.82);
margin-top:-30px;
margin-right:-30px;
cursor:pointer;
}
</style>
<button onclick="privacypolicy()">Show Content</button>
<div id="privacypolicy" class="orthi-textlightbox-background" style="display:none;">
<div class="orthi-textlightbox-area">
LOL<button class="orthi-textlightbox-area-close" onclick="hideprivacypolicy()">×</button>
</div>
</div>
If you have a numpy array you can do this:
import numpy as np
from matplotlib import pyplot as plt
data = np.array([
[1, 2],
[2, 3],
[3, 6],
])
x, y = data.T
plt.scatter(x,y)
plt.show()
Try this:
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);