In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
All credits are to Frank Tzanabetis. However this is the shortest direct example, that also survives in case of empty string or broken original JSON string:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
...
try
{
return JToken.Parse(jsonString).ToString(Formatting.Indented);
}
catch
{
return jsonString;
I know this is not a coding answer but it is what the OP wanted and what I have spent half the day trying to achieve - print from a web page with page numbers.
Yes, it is two steps instead of one but I haven't been able to find any CSS option despite several hours of searching. Real shame all the browsers removed the functionality that used to allow it.
ES6 (Firefox and Chrome already support it (Destructuring Assignment Array Matching)):
let a = 5, b = 6;_x000D_
[a, b] = [b, a];_x000D_
console.log(`${a} ${b}`);
_x000D_
restarting the adb server as root worked for me. see:
derek@zoe:~/Downloads$ adb sideload angler-ota-mtc20f-5a1e93e9.zip
loading: 'angler-ota-mtc20f-5a1e93e9.zip'
error: insufficient permissions for device
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX no permissions
derek@zoe:~/Downloads$ adb kill-server
derek@zoe:~/Downloads$ sudo adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
derek@zoe:~/Downloads$ adb devices
List of devices attached
XXXXXXXXXXXXXXXX sideload
There is a static method on the Thread
Class that will return the number of active threads controlled by the JVM:
Thread.activeCount()
Returns the number of active threads in the current thread's thread group.
Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.
SELECT * FROM "comments" JOIN (
SELECT 1 as "id",1 as "order" UNION ALL
SELECT 3,2 UNION ALL SELECT 2,3 UNION ALL SELECT 4,4
) j ON "comments"."id" = j."id" ORDER BY j.ORDER
or if you prefer evil over good:
SELECT * FROM "comments" WHERE ("comments"."id" IN (1,3,2,4))
ORDER BY POSITION(','+"comments"."id"+',' IN ',1,3,2,4,')
If someone else have got a similar error message, you probably built the app with optimisations(production) flag on and that's why the error message is not that communicative. Another possibility that you have got the error under development (from i386 I know you were using simulator). If that is the case, change the build environment to development and try to reproduce the situation to get a more specific error message.
You should restart apache or httpd, not mysqld
sudo service httpd restart
or
sudo /etc/init.d/apache2 restart
Do you specify a user name and password to log on? What exactly is your complete command line?
If you're running on your own box, you can either specify a username/password, or use the -E
parameter to log on with your Windows credentials (if those are permitted in your SQL server installation).
Marc
Being a geezer programmer, many of my school programming projects used text menu driven interactions. Virtually all used something like the following logic for the main procedure:
do
display options
get choice
perform action appropriate to choice
while choice is something other than exit
Since school days, I have found that I use the while loop more frequently.
View->ToolBar
& View->Tool Buttons
Project
would be visible, right click on it and
press Autoscroll to source
and then run your code.This worked for me.
Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.
If you have a backup SQL file then you can easily Restore it. Just follow the instructions, given in the below
1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example: cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql
Type password for your postgres user if needed and let Postgres to do its work. Then you can check the restore process.
You should install both 32bit & 64bit java (At least JRE), that in case you're using 64bit OS.
using namespaces and subqueries You can do it:
declare @data table (RequestID varchar(20), CreatedDate datetime, HistoryStatus varchar(20))
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000001','8/26/2009 1:07:01 PM','Completed');
insert into @data values ('CF-0000112','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000113','8/26/2009 1:07:01 PM','For Review');
insert into @data values ('CF-0000114','8/26/2009 1:07:01 PM','Completed');
insert into @data values ('CF-0000115','8/26/2009 1:07:01 PM','Completed');
select d1.RequestID,d1.CreatedDate,d1.HistoryStatus
from @data d1
where d1.HistoryStatus = 'Completed'
union all
select d2.RequestID,d2.CreatedDate,d2.HistoryStatus
from @data d2
where d2.HistoryStatus = 'For Review'
and d2.RequestID not in (
select RequestID
from @data
where HistoryStatus = 'Completed'
and CreatedDate = d2.CreatedDate
)
Above query returns
CF-0000001, 2009-08-26 13:07:01.000, Completed
CF-0000114, 2009-08-26 13:07:01.000, Completed
CF-0000115, 2009-08-26 13:07:01.000, Completed
CF-0000112, 2009-08-26 13:07:01.000, For Review
CF-0000113, 2009-08-26 13:07:01.000, For Review
Under
Provisioning -> Distribution -> Distribution Provisioning Profiles
I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).
What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)
var htmlEntities = [
{regex:/&/g,entity:'&'},
{regex:/>/g,entity:'>'},
{regex:/</g,entity:'<'},
{regex:/"/g,entity:'"'},
{regex:/á/g,entity:'á'},
{regex:/é/g,entity:'é'},
{regex:/í/g,entity:'í'},
{regex:/ó/g,entity:'ó'},
{regex:/ú/g,entity:'ú'}
];
total = <some string value>
for(v in htmlEntities){
total = total.replace(htmlEntities[v].regex, htmlEntities[v].entity);
}
A array solution
well! you can actually create a bunch of custom HTML attributes by disguising the data attributes in what you actually want.
eg.
[attribute='value']{
color:red;
}
<span attribute="value" >hello world</span>
It apparently works but that would invalidate your document, there is no need of using JScript for you to have custom attributes or even elements unless you have to, you just need to treat your new formulated(custom) attributes just the same way you treat your "data" attribute
Remember "invalid" does not mean anything. The document will load fine at all the time. and some browsers would actually validate your document only by the presence of DOCTYPE....., you actually know what I mean.
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
None
is just a value that commonly is used to signify 'empty', or 'no value here'. It is a signal object; it only has meaning because the Python documentation says it has that meaning.
There is only one copy of that object in a given Python interpreter session.
If you write a function, and that function doesn't use an explicit return
statement, None
is returned instead, for example. That way, programming with functions is much simplified; a function always returns something, even if it is only that one None
object.
You can test for it explicitly:
if foo is None:
# foo is set to None
if bar is not None:
# bar is set to something *other* than None
Another use is to give optional parameters to functions an 'empty' default:
def spam(foo=None):
if foo is not None:
# foo was specified, do something clever!
The function spam()
has a optional argument; if you call spam()
without specifying it, the default value None
is given to it, making it easy to detect if the function was called with an argument or not.
Other languages have similar concepts. SQL has NULL
; JavaScript has undefined
and null
, etc.
Note that in Python, variables exist by virtue of being used. You don't need to declare a variable first, so there are no really empty variables in Python. Setting a variable to None
is then not the same thing as setting it to a default empty value; None
is a value too, albeit one that is often used to signal emptyness. The book you are reading is misleading on that point.
It works the same way for axes: parse(text='70^o*N')
will raise the o
as a superscript (the *N
is to make sure the N doesn't get raised too).
labelsX=parse(text=paste(abs(seq(-100, -50, 10)), "^o ", "*W", sep=""))
labelsY=parse(text=paste(seq(50,100,10), "^o ", "*N", sep=""))
plot(-100:-50, 50:100, type="n", xlab="", ylab="", axes=FALSE)
axis(1, seq(-100, -50, 10), labels=labelsX)
axis(2, seq(50, 100, 10), labels=labelsY)
box()
Simply create a new external tool configuration (from Eclipse Run -> External Tools)
for example - To open Cygwin terminal on the current resource directory:
Location:
C:\cygwin\bin\mintty.exe
Working Directory:
${container_loc}
Arguments:
-i /Cygwin-Terminal.ico
-"cygpath -p '${container_loc}' | xargs cd"
PHP uses Content-Type "text/html" as default - which is pretty similar to "text/plain" - and this explains why you don't see any differences. text/plain is necessary if you want to output text as is (including <>-symbols). Examples:
header("Content-Type: text/plain");
echo "<b>hello world</b>";
// Output: <b>hello world</b>
header("Content-Type: text/html");
echo "<b>hello world</b>";
// Output: hello world
I think android:screenOrientation="portrait"
can be used for individual activities. So use that attribute in <activity>
tag like :
<activity android:name=".<Activity Name>"
android:label="@string/app_name"
android:screenOrientation="portrait">
...
</activity>
-Module name gulp-task
-Project name project-x
You want to link gulp-task:
1: Go to the gulp-task directory then do npm link
this will symlink the project to your global modules
2: Go to your project project-x then do npm install
make sure to remove the current node_modules directory
Now you want to remove this madness and use the real gulp-task, we have two options:
1: Go to your project and do npm unlink gulp-task
this will remove the linked installed module
2: Go to the gulp-task directory and do npm unlink
to remove symlink. Notice we didn't use the name of the module
3: celebrate
What if this didn't work, verify by locating your global installed module. My are location ls -la /usr/local/lib/node_modules/
if you are using nvm it will be a different path
1: locate your global dependencies cd /usr/local/lib/node_modules/
2: removing symlink is simply using the rm
command
rm gulp-task
make sure you don't have /
at the end
rm gulp-task/
is wrong
rm gulp-task
??
One advantage you get with the approach mentioned by @Tom is that you don't have to create any constructors in the SomeManager, and hence limiting the clients to instantiate it.
@RunWith(MockitoJUnitRunner.class)
public class SomeManagerTest {
@InjectMocks
private SomeManager someManager;
@Mock
private SomeDependency someDependency; // this will be injected into someManager
//You don't need to instantiate the SomeManager with default contructor at all
//SomeManager someManager = new SomeManager();
//Or SomeManager someManager = new SomeManager(someDependency);
//tests...
}
Whether its a good practice or not depends on your application design.
If you're executing this through PHP, what about this?
$hQuery = mysql_query("SELECT * FROM users");
while($hRow = mysql_fetch_array($hQuery)) {
$hOut .= $hRow['username'] . ", ";
}
$hOut = substr($hOut, 0, strlen($hOut) - 1);
echo $hOut;
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
Ok this maight not be the fastest but it's... simple.
str = " aaa ";
int len = str.length();
// rtrim
while(str[len-1] == ' ') { str.erase(--len,1); }
// ltrim
while(str[0] == ' ') { str.erase(0,1); }
In Ubuntu if you execute the script with sh scriptname.sh
you get this problem.
Try executing the script with ./scriptname.sh
instead.
I combined the answer above with certbot SSL cert and CORS access-control-allow-headers and got it working so I thought I would share the results.
Apache httpd.conf added to the bottom of the file:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Apache VirtualHost settings (doc root for PHP is under Apache and SSL with Certbot, while node.js/socket.io site runs on port 3000 - and uses SSL cert from Apache) Also notice the node.js site uses the proxy for the folder /nodejs, socket.io, and ws (websockets):
<IfModule mod_ssl.c>
<VirtualHost *:443>
ServerName www.example.com
ServerAlias www.example.com
DocumentRoot /var/html/www.example.com
ErrorLog /var/html/log/error.log
CustomLog /var/html/log/requests.log combined
SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
RewriteEngine On
RewriteCond %{REQUEST_URI} ^socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /{.*} ws://localhost:3000/$1 [P,L]
RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteRule /(.*) ws://localhost:3000/$1 [P,L]
ProxyPass /nodejs http://localhost:3000/
ProxyPassReverse /nodejs http://localhost:3000/
ProxyPass /socket.io http://localhost:3000/socket.io
ProxyPassReverse /socket.io http://localhost:3000/socket.io
ProxyPass /socket.io ws://localhost:3000/socket.io
ProxyPassReverse /socket.io ws://localhost:3000/socket.io
</VirtualHost>
</IfModule>
Then my node.js app (app.js):
var express = require('express');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
next();
});
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen({host:'0.0.0.0',port:3000});
I force a ip4 listener, but that is optional - you can substitute:
http.listen(3000);
node.js app (app.js) code continues with:
io.of('/nodejs').on('connection', function(socket) {
//optional settings:
io.set('heartbeat timeout', 3000);
io.set('heartbeat interval', 1000);
//listener for when a user is added
socket.on('add user', function(data) {
socket.join('AnyRoomName');
socket.broadcast.emit('user joined', data);
});
//listener for when a user leaves
socket.on('remove user', function(data) {
socket.leave('AnyRoomName');
socket.broadcast.emit('user left', data);
});
//sample listener for any other function
socket.on('named-event', function(data) {
//code....
socket.broadcast.emit('named-event-broadcast', data);
});
// add more listeners as needed... use different named-events...
});
finally, on the client side (created as nodejs.js):
//notice the /nodejs path
var socket = io.connect('https://www.example.com/nodejs');
//listener for user joined
socket.on('user joined', function(data) {
// code... data shows who joined...
});
//listener for user left
socket.on('user left', function(data) {
// code... data shows who left...
});
// sample listener for any function:
socket.on('named-event-broadcast', function(data) {
// this receives the broadcast data (I use json then parse and execute code)
console.log('data1=' + data.data1);
console.log('data2=' + data.data2);
});
// sample send broadcast json data for user joined:
socket.emit('user joined', {
'userid': 'userid-value',
'username':'username-value'
});
// sample send broadcast json data for user left
//(I added the following with an event listener for 'beforeunload'):
// socket.emit('user joined', {
// 'userid': 'userid-value',
// 'username':'username-value'
// });
// sample send broadcast json data for any named-event:
socket.emit('named-event', {
'data1': 'value1',
'data2':'value2'
});
In this example when the JS loads, it will emit to the socket a "named-event" sending the data in JSON to the node.js/socket.io server.
Using the io and socket on the server under path /nodejs (connected by client), receives the data an then resends it as a broadcast. Any other users in the socket would receive the data with their listener "named-event-broadcast". Note that the sender does not receive their own broadcast.
Well, the message is pretty much self-explanatory. You did not tell git what your name and email address is.
Open a command line and type:
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
Of course you should enter your real name and email. Afterwards git knows who you are and is able to insert this information in your commits.
Seems like smartgit does not add the git binary to your path. You have to add its path to the PATH environment variable or first change to the corresponding directory. You can find a screencast here: http://blog.dragndream.com/?p=97
As an example, mocha would normally be a devDependency, since testing isn't necessary in production, while express would be a dependency.
By keys()
and values()
methods of dictionary and zip
.
zip
will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
This worked for me.
<select ng-model="somethingHere" ng-init="somethingHere='Cool'">
<option value="Cool">Something Cool</option>
<option value="Else">Something Else</option>
</select>
By the RFC7231 it does not matter and may be empty
How we implement json api standard based solution in the project:
post/put: outputs object attributes as in get (field filter/relations applies the same)
delete: data only contains null (for its a representation of missing object)
status for standard delete: 200
The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click
event handler of that menu entry.
If 'localhost' doesn't work but 127.0.0.1 does. Make sure your local hosts file points to the correct location. (/etc/hosts for linux/mac, C:\Windows\System32\drivers\etc\hosts for windows).
Also, make sure your user is allowed to connect to whatever database you're trying to select.
What include
does is copying all the contents from the file (which is the argument inside the <>
or the ""
), so when the preproccesor finishes its work main.cpp
will look like:
// iostream stuff
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
So foo will be defined in main.cpp
, but a definition also exists in foop.cpp
, so the compiler "gets confused" because of the function duplication.
Why dont you just do it in SQL?
DELETE FROM SomeTable
If you're using Python 2.5 or later, the uuid module is already included with the Python standard distribution.
Ex:
>>> import uuid
>>> uuid.uuid4()
UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14')
You can do as @rmobis has specified in his answer, [Adding something more into it]
Using order by
twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by
:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As @rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate
in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
I'm posting this answer with the hope of someone sharing with me if and why it would be a bad idea. In my application, I have a property of Type that I want to check to be sure it is typeof(A) or typeof(B), where B is any class derived from A. So my code:
public class A
{
}
public class B : A
{
}
public class MyClass
{
private Type _helperType;
public Type HelperType
{
get { return _helperType; }
set
{
var testInstance = (A)Activator.CreateInstance(value);
if (testInstance==null)
throw new InvalidCastException("HelperType must be derived from A");
_helperType = value;
}
}
}
I feel like I might be a bit naive here so any feedback would be welcome.
There are some default or existing modules in node.js when you download and install node.js like http, sys etc.
Since they are already in node.js, when we want to use these modules we basically do like import modules, but why? because they are already present in the node.js. Importing is like taking them from node.js and putting them into your program. And then using them.
Whereas Exports is exactly the opposite, you are creating the module you want, let's say the module addition.js and putting that module into the node.js, you do it by exporting it.
Before I write anything here, remember, module.exports.additionTwo is same as exports.additionTwo
Huh, so that's the reason, we do like
exports.additionTwo = function(x)
{return x+2;};
Be careful with the path
Lets say you have created an addition.js module,
exports.additionTwo = function(x){
return x + 2;
};
When you run this on your NODE.JS command prompt:
node
var run = require('addition.js');
This will error out saying
Error: Cannot find module addition.js
This is because the node.js process is unable the addition.js since we didn't mention the path. So, we have can set the path by using NODE_PATH
set NODE_PATH = path/to/your/additon.js
Now, this should run successfully without any errors!!
One more thing, you can also run the addition.js file by not setting the NODE_PATH, back to your nodejs command prompt:
node
var run = require('./addition.js');
Since we are providing the path here by saying it's in the current directory ./
this should also run successfully.
For posterity sake,the answer maybe too late.You should check for the return value of the variable and throw an exception. In that case you are assured that the program will jump from where the exception is being raised to the catch block. Find below.
try{
$tableAresults = $dbHandler->doSomethingWithTableA();
if (!tableAresults)
throw new Exception('Problem with tableAresults');
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if (!tableBresults)
throw new Exception('Problem with tableBresults');
} catch (Exception $e) {
echo $e->getMessage();
}
Say A:A contains the post codes, you could add a B column and put a 1 in each cell. In C1, put =SUMIF(A:A, A1, B:B) and Drag it down your sheet. That would give you the first desired result listed in your question.
EDIT: As Corey pointed out, you can just use COUNTIF(A:A, A1). As I mentioned in the comments you can copy paste special the row with formulas to hard code the counts, the select column A and click remove duplicates (entire row) to get your ideal result.
You can even simulate a queue using only one stack. The second (temporary) stack can be simulated by the call stack of recursive calls to the insert method.
The principle stays the same when inserting a new element into the queue:
A Queue class using only one Stack, would be as follows:
public class SimulatedQueue<E> {
private java.util.Stack<E> stack = new java.util.Stack<E>();
public void insert(E elem) {
if (!stack.empty()) {
E topElem = stack.pop();
insert(elem);
stack.push(topElem);
}
else
stack.push(elem);
}
public E remove() {
return stack.pop();
}
}
You have to use Promise to print or store values of element.
var ExpectedValue:string ="AllTestings.com";
element(by.id("xyz")).getAttribute("value").then(function (Text) {
expect(Text.trim()).toEqual("ExpectedValue", "Wrong page navigated");//Assertion
console.log("Text");//Print here in Console
});
Try Like this.
For Inserting into DB
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";
$qry = mysqli_query($db, $query);
For Accessing image From Blob
$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';
Hope It will help you.
Thanks.
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute()
it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
std::string
is the C++ equivalent: It's mutable.
I ran into this issue but had a different fix. It involved updating the Control Panel>Administrative Tools>IIS Manager
and reverting my App site's Managed Pipeline from Integrated
to Classic
.
To add to MattDMo's answer, you can get the exact font that's used on Linux like so (the example is from Xubuntu 14.04):
$ fc-match Monospace
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"
A short answer in what context the 3 options are used:
To keep the current changes in the code but to rewrite the commit history:
soft
: You can commit everything at once and create a new commit with a new description (if you use torotise git or any most other GUIs, this is the one to use, as you can still tick which files you want in the commit and make multiple commits that way with different files. In Sourcetree all files would be staged for commit.)mixed
: You will have to add the individual files again to the index before you make commits (in Sourcetree all the changed files would be unstaged)To actually lose your changes in the code as well:
hard
: you don't just rewrite history but also lose all your changes up to the point you resetIt is used to stop the propagation of the event. You see when you have two elements both with a click event handler (for example)
-----------------------------------
| element1 |
| ------------------------- |
| |element2 | |
| ------------------------- |
| |
-----------------------------------
If you click on the inner element (element2) it will trigger a click event in both elements: 1 and 2. It is called "Event bubbling". If you want to handle the event in element2 only, then the event handler has to return false to stop the event propagation.
Another example will be the link onclick handler. If you want to stop a link form working. You can add an onclick handler and return false. To stop the event from propagating to the default handler.
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
You can use the JsonTextReader
to read the JSON and iterate over the tokens:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
Console.WriteLine("{0} - {1} - {2}",
reader.TokenType, reader.ValueType, reader.Value);
}
}
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
Swift 3:
Simplest way to adjust only size:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
if let textlabel = header.textLabel {
textlabel.font = textlabel.font.withSize(15)
}
}
This is because you're using getActivity()
inside an inner class. Try using:
SherlockFragmentActivity.this.getActivity()
instead, though there's really no need for the getActivity()
part. In your case,
SherlockFragmentActivity .this
should suffice.
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
I know this was not your case but I had the same problem because H2 was creating the tables with UPPERCASE names then behaving case-sensitive, even though in all scripts (including in the creation ones) i used lowercase.
Solved by adding ;DATABASE_TO_UPPER=false
to the connection URL.
in Firefox 39 I've found that setting a border to the select element will render the arrow as (2). No border set, will render the arrow as (1). I think it's a bug.
In Swift 4:
let formatString = "12345"
if let number = Decimal(string:formatString){
print("String contains only number")
}
else{
print("String doesn't contains only number")
}
How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
There are already answers which describes about window.location.href property and window.open() method.
I will go by Objective use:
Use window.location.href. Set href property to the href of another page.
Use window.open(). Pass parameters as per your goal.
Use window.location.href. Get value of window.location.href property. You can also get specific protocol, hostname, hashstring from window.location object.
See Location Object for more information.
Handler answer in Kotlin :
1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :
fun delayFunction(function: ()-> Unit, delay: Long) {
Handler().postDelayed(function, delay)
}
2 - Then call it anywhere you needed it :
delayFunction({ myDelayedFunction() }, 300)
Varargs will work too!
Stream.of(T... values).collect(Collectors.toSet());
My issue was due to what physical USB female port I plugged the Arduino cable into on my D-Link DUB-H7 (USB hub) on Windows 10. I had my Arduino plugged into one of the two ports way on the right (in the image below). The USB cable fit, and it powers the Arduino fine, but the Arduino wasn't seeing the port for some reason.
Windows does not recognize these two ports. Any of the other ports are fair game. In my case, the Tools > Port menu was grayed out. In this scenario, the "Ports" section in the object explorer was hidden. So to show the hidden devices, I chose View > show hidden. COM1 was what showed up originally. When I changed it to COM3, it didn't work.
There are many places where the COM port can be configured.
Windows > Control Panel > Device Manager > Ports > right click Arduino > Properties > Port Settings > Advanced > COM Port Number: [choose port]
Windows > Start Menu > Arduino > Tools > Ports > [choose port]
Windows > Start Menu > Arduino > File > Preferences > @ very bottom, there is a label named "More preferences can be edited directly in the file".
C:\Users{user name}\AppData\Local\Arduino15\preferences.txt
target_package = arduino
target_platform = avr
board = uno
software=ARDUINO
# Warn when data segment uses greater than this percentage
build.warn_data_percentage = 75
programmer = arduino:avrispmkii
upload.using = bootloader
upload.verify = true
serial.port=COM3
serial.databits=8
serial.stopbits=1
serial.parity=N
serial.debug_rate=9600
# I18 Preferences
# default chosen language (none for none)
editor.languages.current =
The user preferences.txt overrides this one:
C:\Users{user name}\Desktop\avrdude.conf
... search for "com" ... "com1" is the default
Calendar calendar = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
String date = simpleDateFormat.format(newDate.getTime());
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
And use this style:
<style name="DatePickerDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">@color/colorPrimary</item>
</style>
Have you tried setting the painted border false?
JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);
It works on my mac :)
Or can use the Extension Splitter Trickster::getExtention()
function of https://github.com/secrethash/trickster
Trickster::getExtention('some-funny.image.jpg');
It returns jpg
Just had this problem, what worked for me was to use localhost.fiddler:
<endpoint address="http://localhost.fiddler/test/test.svc"
binding="basicHttpBinding"
bindingConfiguration="customBinding"
contract="test"
name="customBinding"/>
If I've understood your problem correctly, there are two possible problems here:
resultset
is null
- I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.resultset.getString(i++)
will get columns 1,2,3 and so on from each subsequent row.I think that the second point is probably your problem here.
Lets say you only had 1 row returned, as follows:
Col 1, Col 2, Col 3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
Edit:
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
RFC6648 recommends that you assume that your custom header "might become standardized, public, commonly deployed, or usable across multiple implementations." Therefore, it recommends not to prefix it with "X-" or similar constructs.
However, there is an exception "when it is extremely unlikely that [your header] will ever be standardized." For such "implementation-specific and private-use" headers, the RFC says a namespace such as a vendor prefix is justified.
Solved by removing the -webkit-transform
from the navbar:
-webkit-transform: translate3d(0, 0, 0);
pillaged from https://stackoverflow.com/a/12653766/391925
The question was to see if ping responded which this script does.
However this will not work if you get the Host Unreachable message as this returns ERRORLEVEL 0 and passes the check for Received = 1 used in this script, returning Link is UP from the script. Host Unreachable occurs when ping was delivered to target notwork but remote host cannot be found.
If I recall the correct way to check if ping was successful is to look for the string 'TTL' using Find.
@echo off
cls
set ip=%1
ping -n 1 %ip% | find "TTL"
if not errorlevel 1 set error=win
if errorlevel 1 set error=fail
cls
echo Result: %error%
This wont work with IPv6 networks because ping will not list TTL when receiving reply from IPv6 address.
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
Anyone who wants to do a deep copy (e.g. if your array contains objects) can use:
let arrCopy = JSON.parse(JSON.stringify(arr))
Then you can sort arrCopy
without changing arr
.
arrCopy.sort((obj1, obj2) => obj1.id > obj2.id)
Please note: this can be slow for very large arrays.
$('#input').datepicker({autoclose:true});
You need to use the await keyword when use async and your function return type should be generic Here is an example with return value:
public async Task<object> MethodName()
{
return await Task.FromResult<object>(null);
}
Here is an example with no return value:
public async Task MethodName()
{
await Task.CompletedTask;
}
Read these:
TPL: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx and Tasks: http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=vs.110).aspx
Async: http://msdn.microsoft.com/en-us/library/hh156513.aspx Await: http://msdn.microsoft.com/en-us/library/hh156528.aspx
The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .
like this:
BigDecimal bd1 = new BigDecimal("10.0001");
now, you can display bd1 as 10.0001
So simple. GOOD LUCK.
Suppose access a proxy server A(eg. nginx), and the server A forwards the request to another server B(eg. tomcat).
If this process continues for a long time (more than the proxy server read timeout setting), A still did not get a completed response of B. It happens.
for nginx, You can configure the proxy_read_timeout(in location) property to solve his.But this is usually not a good idea, if you set the value too high. This may hide the real error.You'd better improve the design to really solve this problem.
go to the url about:config
and paste each line:
network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10
I use AquaFold at work on Windows, but it's based on Java and supports Mac OS X.
My way of avoiding the force push is to create a new branch and continuing work on that new branch and after some stability, remove the old branch that was rebased:
For this the System.Timers.Timer
works best
// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it
myTimer.Enabled = true;
// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }
See Timer Class (.NET 4.6 and 4.5) for details
As long as the object is actually a SkyfilterClient
, then a cast should work. Here is a contrived example to prove this:
using System;
class Program
{
static void Main()
{
NetworkClient net = new SkyfilterClient();
var sky = (SkyfilterClient)net;
}
}
public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}
However, if it is actually a NetworkClient
, then you cannot magically make it become the subclass. Here is an example of that:
using System;
class Program
{
static void Main()
{
NetworkClient net = new NetworkClient();
var sky = (SkyfilterClient)net;
}
}
public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}
HOWEVER, you could create a converter class. Here is an example of that, also:
using System;
class Program
{
static void Main()
{
NetworkClient net = new NetworkClient();
var sky = SkyFilterClient.CopyToSkyfilterClient(net);
}
}
public class NetworkClient
{
public int SomeVal {get;set;}
}
public class SkyfilterClient : NetworkClient
{
public int NewSomeVal {get;set;}
public static SkyfilterClient CopyToSkyfilterClient(NetworkClient networkClient)
{
return new SkyfilterClient{NewSomeVal = networkClient.SomeVal};
}
}
But, keep in mind that there is a reason you cannot convert this way. You may be missing key information that the subclass needs.
Finally, if you just want to see if the attempted cast will work, then you can use is
:
if(client is SkyfilterClient)
cast
For 2005 and later, these will both give what you're looking for.
SELECT name FROM sys.schemas
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
For 2000, this will give a list of the databases in the instance.
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA
That's the "backward incompatability" noted in @Adrift's answer.
In SQL Server 2000 (and lower), there aren't really "schemas" as such, although you can use roles as namespaces in a similar way. In that case, this may be the closest equivalent.
SELECT * FROM sysusers WHERE gid <> 0
Try to use it
LayoutInflater inflater = (LayoutInflater).getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflate.from(YourActivity.this).inflate(R.layout.yourLayout, null);
I'm would recommend it:
<style>
.clearfix {
*zoom: 1;
}
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
ul.list {
list-style: none;
}
ul.list li {
display: inline-block;
}
</style>
<ul class="list clearfix">
<li>li-one</li>
<li>li-two</li>
<li>li-three</li>
<li>li-four</li>
</ul>
Contains information about how to fetch a resource from its location. For example:
http://example.com/mypage.html
ftp://example.com/download.zip
mailto:[email protected]
file:///home/user/file.txt
http://example.com/resource?foo=bar#fragment
/other/link.html
(A relative URL, only useful in the context of another URL)URLs always start with a protocol (http
) and usually contain information such as the network host name (example.com
) and often a document path (/foo/mypage.html
). URLs may have query parameters and fragment identifiers.
Identifies a resource by name. It always starts with the prefix urn:
For example:
urn:isbn:0451450523
to identify a book by its ISBN number.urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66
a globally unique identifierurn:publishing:book
- An XML namespace that identifies the document as a type of book.URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a "resolver". The document can then be downloaded from the URL.
URIs encompasses both URLs, URNs, and other ways to indicate a resource.
An example of a URI that is neither a URL nor a URN would be a data URI such as data:,Hello%20World
. It is not a URL or URN because the URI contains the data. It neither names it, nor tells you how to locate it over the network.
There are also uniform resource citations (URCs) that point to meta data about a document rather than to the document itself. An example of a URC would be an indicator for viewing the source code of a web page: view-source:http://example.com/
. A URC is another type of URI that is neither URL nor URN.
The w3 spec for HTML says that the href
of an anchor tag can contain a URI, not just a URL. You should be able to put in a URN such as <a href="urn:isbn:0451450523">
. Your browser would then resolve that URN to a URL and download the book for you.
Not that I know of, but modern web browser do implement the data URI scheme.
Good question. I've seen lots of places on the web that state this is true. I haven't been able to find any examples of something that is both a URL and a URN. I don't see how it is possible because a URN starts with urn:
which is not a valid network protocol.
No. Both relative and absolute URLs are URLs (and URIs.)
No. Both URLs with and without query parameters are URLs (and URIs.)
No. Both URLs with and without fragment identifiers are URLs (and URIs.)
tel:
URI a URL or a URN?For example tel:1-800-555-5555
. It doesn't start with urn:
and it has a protocol for reaching a resource over a network. It must be a URL.
Yes. The W3C realized that there is a ton of confusion about this. They issued a URI clarification document that says that it is now OK to use URL and URI interchangeably. It is no longer useful to strictly segment URIs into different types such as URL, URN, and URC.
I must add one more point in this thread. To install/uninstall 64-bit
version of assemblies one should use 64-bit
version of tool. To install a service, the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
"C:\YourFolder\YourService.exe"
and to uninstall the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -u
"C:\YourFolder\YourService.exe"
Since Java 11 you can do it even simpler:
import java.nio.file.Files;
Files.readString(Path path);
Files.readString?(Path path, Charset cs)
Easiest Way!!!
If you are using Entity Framework and your Visual Studio Version is 2012 or higher,then
Its done. Now restart your visual studio and build your code.
What do these packages do?
After installing these packages no additional Oracle client software is required to be installed to connect to database.
@synergetic I think @blesh suppose to put function validate as below
function validate(value) {
var valid = blacklist.indexOf(value) === -1;
ngModel.$setValidity('blacklist', valid);
return valid ? value : undefined;
}
ngModel.$formatters.unshift(validate);
ngModel.$parsers.unshift(validate);
What the error is telling you, is that refresh
isn't initialized. Note that you chose to make refresh
not optional, which in Swift means that it has to have a value before you call super.init
(or it's implicitly called, which seems to be your case). Either make refresh
optional (probably what you want) or initialize it in some way.
I would suggest reading the Swift introductory documentation again, which covers this in great length.
One last thing, not part of the answer, as pointed out by @Anil, there is a built in pull to refresh control in iOS called UIRefresControl
, which might be something worth looking into.
I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray()
According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.
This will work for you:
$phpExcel = new PHPExcel();
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
To apply font style to complete excel document:
$styleArray = array(
'font' => array(
'bold' => true,
'color' => array('rgb' => 'FF0000'),
'size' => 15,
'name' => 'Verdana'
));
$phpExcel->getDefaultStyle()
->applyFromArray($styleArray);
There is no variable included for that yet, so you have to use shell-out-read-file method:
sh 'pwd > workspace'
workspace = readFile('workspace').trim()
Or (if running on master node):
workspace = pwd()
My 2 cents here: using Java8 Streams + checking an exact string:
public enum MyEnum {
VALUE_1("Super"),
VALUE_2("Rainbow"),
VALUE_3("Dash"),
VALUE_3("Rocks");
private final String value;
MyEnum(String value) {
this.value = value;
}
/**
* @return the Enum representation for the given string.
* @throws IllegalArgumentException if unknown string.
*/
public static MyEnum fromString(String s) throws IllegalArgumentException {
return Arrays.stream(MyEnum.values())
.filter(v -> v.value.equals(s))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
}
}
** EDIT **
Renamed the function to fromString()
since naming it using that convention, you'll obtain some benefits from Java language itself; for example:
The following functor retrieves the key set of a map:
#include <vector>
#include <iterator>
#include <algorithm>
template <class _Map>
std::vector<typename _Map::key_type> keyset(const _Map& map)
{
std::vector<typename _Map::key_type> result;
result.reserve(map.size());
std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
return kvpair.first;
});
return result;
}
Bonus: The following functors retrieve the value set of a map:
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
template <class _Map>
std::vector<typename _Map::mapped_type> valueset(const _Map& map)
{
std::vector<typename _Map::mapped_type> result;
result.reserve(map.size());
std::transform(map.cbegin(), map.cend(), std::back_inserter(result), [](typename _Map::const_reference kvpair) {
return kvpair.second;
});
return result;
}
template <class _Map>
std::vector<std::reference_wrapper<typename _Map::mapped_type>> valueset(_Map& map)
{
std::vector<std::reference_wrapper<typename _Map::mapped_type>> result;
result.reserve(map.size());
std::transform(map.begin(), map.end(), std::back_inserter(result), [](typename _Map::reference kvpair) {
return std::ref(kvpair.second);
});
return result;
}
Usage:
int main()
{
std::map<int, double> map{
{1, 9.0},
{2, 9.9},
{3, 9.99},
{4, 9.999},
};
auto ks = keyset(map);
auto vs = valueset(map);
for (auto& k : ks) std::cout << k << '\n';
std::cout << "------------------\n";
for (auto& v : vs) std::cout << v << '\n';
for (auto& v : vs) v += 100.0;
std::cout << "------------------\n";
for (auto& v : vs) std::cout << v << '\n';
std::cout << "------------------\n";
for (auto& [k, v] : map) std::cout << v << '\n';
return 0;
}
Expected output:
1
2
3
4
------------------
9
9.9
9.99
9.999
------------------
109
109.9
109.99
109.999
------------------
109
109.9
109.99
109.999
This works for me in iOS 9.3.x with Swift:
override func didMoveToParentViewController(parent: UIViewController?) {
super.didMoveToParentViewController(parent)
if parent == self.navigationController?.parentViewController {
print("Back tapped")
}
}
Unlike other solutions here, this doesn't seem to trigger unexpectedly.
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
Try This
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
Note : We should always check the renameTo return value to make sure rename file is successful because it’s platform dependent(different Operating system, different file system) and it doesn’t throw IO exception if rename fails.
The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?
Then the problem are these numbers you are using for your months.
See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).
So checking your code, you are passing february and november, which would result in "1317510000".
Best regards.
I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master
.
A nice thing I recently found, mixing the use of line-height
+vertical-align
and the 50%
left trick, you can center
a dynamically sized box inside another dynamically sized box, on both the horizontal and vertical using pure CSS.
Note you must use spans (and inline-block
), tested in modern browsers + Internet Explorer 8.
HTML:
<h1>Center dynamic box using only css test</h1>
<div class="container">
<div class="center">
<div class="center-container">
<span class="dyn-box">
<div class="dyn-head">This is a head</div>
<div class="dyn-body">
This is a body<br />
Content<br />
Content<br />
Content<br />
Content<br />
</div>
</span>
</div>
</div>
</div>
CSS:
.container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
overflow: hidden;
}
.center {
position: absolute;
left: 50%;
top: 50%;
}
.center-container {
position: absolute;
left: -2500px;
top: -2500px;
width: 5000px;
height: 5000px;
line-height: 5000px;
text-align: center;
overflow: hidden;
}
.dyn-box {
display: inline-block;
vertical-align: middle;
line-height: 100%;
/* Purely asthetic below this point */
background: #808080;
padding: 13px;
border-radius: 11px;
font-family: arial;
}
.dyn-head {
background: red;
color: white;
min-width: 300px;
padding: 20px;
font-size: 23px;
}
.dyn-body {
padding: 10px;
background: white;
color: red;
}
This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.
More about csrf tokens here:
What is a CSRF token ? What is its importance and how does it work?
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
I am an operating system that only allocates you memory in 10mb partitions.
Internal Fragmentation
Fulfilling this request has just led to 3mb of internal fragmentation.
External Fragmentation
Fulfilling this request has just led to external fragmentation
Just make sure that the controller name is the same as yours DeliveryController if you renamed it (it will not change automatically!). if you rename the project name too you should delete the reference to this project from the Bin folder. Don't forget to specify the method get or post.
Instead of IN
we can use ANY
with arrays casted to enum array, for example:
create type example_enum as enum (
'ENUM1', 'ENUM2'
);
create table example_table (
id integer,
enum_field example_enum
);
select
*
from
example_table t
where
t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);
Or we can still use 'IN' clause, but first, we should 'unnest' it:
select
*
from
example_table t
where
t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));
Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0
use
should work (I've tested in Chrome, Firefox and Edge):
let users = [{username: 'user1'}, {username: 'user2'}, {username: 'user3'}];_x000D_
let favTitle = '';_x000D_
for(let j = 0; j < users.length; j++)_x000D_
favTitle += users[j].username + " ";_x000D_
_x000D_
$("#item").append('<i title="In favorite users: ' + favTitle + '">Favorite</i>');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id = item></div>
_x000D_
This will work. This is your directory name "Directory_Name"
sudo code --user-data-dir="Directory_Name"
Slightly more compact:
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)
Note:
sort
has been deprecated, replaced by sort_index
for this scenarioinplace
as it is usually harder to read and prevents chaining. See explanation in answer here:
Pandas: peculiar performance drop for inplace rename after dropnaAll of these answers are a good way, but I don't think you want to always go to your DB and modify the default value that you have set to NULL.
I suggest you go to the app/User.php and modify the protected $fillable
so it will take your new fields in the data array used to register.
Let's say you add a new input field called "first_name"
, your $fillable
should be something like this :
protected $fillable = [ 'first_name', 'email', 'password',];
This did it for me. Good luck!
I think the easiest way would be
var items = $('img, style, ...'), itemslen = items.length;
items.bind('load', function(){
itemslen--;
if (!itemlen) // Do stuff here
});
EDIT, to be a little crazy:
var items = $('a, abbr, acronym, address, applet, area, audio, b, base, ' +
'basefont, bdo, bgsound, big, body, blockquote, br, button, canvas, ' +
'caption, center, cite, code, col, colgroup, comment, custom, dd, del, ' +
'dfn, dir, div, dl, document, dt, em, embed, fieldset, font, form, frame, ' +
'frameset, head, hn, hr, html, i, iframe, img, input, ins, isindex, kbd, ' +
'label, legend, li, link, listing, map, marquee, media, menu, meta, ' +
'nextid, nobr, noframes, noscript, object, ol, optgroup, option, p, ' +
'param, plaintext, pre, q, rt, ruby, s, samp, script, select, small, ' +
'source, span, strike, strong, style, sub, sup, table, tbody, td, ' +
'textarea, tfoot, th, thead, title, tr, tt, u, ul, var, wbr, video, ' +
'window, xmp'), itemslen = items.length;
items.bind('load', function(){
itemslen--;
if (!itemlen) // Do stuff here
});
I played around with nico's answer a little and it felt jumpy. Did a bit of investigation and found window.requestAnimationFrame
which is a function that is called on each repaint cycle. This allows for a more clean-looking animation. Still trying to hone in on good default values for step size but for my example things look pretty good using this implementation.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do {
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var stepFunc = function() {
scrollContainer.scrollTop =
Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);
if (scrollContainer.scrollTop >= targetY) {
return;
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
}
In C shell - The ampersand is after the greater-than symbol
make >& filename
this is a late answer, but you could also use the File.Copy method of the System.IO namespace top send a file to the printer:
System.IO.File.Copy(filename, printerName);
This works fine
This is the simplest way to plot an ROC curve, given a set of ground truth labels and predicted probabilities. Best part is, it plots the ROC curve for ALL classes, so you get multiple neat-looking curves as well
import scikitplot as skplt
import matplotlib.pyplot as plt
y_true = # ground truth labels
y_probas = # predicted probabilities generated by sklearn classifier
skplt.metrics.plot_roc_curve(y_true, y_probas)
plt.show()
Here's a sample curve generated by plot_roc_curve. I used the sample digits dataset from scikit-learn so there are 10 classes. Notice that one ROC curve is plotted for each class.
Disclaimer: Note that this uses the scikit-plot library, which I built.
I have the same problem. I have resolved the problem with following code:
app.use('/img',express.static(path.join(__dirname, 'public/images')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/css',express.static(path.join(__dirname, 'public/stylesheets')));
Static request example:
http://pruebaexpress.lite.c9.io/js/socket.io.js
I need a more simple solution. Does it exist?
None of the solutions worked for me. If everything else fails, get the picture to Photoshop and apply some effect. 5 minutes versus so much time on this...
Use
.one-word-per-line {
word-spacing: <parent-width>;
}
.your-classname{
width: min-intrinsic;
width: -webkit-min-content;
width: -moz-min-content;
width: min-content;
display: table-caption;
display: -ms-grid;
-ms-grid-columns: min-content;
}
where <parent-width>
is the width of the parent element (or an arbitrary high value that doesn't fit into one line). That way you can be sure that there is even a line-break after a single letter. Works with Chrome/FF/Opera/IE7+ (and probably even IE6 since it's supporting word-spacing as well).
This answer is good for typescript / Angular 2, 4, 5+
I got this answer with the help of @rujmah answer above. His answer brings in the array count... and then find's the value and replaces it with another value...
What this answer does is simply grabs the array name that might be set in another variable via another module / component... in this case the array I build had a css name of stay-dates. So what this does is extract that name and then allows me to set it to another variable and use it like so. In my case it was an html css class.
let obj = this.highlightDays.find(x => x.css);
let index = this.highlightDays.indexOf(obj);
console.log('here we see what hightlightdays is ', obj.css);
let dayCss = obj.css;
You need Three Tools to decompile an APK
file.
for more how-to-use-dextojar. Hope this will help You and all! :)
If you use Guava in your project you can use Iterables::toArray
.
Foo[] foos = Iterables.toArray(x, Foo.class);
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
?modestbranding=1&autohide=1&showinfo=0&controls=0
autohide=1
is something that I never found... but it was the key :) I hope it's help
What I do is use Object.keys() to return a list of all the keys and then get the length of that
Object.keys(dictionary).length
*** Update August 2020 Release *** see https://github.com/microsoft/vscode/pull/104310
"editor.renderWhitespace": "trailing"
// option being added
Add a new option ('trailing') to editor.renderWhitespace that renders only
trailing whitespace (including lines with only whitespace).
*** Update February 2020 Release *** see https://github.com/microsoft/vscode/issues/90386
In v1.43 the default value will be changed to selection
from none
as it was in v1.42.
"editor.renderWhitespace": "selection" // default in v1.43
Update for v1.37: adding the option to render whitespace within selected text only. See v1.37 release notes, render whitespace.
The
editor.renderWhitespace
setting now supports aselection
option. With this option set, whitespace will be shown only on selected text:
"editor.renderWhitespace": "selection"
and
"workbench.colorCustomizations": {
"editorWhitespace.foreground": "#fbff00"
}
1) The circles are Entities/POJOs/Beans
2) deg is an abbreviation for degree as in graphs (number of edges)
PK=Primary key, FK=Foreign key
Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.
I have used Fredrik's code above in a project with some slight modifications, thought I'd share:
private static bool DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception)
{
return false;
}
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download it
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
return true;
}
else
return false;
}
Main changes are:
I worked out on Xcode 6.4 on swift. See below.
var view1: UIView!
func assignTapToView1() {
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap"))
// tap.delegate = self
view1.addGestureRecognizer(tap)
self.view .addSubview(view1)
...
}
func handleTap() {
print("tap working")
view1.removeFromSuperview()
// view1.alpha = 0.1
}
Apparently the version of sqlite3 included in Python 2.6 has this ability: http://docs.python.org/dev/library/sqlite3.html
# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os
con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
Here's an aparently free tool http://www.extradata.com/products/jarc/
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
Maybe try putting it all in the end if and use a else to skip the code this will make it so that you are able not use the GoTo.
If 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1)) = 7 Or (Int_Column - 1) + Int_direction(e, 0) = -1 Or (Int_Column - 1) + Int_direction(e, 0) = 7 Then
Else
If Grid((Int_Column - 1) + Int_direction(e, 0), 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1))) = "_" Then
Console.ReadLine()
End If
End If
You can add the application folder to your path from a command prompt using:
setx PATH "%PATH%;c:\MinGW\bin"
Note that you will probably need to open a new command window for the modified path setting to go into effect.
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X");
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
I ran into this problem, and my solution was moreso that www-data didn't own the proper folders, and instead I set it for one of the users to own it. (I was trying to do a bit of fancy, but erroneous trickery to get ftp to play nicely.)
After running:
chown -R www-data:www-data /var/www/html
The machine started serving data again. You can see who currently owns the folder by means of
ls -l /var/www/html
By using ''.join
list1 = ['1', '2', '3']
str1 = ''.join(list1)
Or if the list is of integers, convert the elements before joining them.
list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)
A patch is little more (see below) than a series of instructions: "add this here", "remove that there", "change this third thing to a fourth". That's why git tells you:
The copy of the patch that failed is found in: c:/.../project2/.git/rebase-apply/patch
You can open that patch in your favorite viewer or editor, open the files-to-be-changed in your favorite editor, and "hand apply" the patch, using what you know (and git does not) to figure out how "add this here" is to be done when the files-to-be-changed now look little or nothing like what they did when they were changed earlier, with those changes delivered to you as a patch.
A three-way merge introduces that "little more" information than the plain "series of instructions": it tells you what the original version of the file was as well. If your repository has the original version, your git can compare what you did to a file, to what the patch says to do to the file.
As you saw above, if you request the three-way merge, git can't find the "original version" in the other repository, so it can't even attempt the three-way merge. As a result you get no conflict markers, and you must do the patch-application by hand.
--reject
When you have to apply the patch by hand, it's still possible that git can apply most of the patch for you automatically and leave only a few pieces to the entity with the ability to reason about the code (or whatever it is that needs patching). Adding --reject
tells git to do that, and leave the "inapplicable" parts of the patch in rejection files. If you use this option, you must still hand-apply each failing patch, and figure out what to do with the rejected portions.
Once you have made the required changes, you can git add
the modified files and use git am --continue
to tell git to commit the changes and move on to the next patch.
Since we don't have your code, I can't tell if this is the case, but sometimes, you wind up with one of the patches saying things that amount to, e.g., "fix the spelling of a word on line 42" when the spelling there was already fixed.
In this particular case, you, having looked at the patch and the current code, should say to yourself: "aha, this patch should just be skipped entirely!" That's when you use the other advice git already printed:
If you prefer to skip this patch, run "git am --skip" instead.
If you run git am --skip
, git will skip over that patch, so that if there were five patches in the mailbox, it will end up adding just four commits, instead of five (or three instead of five if you skip twice, and so on).
artejera, do you mean Selenium as plugin to your browser (Selenium IDE)? Here is something for automation in Google Chrome.
But if you want to work with Selenium RC, just set up browser in your test script. There is setBrowser() method in Selenium.
Setting the -fx-text-fill
works for me.
See below:
if (passed) {
resultInfo.setText("Passed!");
resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
resultInfo.setText("Failed!");
resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}
Use the following command to increase the timeout period so that you could retype password for a while
git config --global credential.helper 'cache --timeout 3600'
I used it for Bitbucket and GitHub it works for both. The only thing you need to do is
3600
is in seconds. Increase it to whatever extent you want. I changed it to 259200
which is about 30 days. This way I re-enter my password for every 30 days or so.
Because it's an object, the way to assign value to its properties is using :
.
Change the =
to :
to fix the error.
var options = {
host: 'localhost',
port: 8080,
path: '/',
method: 'POST'
}
If you want to modify a control it must be done in the thread in which the control was created. This Invoke
method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).
In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created
private void btn_Click(object sender, EvenetArgs e)
{
var thread1 = new Thread(SetText1);
var thread2 = new Thread(SetText2);
thread1.Start();
thread2.Start();
}
private void SetText1()
{
textBox1.Text = "Test";
}
private void SetText2()
{
textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}
Use try-catch to avoid it:
var result = null;
try {
// if jQuery
result = $.parseJSON(JSONstring);
// if plain js
result = JSON.parse(JSONstring);
}
catch(e) {
// forget about it :)
}
You can react to new file activity with FileSystemWatcher.
• Debug: fine-grained statements concerning program state, typically used for debugging;
• Info: informational statements concerning program state, representing program events or behavior tracking;
• Warn: statements that describe potentially harmful events or states in the program;
• Error: statements that describe non-fatal errors in the application; this level is used quite often for logging handled exceptions;
• Fatal: statements representing the most severe of error conditions, assumedly resulting in program termination.
Found on http://www.beefycode.com/post/Log4Net-Tutorial-pt-1-Getting-Started.aspx
$cfg['Servers'][$i]['AllowNoPassword'] = false;
It looks like you're using Python 3.0, in which print has turned into a callable function rather than a statement.
print('Hello world!')
SELECT tem.name, COUNT(*)
FROM (
SELECT name FROM results
UNION ALL
SELECT name FROM archive_results
) AS tem
GROUP BY name
ORDER BY name
15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes
This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3
to the command line of s_client.
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio button
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
I found a solution for Chrome with CSS this following selector without bypassing the native verification form which could be very useful.
form input::-webkit-validation-bubble-message,
form select::-webkit-validation-bubble-message,
form textarea::-webkit-validation-bubble-message {
display:none;
}
By this way, you can also customise your message...
I got the solution on this page : http://trac.webkit.org/wiki/Styling%20Form%20Controls
I just tend to make them fixed widths so that they add up to the total width of the page - probably only works if you are using a fixed width page. Also "float".
This is a particularly involved problem on Windows, where it's not enough to just chmod the files correctly. You have to set up your environment.
On Windows, this worked for me:
Install cygwin.
Replace the msysgit ssh.exe with cygwin's ssh.exe.
Using cygwin bash, chmod 600 the private key file, which was "id_rsa" for me.
If it still doesn't work, go to Control Panel -> System Properties -> Advanced -> Environment Variables and add the following environment variable. Then repeat step 3.
Variable Value
CYGWIN sbmntsec
Fixed positioning will do what you need:
#main
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
}
This code is very simple:
<select class="form-control" id="marasemaat" style="margin-top: 10%;font-size: 13px;" [(ngModel)]="fullNamePresentor" [formControl]="stateControl"
(change)="onSelect($event.target.value)">
<option *ngFor="let char of programInfo1;let i = index;" onclick="currentSlide(9,false)" value={{char.id}}>{{char.title + " "}} ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
</select>
To be honest I think that it's really shame that there is no simple checkbox in storyboard to say that you want to resize buttons to accommodate the text. Well... whatever.
Here is the simplest solution using storyboard.
Place UILabel inside UIView. Set constraints to attach it to edges of UIView.
Place your UIButton inside UIView. Set the same constraints to attach it to the edges of UIView.
Set up the outlets.
@IBOutlet var button: UIButton!
@IBOutlet var textOnTheButton: UILabel!
let someTitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
override func viewDidLoad() {
super.viewDidLoad()
textOnTheButton.text = someTitle
button.setTitle(someTitle, for: .normal)
button.titleLabel?.numberOfLines = 0
}
For linux (I have fixed bugs in code above):
void remove_dir(char *path)
{
struct dirent *entry = NULL;
DIR *dir = NULL;
dir = opendir(path);
while(entry = readdir(dir))
{
DIR *sub_dir = NULL;
FILE *file = NULL;
char* abs_path new char[256];
if ((*(entry->d_name) != '.') || ((strlen(entry->d_name) > 1) && (entry->d_name[1] != '.')))
{
sprintf(abs_path, "%s/%s", path, entry->d_name);
if(sub_dir = opendir(abs_path))
{
closedir(sub_dir);
remove_dir(abs_path);
}
else
{
if(file = fopen(abs_path, "r"))
{
fclose(file);
remove(abs_path);
}
}
}
delete[] abs_path;
}
remove(path);
}
For windows:
void remove_dir(const wchar_t* folder)
{
std::wstring search_path = std::wstring(folder) + _T("/*.*");
std::wstring s_p = std::wstring(folder) + _T("/");
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if (hFind != INVALID_HANDLE_VALUE) {
do {
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (wcscmp(fd.cFileName, _T(".")) != 0 && wcscmp(fd.cFileName, _T("..")) != 0)
{
remove_dir((wchar_t*)(s_p + fd.cFileName).c_str());
}
}
else {
DeleteFile((s_p + fd.cFileName).c_str());
}
} while (::FindNextFile(hFind, &fd));
::FindClose(hFind);
_wrmdir(folder);
}
}
I am simply using the daemon npm module:
var daemon = require('daemon');
daemon.daemonize({
stdout: './log.log'
, stderr: './log.error.log'
}
, './node.pid'
, function (err, pid) {
if (err) {
console.log('Error starting daemon: \n', err);
return process.exit(-1);
}
console.log('Daemonized successfully with pid: ' + pid);
// Your Application Code goes here
});
Lately I'm also using mon(1) from TJ Holowaychuk to start and manage simple node apps.
In short, The basic problem an interface is trying to solve is to separate how we use something from how it is implemented. But you should consider interface is not a contract. Read more here.
function rmdir_recursive( $dirname ) {
/**
* FilesystemIterator and SKIP_DOTS
*/
if ( class_exists( 'FilesystemIterator' ) && defined( 'FilesystemIterator::SKIP_DOTS' ) ) {
if ( !is_dir( $dirname ) ) {
return false;
}
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
$path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
}
return rmdir( $dirname );
}
/**
* RecursiveDirectoryIterator and SKIP_DOTS
*/
if ( class_exists( 'RecursiveDirectoryIterator' ) && defined( 'RecursiveDirectoryIterator::SKIP_DOTS' ) ) {
if ( !is_dir( $dirname ) ) {
return false;
}
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
$path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
}
return rmdir( $dirname );
}
/**
* RecursiveIteratorIterator and RecursiveDirectoryIterator
*/
if ( class_exists( 'RecursiveIteratorIterator' ) && class_exists( 'RecursiveDirectoryIterator' ) ) {
if ( !is_dir( $dirname ) ) {
return false;
}
foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
if ( in_array( $path->getFilename(), array( '.', '..' ) ) ) {
continue;
}
$path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
}
return rmdir( $dirname );
}
/**
* Scandir Recursive
*/
if ( !is_dir( $dirname ) ) {
return false;
}
$objects = scandir( $dirname );
foreach ( $objects as $object ) {
if ( $object === '.' || $object === '..' ) {
continue;
}
filetype( $dirname . DIRECTORY_SEPARATOR . $object ) === 'dir' ? rmdir_recursive( $dirname . DIRECTORY_SEPARATOR . $object ) : unlink( $dirname . DIRECTORY_SEPARATOR . $object );
}
reset( $objects );
rmdir( $dirname );
return !is_dir( $dirname );
}
I do it even simpler:
use Symfony\Component\HttpFoundation\Request;
public function updateAction(Request $request)
{
$foo = $request->get('foo');
$bar = $request->get('bar');
}
Another option is to introduce your parameters into your action function definition:
use Symfony\Component\HttpFoundation\Request;
public function updateAction(Request $request, $foo, $bar)
{
echo $foo;
echo $bar;
}
which, then assumes that you defined {foo} and {bar} as part of your URL pattern in your routing.yml file:
acme_myurl:
pattern: /acme/news/{foo}/{bar}
defaults: { _controller: AcmeBundle:Default:getnews }
If you just want a string/json to print it can be solved with:
print(df.to_string(index=False))
Buf if you want to serialize the data too or even send to a MongoDB, would be better to do something like:
document = df.to_dict(orient='list')
There are 6 ways by now to orient the data, check more in the panda docs which better fits you.
It's simple to print an object to console in Javascript. Just use the following syntax:
console.log( object );
or
console.log('object: %O', object );
A relatively unknown method is following which prints an object or array to the console as table:
console.table( object );
I think it is important to say that this kind of logging statement only works inside a browser environment. I used this with Google Chrome. You can watch the output of your console.log calls inside the Developer Console: Open it by right click on any element in the webpage and select 'Inspect'. Select tab 'Console'.
Here's a short and ugly way to do search file names using the AWS CLI:
aws s3 ls s3://your-bucket --recursive | grep your-search | cut -c 32-
Instead of using np.hist2d, which in general produces quite ugly histograms, I would like to recycle py-sphviewer, a python package for rendering particle simulations using an adaptive smoothing kernel and that can be easily installed from pip (see webpage documentation). Consider the following code, which is based on the example:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import sphviewer as sph
def myplot(x, y, nb=32, xsize=500, ysize=500):
xmin = np.min(x)
xmax = np.max(x)
ymin = np.min(y)
ymax = np.max(y)
x0 = (xmin+xmax)/2.
y0 = (ymin+ymax)/2.
pos = np.zeros([len(x),3])
pos[:,0] = x
pos[:,1] = y
w = np.ones(len(x))
P = sph.Particles(pos, w, nb=nb)
S = sph.Scene(P)
S.update_camera(r='infinity', x=x0, y=y0, z=0,
xsize=xsize, ysize=ysize)
R = sph.Render(S)
R.set_logscale()
img = R.get_image()
extent = R.get_extent()
for i, j in zip(xrange(4), [x0,x0,y0,y0]):
extent[i] += j
print extent
return img, extent
fig = plt.figure(1, figsize=(10,10))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)
#Plotting a regular scatter plot
ax1.plot(x,y,'k.', markersize=5)
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)
heatmap_16, extent_16 = myplot(x,y, nb=16)
heatmap_32, extent_32 = myplot(x,y, nb=32)
heatmap_64, extent_64 = myplot(x,y, nb=64)
ax2.imshow(heatmap_16, extent=extent_16, origin='lower', aspect='auto')
ax2.set_title("Smoothing over 16 neighbors")
ax3.imshow(heatmap_32, extent=extent_32, origin='lower', aspect='auto')
ax3.set_title("Smoothing over 32 neighbors")
#Make the heatmap using a smoothing over 64 neighbors
ax4.imshow(heatmap_64, extent=extent_64, origin='lower', aspect='auto')
ax4.set_title("Smoothing over 64 neighbors")
plt.show()
which produces the following image:
As you see, the images look pretty nice, and we are able to identify different substructures on it. These images are constructed spreading a given weight for every point within a certain domain, defined by the smoothing length, which in turns is given by the distance to the closer nb neighbor (I've chosen 16, 32 and 64 for the examples). So, higher density regions typically are spread over smaller regions compared to lower density regions.
The function myplot is just a very simple function that I've written in order to give the x,y data to py-sphviewer to do the magic.
I know this is an old post, but I found my way here in 2018, so maybe someone else will too. In my opinion, the OP had a better approach (using dgv_DataBindingComplete event) than any of the answers provided. At the time of writing, all of the answers are written using paint events or cellformatting events which seems inefficient.
The OP was 99% of the way there, all they had to do was loop through their rows, test the cell value of each row, and set the BackColor, ForeColor, or whatever other property you want to set.
Please excuse the vb.NET syntax, but I think its close enough to C# that it should be clear.
Private Sub dgvFinancialResults_DataBindingComplete Handles dgvFinancialResults.DataBindingComplete
Try
Logging.TraceIt()
For Each row As DataGridViewRow in dgvFinancialResults.Rows
Dim invoicePricePercentChange = CSng(row.Cells("Invoice Price % Change").Value)
Dim netPricePercentChange = CSng(row.Cells("Net Price % Change").Value)
Dim tradespendPricePercentChange = CSng(row.Cells("Trade Spend % Change").Value)
Dim dnnsiPercentChange = CSng(row.Cells("DNNSI % Change").Value)
Dim cogsPercentChange = CSng(row.Cells("COGS % Change").Value)
Dim grossProfitPercentChange = CSng(row.Cells("Gross Profit % Change").Value)
If invoicePricePercentChange > Single.Epsilon Then
row.Cells("Invoice Price % Change").Style.ForeColor = Color.Green
Else
row.Cells("Invoice Price % Change").Style.ForeColor = Color.Red
End If
If netPricePercentChange > Single.Epsilon Then
row.Cells("Net Price % Change").Style.ForeColor = Color.Green
Else
row.Cells("Net Price % Change").Style.ForeColor = Color.Red
End If
If tradespendPricePercentChange > Single.Epsilon Then
row.Cells("Trade Spend % Change").Style.ForeColor = Color.Green
Else
row.Cells("Trade Spend % Change").Style.ForeColor = Color.Red
End If
If dnnsiPercentChange > Single.Epsilon Then
row.Cells("DNNSI % Change").Style.ForeColor = Color.Green
Else
row.Cells("DNNSI % Change").Style.ForeColor = Color.Red
End If
If cogsPercentChange > Single.Epsilon Then
row.Cells("COGS % Change").Style.ForeColor = Color.Green
Else
row.Cells("COGS % Change").Style.ForeColor = Color.Red
End If
If grossProfitPercentChange > Single.Epsilon Then
row.Cells("Gross Profit % Change").Style.ForeColor = Color.Green
Else
row.Cells("Gross Profit % Change").Style.ForeColor = Color.Red
End If
Next
Catch ex As Exception
Logging.ErrorHandler(ex)
End Try
End Sub
Do use this:
highp float rand(vec2 co)
{
highp float a = 12.9898;
highp float b = 78.233;
highp float c = 43758.5453;
highp float dt= dot(co.xy ,vec2(a,b));
highp float sn= mod(dt,3.14);
return fract(sin(sn) * c);
}
Don't use this:
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
You can find the explanation in Improvements to the canonical one-liner GLSL rand() for OpenGL ES 2.0
MSSQL uses regular XPath rules as follows:
I use the AbsoluteUri and you can get it like this:
string myURI = Request.Url.AbsoluteUri;
if (!WebSecurity.IsAuthenticated) {
Response.Redirect("~/Login?returnUrl="
+ Request.Url.AbsoluteUri );
Then after you login:
var returnUrl = Request.QueryString["returnUrl"];
if(WebSecurity.Login(username,password,true)){
Context.RedirectLocal(returnUrl);
It works well for me.
There is a cleaner way to do this with namedtuple:
from collections import namedtuple
def make_consts(name, **kwargs):
return namedtuple(name, kwargs.keys())(**kwargs)
Usage Example
CONSTS = make_consts("baz1",
foo=1,
bar=2)
With this exactly approach you can namespace your constants.
JavaScript with onchange
event:
<form action="upload.php" method="post" enctype="multipart/form-data">_x000D_
<input type="file" name="filename" onchange="javascript:this.form.submit();">_x000D_
</form>
_x000D_
jQuery
.change()
and .submit()
:
$('#fileInput').change(function() {_x000D_
$('#myForm').submit();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<form action="upload.php" id="myForm">_x000D_
<input type="file" id="fileInput">_x000D_
</form>
_x000D_
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
Ensure the below folders in storage directory:
Below is a command-line snippet that does for you
cd storage
mkdir logs
mkdir framework
mkdir framework/cache && framework/cache/data
mkdir framework/sessions
mkdir framework/testing
mkdir framework/views
chgrp -R www-data ../storage
chown -R www-data ../storage
I've always thought that Encryption can be converted both ways, in a way that the end value can bring you to original value and with Hashing you'll not be able to revert from the end result to the original value.
Your composer.phar
command lacks the flag for executable, or it is not inside the path.
The first problem can be fixed with chmod +x composer.phar
, the second by calling it as ./composer.phar -v
.
You have to prefix executables that are not in the path with an explicit reference to the current path in Unix, in order to avoid going into a directory that has an executable file with an innocent name that looks like a regular command, but is not. Just think of a cat
in the current directory that does not list files, but deletes them.
The alternative, and better, fix for the second problem would be to put the composer.phar
file into a location that is mentioned in the path
All these answers date back to 2016 or earlier... There's a new web standard for this using flex-boxes
. In general floats
for these sorts of problems is now frowned upon.
HTML
<div class="image-txt-container">
<img src="https://images4.alphacoders.com/206/thumb-350-20658.jpg">
<h2>
Text here
</h2>
</div>
CSS
.image-txt-container {
display: flex;
align-items: center;
flex-direction: row;
}
Example fiddle: https://jsfiddle.net/r8zgokeb/1/
If you want to revert the changes only in current working directory, use
git checkout -- .
And before that, you can list the files that will be reverted without actually making any action, just to check what will happen, with:
git checkout --
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
Semantically what you are trying is invalid html, table
element cannot have a div
element as a direct child. What you can do is, get your div
element inside a td
element and than try to hide it
I think some of the answers are missing an important point. The choice between UDP and TCP should not be based on the type of data (e.g., audio or video) or whether the application starts to play it before the transfer is completed ("streaming"), but whether it is real time. Real time data is (by definition) delay-sensitive, so it is often best sent over RTP/UDP (Real Time Protocol over UDP).
Delay is not an issue with stored data from a file, even if it's audio and/or video, so it is probably best sent over TCP so any packet losses can be corrected. The sender can read ahead and keep the network pipe full and the receiver can also use lots of playout buffering so it won't be interrupted by the occasional TCP retransmission or momentary network slowdown. The limiting case is where the entire recording is transferred before playback begins. This eliminates any risk of a playback stall, but is often impractical.
The problem with TCP for real-time data isn't retransmissions so much as excessive buffering as TCP tries to use the pipe as efficiently as possible without regard to latency. UDP preserves application packet boundaries and has no internal storage, so it does not introduce any latency.
The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).
Now I'm settled with Fiddler (Inspectors > WebView)
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
If you can run javascript, which seems like you can, create a new iframe, and post to that iframe instead. You can do <form target="iframe-id" ...>
That way all the redirects happen in the iframe and you still have control of the page.
The other solution is to also do a post via ajax. But that's a little more tricky if the page needs to error check or something.
Here is an example:
$("<iframe id='test' />").appendTo(document.body);
$("form").attr("target", "test");