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
});
For IntelliJ IDEA 2017.2 I did the following to fix this issue: Go to your project structure Now go to SDKs under platform settings and click the green add button. Add your JDK path. In my case it was this path C:\Program Files\Java\jdk1.8.0_144 Now Just go Project under Project settings and select the project SDK.
Here is a short tutorial:
Model:
namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;
public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}
View:
Create:
@model ImageUploadApp.Models.Image
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
new { enctype = "multipart/form-data" })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
<input id="ImagePath" title="Upload a product image"
type="file" name="file" />
</div>
<p><input type="submit" value="Create" /></p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Index (for display):
@model IEnumerable<ImageUploadApp.Models.Image>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ImagePath)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ImagePath)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
</td>
</tr>
}
</table>
Controller (Create)
public ActionResult Create(Image img, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
img.ImagePath = file.FileName;
}
db.Image.Add(img);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(img);
}
Hope this will help :)
CDATA
has no meaning at all in HTML.
CDATA
is an XML construct which sets a tag's contents that is normally #PCDATA - parsed character data, to be instead taken as #CDATA, that is, non-parsed character data. It is only relevant and valid in XHTML.
It is used in script
tags to avoid parsing <
and &
. In HTML, this is not needed, because in HTML, script
is already #CDATA.
I had to make my VideoView sit in a RelativeLayout in order to make the chosen answer work.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<VideoView android:id="@+id/videoViewRelative"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</VideoView>
</RelativeLayout>
As given here: Android - How to stretch video to fill VideoView area Toggling between screen sizes would be as simple as changing the layout parameters as given in the chosen answer.
You should have the file at the same location as that of the Python files you are trying to import. Also 'from file import function' is enough.
I didn't know the existing sa password so this is what I did:
Open Services in Control Panel
Find the "SQL Server (SQLEXPRESS)" entry and select properties
Stop the service
Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;
Start the service
Open a Command Prompt
Enter the command:
osql -S YourPcName\SQLEXPRESS -E
(change YourPcName to whatever your PC is called).
alter login sa enable go sp_password NULL,'new_password','sa' go quit
Stop the "SQL Server (SQLEXPRESS)" service
Remove the "-m" from the Start parameters field
Start the service
If we are talking about inexpensive implementation of the skip-list, I wonder in term of big O, what the cost of this operation is:
YourType[] array = someSet.toArray(new YourType[yourSet.size()]);
I mean it is always get stuck into a whole array creation, so it is O(n):
java.util.Arrays#copyOf
I ran into a similar issue where eclipse was not using my current %JAVA_HOME%
that was on the path
and was instead using an older version. The documentation points out that if no -vm
is specified in the ini file, eclipse will search for a shared library jvm.dll
This appears in the registry under the key HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
that gets installed when using the windows java installer (key might be a bit different based on 64-bit vs 32-bit, but search for jvm.dll
). Because it was finding this shared library on my path
before the %JAVA_HOME%/bin
, it was using the old version.
Like others have stated, the easiest way to deal with this is to specify the specific vm you want to use in the eclipse.ini
file. I'm writing this because I couldn't figure out how it was still using the old version when it wasn't specified anywhere on the path
or eclipse.ini
file.
See link to doc below: http://help.eclipse.org/kepler/topic/org.eclipse.platform.doc.isv/reference/misc/launcher.html?cp=2_1_3_1
Finding a VM and using the JNI Invocation API
The Eclipse launcher is capable of loading the Java VM in the eclipse process using the Java Native Interface Invocation API. The launcher is still capable of starting the Java VM in a separate process the same as previous version of Eclipse did. Which method is used depends on how the VM was found.
No -vm specified
When no -vm is specified, the launcher looks for a virtual machine first in a jre directory in the root of eclipse and then on the search path. If java is found in either location, then the launcher looks for a jvm shared library (jvm.dll on Windows, libjvm.so on *nix platforms) relative to that java executable.
- If a jvm shared library is found the launcher loads it and uses the JNI invocation API to start the vm.
- If no jvm shared library is found, the launcher executes the java launcher to start the vm in a new process.
-vm specified on the command line or in eclipse.ini
Eclipse can be started with "-vm " to indicate a virtual machine to use. There are several possibilities for the value of :
- directory: is a directory. We look in that directory for:
- (1) a java launcher or
- (2) the jvm shared library.
If we find the jvm shared library, we use JNI invocation. If we find a launcher, we attempt to find a jvm library in known locations relative to the launcher. If we find one, we use JNI invocation. If no jvm library is found, we exec java in a new process.
java.exe/javaw.exe: is a path to a java launcher. We exec that java launcher to start the vm in a new process.
jvm dll or so: is a path to a jvm shared library. We attempt to load that library and use the JNI Invocation API to start the vm in the current process.
Use
p.setval(static_cast<const char *>(0));
or
p.setval(static_cast<unsigned int>(0));
As indicated by the error, the type of 0
is int
. This can just as easily be cast to an unsigned int
or a const char *
. By making the cast manually, you are telling the compiler which overload you want.
Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.
To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.
Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.
Hope it helps Rihan
If you want to see landscape on the screen before you print, as well as printing, then in your css, you can set the width to 900px, and the height to 612px.
OP didn't mention A4 size. I assume it's Letter size in my numbers above.
Combine two answers above, I finally make it work. Just be careful that the first single quote for each string is a backtick (`) in file sendmail.mc.
#Change to your mail config directory:
cd /etc/mail
#Make a auth subdirectory
mkdir auth
chmod 700 auth #maybe not, because I cannot apply cmd "cd auth" if I do so.
#Create a file with your auth information to the smtp server
cd auth
touch client-info
#In the file, put the following, matching up to your smtp server:
AuthInfo:your.isp.net "U:root" "I:user" "P:password"
#Generate the Authentication database, make both files readable only by root
makemap hash client-info < client-info
chmod 600 client-info
cd ..
#Add the following lines to sendmail.mc. Make sure you update your smtp server
#The first single quote for each string should be changed to a backtick (`) like this:
define(`SMART_HOST',`your.isp.net')dnl
define(`confAUTH_MECHANISMS', `EXTERNAL GSSAPI DIGEST-MD5 CRAM-MD5 LOGIN PLAIN')dnl
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
#run
sudo sendmailconfig
this nsdate
used different format:
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *dateString = [format stringFromDate:now];
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];
NSDate *parsed = [inFormat dateFromString:dateString];
You can use the parse
method from the URL module in the request callback.
var http = require('http');
var url = require('url');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
response.end('Hello ' + queryData.name + '\n');
} else {
response.end("Hello World\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
I suggest you read the HTTP module documentation to get an idea of what you get in the createServer
callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
Use querySelector insted of getElementById();
var c = document.querySelector('#mainContent');
c.appendChild(document.createElement('div'));
I had this same problem and it occurred because I had hit the enter key when adding code in a text string.
Because it was a long string of text I wanted to see it all without having to scroll in my text editor, however hitting enter added an invisible character to the string which was illegal. I was using Sublime Text as my editor.
According to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):
hexdump -ve '1/1 "%.2x"'
1/1
means "each format is applied once and takes one byte", and "%.2x"
is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.
There are also DRM behaviors that incorporate multiple steps to the process. One of the most well known examples is one of Adobe's methods for verifying an installation of their Creative Suite. The traditional CD Key method discussed here is used, then Adobe's support line is called. The CD key is given to the Adobe representative and they give back an activation number to be used by the user.
However, despite being broken up into steps, this falls prey to the same methods of cracking used for the normal process. The process used to create an activation key that is checked against the original CD key was quickly discovered, and generators that incorporate both of the keys were made.
However, this method still exists as a way for users with no internet connection to verify the product. Going forward, it's easy to see how these methods would be eliminated as internet access becomes ubiquitous.
It's really a shame that both their names start with Hash. That's the least important part of them. The important parts come after the Hash - the Set and Map, as others have pointed out. What they are, respectively, are a Set - an unordered collection - and a Map - a collection with keyed access. They happen to be implemented with hashes - that's where the names come from - but their essence is hidden behind that part of their names.
Don't be confused by their names; they are deeply different things.
This is what I finally came up with, which works great!
{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}
Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.
With recent version of Pandas, you can do
df.N.hist(by=df.Letter)
Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.
pthread_exit
terminates the calling thread while pthread_join
suspends execution of calling thread until target threads completes execution.
They are pretty much well explained in detail in the open group documentation:
int index = dt.Rows.IndexOf(row);
But you're probably better off using a for loop instead of foreach.
I tried it on XP and it doesn't work if the PC is set to International time yyyy-M-d. Place a breakpoint on the line and before it is processed change the date string to use '-' in place of the '/' and you'll find it works. It makes no difference whether you have the CultureInfo or not. Seems strange to be able specify an expercted format only to have the separator ignored.
// Add some tenants to context so we have something for the procedure to return! AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}
You can Try this:
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
Intent intent= new Intent(YourCurrent.this, YourCurrent.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I came to this question looking to solve the "too many open files" error
, but I am using requests.session()
in my code. A few searches later and I came up with an answer on the Python Requests Documentation which suggests to use the with
block so that the session is closed even if there are unhandled exceptions:
with requests.Session() as s:
s.get('http://google.com')
If you're not using Session you can actually do the same thing: https://2.python-requests.org/en/master/user/advanced/#session-objects
with requests.get('http://httpbin.org/get', stream=True) as r:
# Do something
Solved by setting a password for the user first.
In terminal
sudo -u <username> psql
ALTER USER <username> PASSWORD 'SetPassword';
# ALTER ROLE
\q
In pgAdmin
**Connection**
Host name/address: 127.0.0.1
Port: 5432
Maintenance database: postgres
username: postgres
password: XXXXXX
You can specify '-m32' or '-m64' to select the compilation mode.
When dealing with autoconf (configure) scripts, I usually set CC="gcc -m64" (or CC="gcc -m32") in the environment so that everything is compiled with the correct bittiness. At least, usually...people find endless ways to make that not quite work, but my batting average is very high (way over 95%) with it.
You have several choices. The one that makes the most sense really depends on what you're trying to do.
Choice 1: make toyNumber a public member variable in a class
class MyToy {
public int toyNumber;
}
then pass a reference to a MyToy to your method.
void play(MyToy toy){
System.out.println("Toy number in play " + toy.toyNumber);
toy.toyNumber++;
System.out.println("Toy number in play after increement " + toy.toyNumber);
}
Choice 2: return the value instead of pass by reference
int play(int toyNumber){
System.out.println("Toy number in play " + toyNumber);
toyNumber++;
System.out.println("Toy number in play after increement " + toyNumber);
return toyNumber
}
This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);
.
Choice 3: make it a class or static variable
If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.
Choice 4: Create a single element array of type int and pass that
This is considered a hack, but is sometimes employed to return values from inline class invocations.
void play(int [] toyNumber){
System.out.println("Toy number in play " + toyNumber[0]);
toyNumber[0]++;
System.out.println("Toy number in play after increement " + toyNumber[0]);
}
Without a class or an id, and with your specific html:
table tr td label {display:none}
Otherwise if you have jQuery
$('label[for="foo"]').css('display', 'none');
If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.
If you have an instance, and you want to ensure it's not null, simply check for null:
if (value != null)
{
// it's not null.
}
You can update your provisioning certificates in XCode at:
Organizer -> Devices -> LIBRARY -> Provisioning Profiles
There is a refresh button :) So if you have created the certificate manually in iTunes connect, then you need to press this button or download the certificate manually.
Another workaround might be to use <div>
of the same size to wrap the <svg>
. After that, you will be able to apply "background-color"
, and "background-image"
that will affect thesvg
.
<div class="background">
<svg></svg>
</div>
<style type="text/css">
.background{
background-color: black;
/*background-image: */
}
</style>
There is sourceforge.net/projects/svn-search.
There is also a Windows application directly from the SVN home called SvnQuery available at http://svnquery.tigris.org
By far the easiest solution (at least in ubuntu/linux):
Works like a charm.
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
If your source-file is already utf8 then drop the utf8_* functions. php5 is storing strings as array of byte.
you should add a meta tag for encoding within the html AND you should add an http header which sets the transferencoding to utf-8.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
and in php
<?php
header('Content-Type: text/html; charset=utf-8');
Between execution of left != null
and queue.add(left)
another thread could have changed the value of left
to null
.
To work around this you have several options. Here are some:
Use a local variable with smart cast:
val node = left
if (node != null) {
queue.add(node)
}
Use a safe call such as one of the following:
left?.let { node -> queue.add(node) }
left?.let { queue.add(it) }
left?.let(queue::add)
Use the Elvis operator with return
to return early from the enclosing function:
queue.add(left ?: return)
Note that break
and continue
can be used similarly for checks within loops.
Step 1: Install the dependencies
sudo apt-get install build-dep python-psycopg2
Step 2: Run this command in your virtualenv
pip install psycopg2
Ref: Fernando Munoz
Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="...">
it will work.
Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module
Look at the these pages on limits.h and float.h, which are included as part of the standard c library.
I've had the same issue.
Adding the font version (e.g. ?v=1.101
) to the font URLS should do the trick ;)
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 600;
src: url('../fonts/open-sans-v15-latin-600.eot?v=1.101'); /* IE9 Compat Modes */
src: local('Open Sans SemiBold'), local('OpenSans-SemiBold'),
url('../fonts/open-sans-v15-latin-600.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('../fonts/open-sans-v15-latin-600.woff2?v=1.101') format('woff2'), /* Super Modern Browsers */
url('../fonts/open-sans-v15-latin-600.woff?v=1.101') format('woff'), /* Modern Browsers */
url('../fonts/open-sans-v15-latin-600.ttf') format('truetype'), /* Safari, Android, iOS */
url('../fonts/open-sans-v15-latin-600.svg#OpenSans') format('svg'); /* Legacy iOS */
}
Clicking (right mouse click) on font's TTF version and selecting "Get Info" (Mac OSX) "Properties" (Windows) in context menu should be enough to access the font version.
One liner as suggested here
How to determine one year from now in Javascript by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
If you want your form's field clear, you must only add a delay in the onClick event like:
<input name="submit" id="MyButton" type="submit" class="btn-lg" value="ClickMe" onClick="setTimeout('clearform()', 2000 );"
onClick="setTimeout('clearform()', 1500 );" . in 1,5 seconds its clear
document.getElementById("name").value = ""; <<<<<<just correct this
document.getElementById("telephone").value = ""; <<<<<correct this
By clearform()
, I mean your clearing-fields function.
Use List<T>.Insert
While not relevant to your specific example, if performance is important also consider using LinkedList<T>
because inserting an item to the start of a List<T>
requires all items to be moved over. See When should I use a List vs a LinkedList.
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
I found it helpful to remove the outline on a "sliding door" type of input button, because the outline doesn't cover the right "cap" of the sliding door image making the focus state look a little wonky.
input.slidingdoorbutton:focus { outline: none;}
If you have a seeder in your database, run php artisan migrate:fresh --seed
There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.
.text-black-50
and .text-white-50
are 50% transparent.
.text-body {_x000D_
color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
This is for until IE9
<!--[if IE ]>
<style> .someclass{
text-align: center;
background: #00ADEF;
color: #fff;
visibility:hidden; // in case of hiding
}
#someotherclass{
display: block !important;
visibility:visible; // in case of visible
}
</style>
This is for after IE9
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {enter your CSS here}
There 3 functions you want to look at here:
I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:
=LARGE($B$2:$B$11, A13)
=INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
The negative margin trick:
http://pastehtml.com/view/1dujbt3.html
Not elegant, I suppose, but it works in some cases.
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
This should work:
Dim webAddress As String = "http://www.example.com/"
Process.Start(webAddress)
for complete this script , the function for draw circle ,
function drawCircle(coordon)
{
var coord = coordon.split(',');
var c = document.getElementById("myCanvas");
var hdc = c.getContext("2d");
hdc.beginPath();
hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
hdc.stroke();
}
Use List.AddRange(collection As IEnumerable(Of T)) method.
It allows you to append at the end of your list another collection/list.
Example:
List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
On Bootstrap 4 you can use:
<p class="font-weight-bold">Bold text.</p>
<p class="font-weight-normal">Normal weight text.</p>
<p class="font-weight-light">Light weight text.</p>
You could try:
.modal.modal-wide .modal-dialog {
width: 90%;
}
.modal-wide .modal-body {
overflow-y: auto;
}
Just add .modal-wide to your classes
Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
This is known as the "fragment identifier" and is typically used to identify a portion of an HTML document that sits within a fully qualified URL:
Why not simply set it up as a Scheduled Task that is scheduled to run at start up?
The way to store dates in SQLite is:
yyyy-mm-dd hh:mm:ss.xxxxxx
SQLite also has some date and time functions you can use. See SQL As Understood By SQLite, Date And Time Functions.
I have found the metadata plugin to be an excellent solution to the problem of storing arbitrary data with the html tag in a way that makes it easy to retrieve and use with jQuery.
Important: The actual file you include is is only 5 kb and not 37 kb (which is the size of the complete download package)
Here is an example of it being used to store values I use when generating a google analytics tracking event (note: data.label and data.value happen to be optional params)
$(function () {
$.each($(".ga-event"), function (index, value) {
$(value).click(function () {
var data = $(value).metadata();
if (data.label && data.value) {
_gaq.push(['_trackEvent', data.category, data.action, data.label, data.value]);
} else if (data.label) {
_gaq.push(['_trackEvent', data.category, data.action, data.label]);
} else {
_gaq.push(['_trackEvent', data.category, data.action]);
}
});
});
});
<input class="ga-event {category:'button', action:'click', label:'test', value:99}" type="button" value="Test"/>
You can use both Kotlin and Java files in your application.
To switch between the two files, make sure you give them unique < action android:name="" in AndroidManifest.xml, like so:
<activity android:name=".MainActivityKotlin">
<intent-filter>
<action android:name="com.genechuang.basicfirebaseproject.KotlinActivity"/>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.genechuang.basicfirebaseproject.MainActivityJava"
android:label="MainActivityJava" >
<intent-filter>
<action android:name="com.genechuang.basicfirebaseproject.JavaActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Then in your MainActivity.kt (Kotlin file), to start an Activity written in Java, do this:
val intent = Intent("com.genechuang.basicfirebaseproject.JavaActivity")
startActivity(intent)
In your MainActivityJava.java (Java file), to start an Activity written in Kotlin, do this:
Intent mIntent = new Intent("com.genechuang.basicfirebaseproject.KotlinActivity");
startActivity(mIntent);
The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.
You can create an immutable map using a static initialiser too:
public class Test {
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}
In Ember.js you can use inline if helper in if block helper. It can replace ||
logical operator, for example:
{{#if (if firstCondition firstCondition secondCondition)}}
(firstCondition || (or) secondCondition) === true
{{/if}}
I face the same problem. After reading numerous posts, I would like to introduce the following solution I finally chose over many other methods (e.g. use urllib
, httpimport
, clone from GitHub, package the modules for installation, etc). The solution utilizes Google Drive API (official doc) for proper authorization.
id=
" - the file id assigned by Google Drive!pip install pydrive # Package to use Google Drive API - not installed in Colab VM by default
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth # Other necessary packages
from oauth2client.client import GoogleCredentials
auth.authenticate_user() # Follow prompt in the authorization process
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
your_module = drive.CreateFile({"id": "your_module_file_id"}) # "your_module_file_id" is the part after "id=" in the shareable link
your_module.GetContentFile("your_module_file_name.py") # Save the .py module file to Colab VM
import your_module_file_name # Ready to import. Don't include".py" part, of course :)
Last but not least, I should credit the original contributor of this approach. That post might have some typo in the code as it triggered an error when I tried it. After more reading and troubleshooting my code snippets above worked (as of today on Colab VM OS: Linux 4.14.79).
Copy the directory named npm
from your installed node path (In my case the npm directory was available in C:\Program Files\nodejs\node_modules
).
Navigate to C:\Users\%USERNAME%\AppData\Roaming\npm\node_modules
and paste the copied npm
directory there.
This method worked for me when I had the same error. . .
As for the environment variables:
import os
print os.environ["HOME"]
I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.
You can use a TextView and change its background to the image you want to use
In the model, write the below code;
public $timestamps = false;
This would work.
Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
You can use PowerShell job cmdlets to achieve your goals.
There are 6 job related cmdlets available in PowerShell.
If interesting about it, you can download the sample How to create background job in PowerShell
NsUserDefaults saves only small variable sizes. If you want to save many objects you can use CoreData as a native solution, or I created a library that helps you save objects as easy as .save() function. It’s based on SQLite.
Check it out and tell me your comments
You can use getChanges()
on Eloquent model even after persisting.
I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C
). Now a program can use SIG_IGN
to ignore all signals or SIG_DFL
to restore the default action.
Now if you do $ command &
then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
Set the Screen orientation to portrait in Manifest file under the activity Tag.
Here the example
You need to enter in every Activity
for portrait
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity"
for landscape
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity"
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.thcb.app">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2"
android:screenOrientation="landscape"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's a variant of this answer that uses metaclasses to avoid the messy syntax, and use the typing
-style List[int]
syntax:
class template(type):
def __new__(metacls, f):
cls = type.__new__(metacls, f.__name__, (), {
'_f': f,
'__qualname__': f.__qualname__,
'__module__': f.__module__,
'__doc__': f.__doc__
})
cls.__instances = {}
return cls
def __init__(cls, f): # only needed in 3.5 and below
pass
def __getitem__(cls, item):
if not isinstance(item, tuple):
item = (item,)
try:
return cls.__instances[item]
except KeyError:
cls.__instances[item] = c = cls._f(*item)
item_repr = '[' + ', '.join(repr(i) for i in item) + ']'
c.__name__ = cls.__name__ + item_repr
c.__qualname__ = cls.__qualname__ + item_repr
c.__template__ = cls
return c
def __subclasscheck__(cls, subclass):
for c in subclass.mro():
if getattr(c, '__template__', None) == cls:
return True
return False
def __instancecheck__(cls, instance):
return cls.__subclasscheck__(type(instance))
def __repr__(cls):
import inspect
return '<template {!r}>'.format('{}.{}[{}]'.format(
cls.__module__, cls.__qualname__, str(inspect.signature(cls._f))[1:-1]
))
With this new metaclass, we can rewrite the example in the answer I link to as:
@template
def List(member_type):
class List(list):
def append(self, member):
if not isinstance(member, member_type):
raise TypeError('Attempted to append a "{0}" to a "{1}" which only takes a "{2}"'.format(
type(member).__name__,
type(self).__name__,
member_type.__name__
))
list.append(self, member)
return List
l = List[int]()
l.append(1) # ok
l.append("one") # error
This approach has some nice benefits
print(List) # <template '__main__.List[member_type]'>
print(List[int]) # <class '__main__.List[<class 'int'>, 10]'>
assert List[int] is List[int]
assert issubclass(List[int], List) # True
Java 8
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
List<List<String>> stringListList = new ArrayList<>();
stringListList.add(Arrays.asList(new String[] {"(0,0)", "(0,1)"} ));
stringListList.add(Arrays.asList(new String[] {"(1,0)", "(1,1)", "(1,2)"} ));
stringListList.add(Arrays.asList(new String[] {"(2,0)", "(2,1)"} ));
int count=stringListList.stream().mapToInt(i -> i.size()).sum();
System.out.println("stringListList count: "+count);
}
}
It is very dependent of the engine that you use for generating html files. If you are using Hugo for generating htmls you have to write down like this:
<a href="https://example.com" target="_blank" rel="noopener"><span>Example Text</span> </a>.
There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:
http://getbootstrap.com/customize/
Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.
Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:
https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52
You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.
As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.
If you are using SASS or LESS, you would change the font size in the variables file before compiling.
Runnable (vs) Callable comes into point when we are using Executer framework.
ExecutorService is a subinterface of Executor
, which accepts both Runnable and Callable tasks.
Earlier Multi-Threading can be achieved using Interface Runnable
Since 1.0, but here the problem is after completing the thread task we are unable to collect the Threads information. In-order to collect the data we may use Static fields.
Example Separate threads to collect each student data.
static HashMap<String, List> multiTasksData = new HashMap();
public static void main(String[] args) {
Thread t1 = new Thread( new RunnableImpl(1), "T1" );
Thread t2 = new Thread( new RunnableImpl(2), "T2" );
Thread t3 = new Thread( new RunnableImpl(3), "T3" );
multiTasksData.put("T1", new ArrayList() ); // later get the value and update it.
multiTasksData.put("T2", new ArrayList() );
multiTasksData.put("T3", new ArrayList() );
}
To resolve this problem they have introduced Callable<V>
Since 1.5 which returns a result and may throw an exception.
Single Abstract Method : Both Callable and Runnable interface have a single abstract method, which means they can be used in lambda expressions in java 8.
public interface Runnable {
public void run();
}
public interface Callable<Object> {
public Object call() throws Exception;
}
There are a few different ways to delegate tasks for execution to an ExecutorService.
execute(Runnable task):void
crates new thread but not blocks main thread or caller thread as this method return void.submit(Callable<?>):Future<?>
, submit(Runnable):Future<?>
crates new thread and blocks main thread when you are using future.get().Example of using Interfaces Runnable, Callable with Executor framework.
class CallableTask implements Callable<Integer> {
private int num = 0;
public CallableTask(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < 5; i++) {
System.out.println(i + " : " + threadName + " : " + num);
num = num + i;
MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
}
System.out.println(threadName + " : Completed Task. Final Value : "+ num);
return num;
}
}
class RunnableTask implements Runnable {
private int num = 0;
public RunnableTask(int num) {
this.num = num;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " : Started Task...");
for (int i = 0; i < 5; i++) {
System.out.println(i + " : " + threadName + " : " + num);
num = num + i;
MainThread_Wait_TillWorkerThreadsComplete.sleep(1);
}
System.out.println(threadName + " : Completed Task. Final Value : "+ num);
}
}
public class MainThread_Wait_TillWorkerThreadsComplete {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("Main Thread start...");
Instant start = java.time.Instant.now();
runnableThreads();
callableThreads();
Instant end = java.time.Instant.now();
Duration between = java.time.Duration.between(start, end);
System.out.format("Time taken : %02d:%02d.%04d \n", between.toMinutes(), between.getSeconds(), between.toMillis());
System.out.println("Main Thread completed...");
}
public static void runnableThreads() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<?> f1 = executor.submit( new RunnableTask(5) );
Future<?> f2 = executor.submit( new RunnableTask(2) );
Future<?> f3 = executor.submit( new RunnableTask(1) );
// Waits until pool-thread complete, return null upon successful completion.
System.out.println("F1 : "+ f1.get());
System.out.println("F2 : "+ f2.get());
System.out.println("F3 : "+ f3.get());
executor.shutdown();
}
public static void callableThreads() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> f1 = executor.submit( new CallableTask(5) );
Future<Integer> f2 = executor.submit( new CallableTask(2) );
Future<Integer> f3 = executor.submit( new CallableTask(1) );
// Waits until pool-thread complete, returns the result.
System.out.println("F1 : "+ f1.get());
System.out.println("F2 : "+ f2.get());
System.out.println("F3 : "+ f3.get());
executor.shutdown();
}
}
This worked for me in laravel 8:
Add this to your LoginController.php:
public function __construct()
{
session(['url.intended' => url()->previous()]);
$this->redirectTo = session()->get('url.intended');
$this->middleware('guest')->except('logout');
}
It will redirect you back 2 times, so to the page you were before login.
Credits goes to @MevlütÖzdemir for the answer!
This is what you can do:
class Profile < ActiveRecord::Base
before_save :set_default_val
def set_default_val
self.send_updates = 'val' unless self.send_updates
end
end
EDIT: ...but apparently this is a Rookie mistake!
XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
Use:
$(document).ready(function () {
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
if (urlParams["q1"] === 1) {
return 1;
}
Please check and let me know your comments. Also refer to How to get querystring value using jQuery.
From my limited experience with python, is
is used to compare two objects to see if they are the same object as opposed to two different objects with the same value. ==
is used to determine if the values are identical.
Here is a good example:
>>> s1 = u'public'
>>> s2 = 'public'
>>> s1 is s2
False
>>> s1 == s2
True
s1
is a unicode string, and s2
is a normal string. They are not the same type, but are the same value.
You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
//staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
//set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
//shorten way
//staff.setAttribute("id", "1");
//firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
//lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
//nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
//salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\testing.xml"));
transformer.transform(source, result);
System.out.println("Done");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}
You can use is_null() function.
http://php.net/manual/en/function.is-null.php : in the comments :
mdufour at gmail dot com 20-Aug-2008 04:31 Testing for a NULL field/column returned by a mySQL query.
Say you want to check if field/column “foo” from a given row of the table “bar” when > returned by a mySQL query is null. You just use the “is_null()” function:
[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
if (is_null($qValues["foo"]))
echo "No foo data!";
else
echo "Foo data=".$qValues["foo"];
[…]
I managed to do it with
var html_string= "content";
document.getElementById('output_iframe1').src = "data:text/html;charset=utf-8," + escape(html_string);
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
Among other already mentioned tools you can use also readelf
(manual). It is similar to objdump
but goes more into detail. See this for the difference explanation.
$ readelf -sW /lib/liblzma.so.5 |head -n10
Symbol table '.dynsym' contains 128 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_unlock@GLIBC_2.0 (4)
2: 00000000 0 FUNC GLOBAL DEFAULT UND pthread_mutex_destroy@GLIBC_2.0 (4)
3: 00000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable
4: 00000000 0 FUNC GLOBAL DEFAULT UND memmove@GLIBC_2.0 (5)
5: 00000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.0 (5)
6: 00000000 0 FUNC GLOBAL DEFAULT UND memcpy@GLIBC_2.0 (5)
In android gradle 0.4.0 you can just do:
println System.env.HOME
classpath com.android.tools.build:gradle-experimental:0.4.0
Use Runtime to call Curl. This code works for both Ubuntu and Windows.
String[] commands = new String {"curl", "-X", "GET", "http://checkip.amazonaws.com"};
Process process = Runtime.getRuntime().exec(commands);
BufferedReader reader = new BufferedReader(new
InputStreamReader(process.getInputStream()));
String line;
String response;
while ((line = reader.readLine()) != null) {
response.append(line);
}
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date DESC
LIMIT 10)
UNION ALL
(SELECT <some columns>
FROM mytable
<maybe some joins here>
WHERE <various conditions>
ORDER BY date ASC
LIMIT 10)
Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)
C:\Users{Username}.android\avd
Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.
Ctrl + F11, numpad 7 and numpad 9 don't work on my Ubuntu box, but Ctrl + F12 does.
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
You can effectively remove scientific notation in printing with this code:
options(scipen=999)
Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.
A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId
attribute set to True
, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show
without creating a new instance of the class.
Step away from this, and treat your form as an object instead - expose Property Get
members and abstract away the form's controls - the calling code doesn't care about controls anyway:
Option Explicit
Private cancelling As Boolean
Public Property Get UserId() As String
UserId = txtUserId.Text
End Property
Public Property Get Password() As String
Password = txtPassword.Text
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = cancelling
End Property
Private Sub OkButton_Click()
Me.Hide
End Sub
Private Sub CancelButton_Click()
cancelling = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
cancelling = True
Cancel = True
Me.Hide
End If
End Sub
Now the calling code can do this (assuming the UserForm was named LoginPrompt
):
With New LoginPrompt
.Show vbModal
If .IsCancelled Then Exit Sub
DoSomething .UserId, .Password
End With
Where DoSomething
would be some procedure that requires the two string parameters:
Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
'work with the parameter values, regardless of where they came from
End Sub
In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.
But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.
df.ix[10,:]
gives you all the columns from the 10th row. In your case you want everything up to the 10th row which is df.ix[:9,:]
. Note that the right end of the slice range is inclusive: http://pandas.sourceforge.net/gotchas.html#endpoints-are-inclusive
You can actually send it as JSON the following way:
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
This should do the trick:
Application.Current.Shutdown();
If you're interested, here's some additional material that I found helpful:
The values are determined by the bit of the image. 8 bit 0 to 255
16 bit...some ridiculous number..0 to 65,000 approx.
32 bit are 0 to 1
I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255
I know it's a bit old but I ran in the same problem today. I wanted to install eclipse on my vm with xubuntu. Because I've had problems with the latest eclipse version 2019-06 I tried with Oxygen. So I went to eclipse.org and downloaded oxygen. When running oxygen, the problem with merketplace not reachable occurs. So I downloaded the eclipse installer not immediatly the oxygen. After that I can use eclipse as expectet ( all versions)
$( "#btn1" ).click(function() {
$('#btn2').css('display','none');
});
Calendar.getInstance().get(Calendar.MILLISECOND);
Here's one with extend()
types = ('*.jpg', '*.png')
images_list = []
for files in types:
images_list.extend(glob.glob(os.path.join(path, files)))
For an uglier version of unshift
use splice
:
TheArray.splice(0, 0, TheNewObject);
import the HttpClientModule in your app.module.ts
import {HttpClientModule} from '@angular/common/http';
...
@NgModule({
...
imports: [
//other content,
HttpClientModule
]
})
Extracted from @Resord's comments above. This one worked for me and more closely inclined with the question.
$(this).parent().closest('.a');
Thanks
This supports changing systemwide appearance (turning dark mode on or off) while the application is running. You can also set the background colour in Interface Builder, if you set the class of the view to BackgroundColorView first.
class BackgroundColorView: NSView {
@IBInspectable var backgroundColor: NSColor? {
didSet { needsDisplay = true }
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
wantsLayer = true
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
wantsLayer = true
}
override var wantsUpdateLayer: Bool { return true }
override func updateLayer() {
layer?.backgroundColor = backgroundColor?.cgColor
}
}
I think this is best solution, original address: Java2s
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] argv) {
Map<String, String> map = new HashMap<String, String>();
map.put("1","one");
map.put("2","two");
map.put("3","three");
map.put("4","four");
System.out.println(getKeyFromValue(map,"three"));
}
// hm is the map you are trying to get value from it
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
An easy usage: if you put all data in hasMap and you have item = "Automobile", so you are looking its key in hashMap. that is good solution.
getKeyFromValue(hashMap, item);
System.out.println("getKeyFromValue(hashMap, item): "+getKeyFromValue(hashMap, item));
Try using SweetAlert its just simply the best . You will get a lot of customization and flexibility.
sweetAlert(
{
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!"
},
deleteIt()
);
Even after removing the remaking the directories, the datanode wasn't starting.
So, I started it manually using bin/hadoop datanode
It did not reach any conclusion. I opened another terminal from the same username and did jps
and it showed me the running datanode process.
It's working, but I just have to keep the unfinished terminal open by the side.
you can also refactor your solution removing the first loop:
Set<Integer> set = new HashSet<Integer>();
Collection<Integer> removeCandidates = new LinkedList<Integer>(set);
for(Integer element : set)
if(element % 2 == 0)
removeCandidates.add(element);
set.removeAll(removeCandidates);
Imports System.Runtime.InteropServices
Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code:
logger.info("Skipping {0} because it's thumbnail was "
"already in our system as {1}.".format(line[indexes['url']],
video.title))
There is one more reason for such failure which I came to know when mine failed
This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.
A list of PDF/A validators is on the pdfa.org web site here:
A free online PDF/A validator is available here:
A report on the accuracy of many of these PDF/A validators is available from PDFLib:
Se as well:
Another approach I found is to set a delegate for the NavigationController
:
navigationController.delegate = self;
and use setNavigationBarHidden
in navigationController:willShowViewController:animated:
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated
{
// Hide the nav bar if going home.
BOOL hide = viewController != homeViewController;
[navigationController setNavigationBarHidden:hide animated:animated];
}
Easy way to customize the behavior for each ViewController
all in one place.
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Even though the ID selector is the simplest, you can also use the name selector as below:
$('[name='submitted[first_name]']').removeAttr('required');
For more see: https://api.jquery.com/attribute-equals-selector/
{!! Form::text('firstname', null !!}
@if($errors->has('firstname'))
{{ $errors->first('firstname') }}
@endif
Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.
POST https://instagram.com/api/v1/media/upload/
Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php
For horizontal scroll, keep these two properties in mind:
overflow-x:scroll;
white-space: nowrap;
See working link : click me
HTML
<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better control of the layout. The default value is visible.You can use the overflow property when you want to have better control of the layout. The default value is visible.</div>
CSS
div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}
locale
command with no arguments will print the values of all of the relevant environment variables except for LANGUAGE.
For current encoding:
locale charmap
For available locales:
locale -a
For available encodings:
locale -m
I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8
The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:
filter:Alpha(opacity=50)
You can try following sample http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
Sometimes we want to catch a SIGSEGV
to find out if a pointer is valid, that is, if it references a valid memory address. (Or even check if some arbitrary value may be a pointer.)
One option is to check it with isValidPtr()
(worked on Android):
int isValidPtr(const void*p, int len) {
if (!p) {
return 0;
}
int ret = 1;
int nullfd = open("/dev/random", O_WRONLY);
if (write(nullfd, p, len) < 0) {
ret = 0;
/* Not OK */
}
close(nullfd);
return ret;
}
int isValidOrNullPtr(const void*p, int len) {
return !p||isValidPtr(p, len);
}
Another option is to read the memory protection attributes, which is a bit more tricky (worked on Android):
re_mprot.c:
#include <errno.h>
#include <malloc.h>
//#define PAGE_SIZE 4096
#include "dlog.h"
#include "stdlib.h"
#include "re_mprot.h"
struct buffer {
int pos;
int size;
char* mem;
};
char* _buf_reset(struct buffer*b) {
b->mem[b->pos] = 0;
b->pos = 0;
return b->mem;
}
struct buffer* _new_buffer(int length) {
struct buffer* res = malloc(sizeof(struct buffer)+length+4);
res->pos = 0;
res->size = length;
res->mem = (void*)(res+1);
return res;
}
int _buf_putchar(struct buffer*b, int c) {
b->mem[b->pos++] = c;
return b->pos >= b->size;
}
void show_mappings(void)
{
DLOG("-----------------------------------------------\n");
int a;
FILE *f = fopen("/proc/self/maps", "r");
struct buffer* b = _new_buffer(1024);
while ((a = fgetc(f)) >= 0) {
if (_buf_putchar(b,a) || a == '\n') {
DLOG("/proc/self/maps: %s",_buf_reset(b));
}
}
if (b->pos) {
DLOG("/proc/self/maps: %s",_buf_reset(b));
}
free(b);
fclose(f);
DLOG("-----------------------------------------------\n");
}
unsigned int read_mprotection(void* addr) {
int a;
unsigned int res = MPROT_0;
FILE *f = fopen("/proc/self/maps", "r");
struct buffer* b = _new_buffer(1024);
while ((a = fgetc(f)) >= 0) {
if (_buf_putchar(b,a) || a == '\n') {
char*end0 = (void*)0;
unsigned long addr0 = strtoul(b->mem, &end0, 0x10);
char*end1 = (void*)0;
unsigned long addr1 = strtoul(end0+1, &end1, 0x10);
if ((void*)addr0 < addr && addr < (void*)addr1) {
res |= (end1+1)[0] == 'r' ? MPROT_R : 0;
res |= (end1+1)[1] == 'w' ? MPROT_W : 0;
res |= (end1+1)[2] == 'x' ? MPROT_X : 0;
res |= (end1+1)[3] == 'p' ? MPROT_P
: (end1+1)[3] == 's' ? MPROT_S : 0;
break;
}
_buf_reset(b);
}
}
free(b);
fclose(f);
return res;
}
int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask) {
unsigned prot1 = read_mprotection(addr);
return (prot1 & prot_mask) == prot;
}
char* _mprot_tostring_(char*buf, unsigned int prot) {
buf[0] = prot & MPROT_R ? 'r' : '-';
buf[1] = prot & MPROT_W ? 'w' : '-';
buf[2] = prot & MPROT_X ? 'x' : '-';
buf[3] = prot & MPROT_S ? 's' : prot & MPROT_P ? 'p' : '-';
buf[4] = 0;
return buf;
}
re_mprot.h:
#include <alloca.h>
#include "re_bits.h"
#include <sys/mman.h>
void show_mappings(void);
enum {
MPROT_0 = 0, // not found at all
MPROT_R = PROT_READ, // readable
MPROT_W = PROT_WRITE, // writable
MPROT_X = PROT_EXEC, // executable
MPROT_S = FIRST_UNUSED_BIT(MPROT_R|MPROT_W|MPROT_X), // shared
MPROT_P = MPROT_S<<1, // private
};
// returns a non-zero value if the address is mapped (because either MPROT_P or MPROT_S will be set for valid addresses)
unsigned int read_mprotection(void* addr);
// check memory protection against the mask
// returns true if all bits corresponding to non-zero bits in the mask
// are the same in prot and read_mprotection(addr)
int has_mprotection(void* addr, unsigned int prot, unsigned int prot_mask);
// convert the protection mask into a string. Uses alloca(), no need to free() the memory!
#define mprot_tostring(x) ( _mprot_tostring_( (char*)alloca(8) , (x) ) )
char* _mprot_tostring_(char*buf, unsigned int prot);
PS DLOG()
is printf()
to the Android log. FIRST_UNUSED_BIT()
is defined here.
PPS It may not be a good idea to call alloca() in a loop -- the memory may be not freed until the function returns.
The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column
ALTER TABLE MySchema.MyTable ADD
MyColumn int DEFAULT NULL;
But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.
So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:
ALTER TABLE MySchema.MyTable ADD
MyColumn int NULL,
CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;
You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.
As a more elementary situation it would be nice IF this
had a property that could reference it's referring variable (heads
or tails
) but unfortunately it only references the instantiation of the new coinSide
object.
javascript: /* it would be nice but ... a solution NOT! */
function coinSide(){this.ref=this};
/* can .ref be set so as to identify it's referring variable? (heads or tails) */
heads = new coinSide();
tails = new coinSide();
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
alert(["FF's Gecko engine shows:\n\ntoss.toSource() is ", toss.toSource()])
which always displays
[object Object]
and Firefox's Gecko engine shows:
toss.toSource() is ,#1={ref:#1#}
Of course, in this example, to resolve #1
, and hence toss
, it's simple enough to test toss==heads
and toss==tails
. This question, which is really asking if javascript has a call-by-name
mechanism, motivates consideration of the counterpart, is there a call-by-value
mechanism to determine the ACTUAL value of a variable? The example demonstrates that the "values" of both heads
and tails
are identical, yet alert(heads==tails)
is false
.
The self-reference can be coerced as follows:
(avoiding the object space hunt and possible ambiguities as noted in the How to get class object's name as a string in Javascript? solution)
javascript:
function assign(n,v){ eval( n +"="+ v ); eval( n +".ref='"+ n +"'" ) }
function coinSide(){};
assign("heads", "new coinSide()");
assign("tails", "new coinSide()");
toss = Math.random()<0.5 ? heads : tails;
alert(toss.ref);
to display heads
or tails
.
It is perhaps an anathema to the essence of Javascript's language design, as an interpreted prototyping functional language, to have such capabilities as primitives.
A final consideration:
javascript:
item=new Object(); refName="item"; deferAgain="refName";
alert([deferAgain,eval(deferAgain),eval(eval(deferAgain))].join('\n'));
so, as stipulated ...
javascript:
function bindDIV(objName){
return eval( objName +'=new someObject("'+objName+'")' )
};
function someObject(objName){
this.div="\n<DIV onclick='window.opener."+ /* window.opener - hiccup!! */
objName+
".someFunction()'>clickable DIV</DIV>\n";
this.someFunction=function(){alert(['my variable object name is ',objName])}
};
with(window.open('','test').document){ /* see above hiccup */
write('<html>'+
bindDIV('DIVobj1').div+
bindDIV('DIV2').div+
(alias=bindDIV('multiply')).div+
'an aliased DIV clone'+multiply.div+
'</html>');
close();
};
void (0);
Is there a better way ... ?
"better" as in easier? Easier to program? Easier to understand? Easier as in faster execution? Or is it as in "... and now for something completely different"?
Check out the sortBy
method for Eloquent: http://laravel.com/docs/eloquent
df.columns[df.isnull().any()].tolist()
it will return name of columns that contains null rows
@Manuel was part way there. You can add the compiler option as well, like this:
If you have CMake 3.1.0+, this becomes even easier:
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(my_app PRIVATE Threads::Threads)
If you are using CMake 2.8.12+, you can simplify this to:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
target_compile_options(my_app PUBLIC "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
Older CMake versions may require:
find_package(Threads REQUIRED)
if(THREADS_HAVE_PTHREAD_ARG)
set_property(TARGET my_app PROPERTY COMPILE_OPTIONS "-pthread")
set_property(TARGET my_app PROPERTY INTERFACE_COMPILE_OPTIONS "-pthread")
endif()
if(CMAKE_THREAD_LIBS_INIT)
target_link_libraries(my_app "${CMAKE_THREAD_LIBS_INIT}")
endif()
If you want to use one of the first two methods with CMake 3.1+, you will need set(THREADS_PREFER_PTHREAD_FLAG ON)
there too.
You may also consider the following solution:
let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
return html + "<li>" + item + "</li>";
}, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;
GitHub for Windows on Windows 7 currently installs Git
in a path similar to this:
C:\Users\{username}\AppData\Local\GitHub\PortableGit_93e8418133eb85e81a81e5e19c272776524496c6\bin\git.exe
The guid after PortableGit_
may well be different on your system.
Expanding on Jon's correct answer.
The problem here is that your are combining the new "Embed Interop Types" (or NoPIA) feature with use of a class type. The "Embed Interop Types" feature works by essentially statically linking in all of the types from a PIA (Primary Interop Assembly) into the referencing assembly removing the overhead of deploying it.
This feature works great for most types in a PIA but it does have restrictions. One of them is that you cannot embed classes (it's a servicing issue). Misha has a detailed blog article on why this is not allowed
Meaning the 2nd parameter('master
') of the "git push
" command -
$ git push origin master
can be made clear by initiating "push
" command from 'news-item
' branch. It caused local "master
" branch to be pushed to the remote 'master
' branch. For more information refer
https://git-scm.com/docs/git-push
where <refspec>
in
[<repository> [<refspec>…?]
is written to mean "specify what destination ref to update with what source object.
"
For your reference, here is a screen capture how I verified this statement.
You can use a special React
attribute called ref
and then match the real DOM nodes in the onChange
event using React
's getDOMNode()
function:
handleClick: function(event) {
if (event.target === this.refs.prev.getDOMNode()) {
...
}
}
render: function() {
...
<button ref="prev" onClick={this.handleClick}>Previous question</button>
<button ref="next" onClick={this.handleClick}>Next question</button>
...
}
For me the easiest way is to do:
import 'dart:math';
Random rnd = new Random();
r = min + rnd.nextInt(max - min);
//where min and max should be specified.
Thanks to @adam-singer explanation in here.
using (FileStream fs = new FileStream(fileName,FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(something);
}
If you're going to reuse the value like an id or if you want to just keep it you can add a "new{id = 'desiredID/value'}) as its parameters so you can access the value thru jquery/javascript
@Html.HiddenFor(model => model.Car_id)
Open the properties of the solution and click publish. Then, reclick application files. Change prerequisite to include.
I never bother creating with my own regular expression, because chances are that someone else has already come up with a better version. I always use regexlib to find one to my liking.
I Encounter similar issue while doing development on Android Studio 2.2.
My Machine Configuration -
I then made below changes - 1. Uninstall JDK 1.7.0_79 2. Updated JAVA_HOME = 1.8.0_101 JDK path (Similar to SDK Location)
Now i am able to compile and run my application successfully , no more Unsupported major.minor version 52.0 Error
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
In your case if you need your date into yyyy-MM-dd
format you need to specify @JsonFormat
above your field on which you want to apply this format.
For Example :
public class Subject {
private String uid;
private String number;
private String initials;
@JsonFormat(pattern="yyyy-MM-dd")
private Date dateOfBirth;
//Other Code
}
From Docs :
annotation used for configuring details of how values of properties are to be serialized.
Hope this helps.
The simplest Angular jqLite version.
JS:
.directive('cOnChange', function() {
'use strict';
return {
restrict: "A",
scope : {
cOnChange: '&'
},
link: function (scope, element) {
element.on('change', function () {
scope.cOnChange();
});
}
};
});
HTML:
<input type="file" data-c-on-change="your.functionName()">
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
You could do this:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)
func someSelector() {
// Something after a delay
}
For anybody facing a similar issue at this point in time, all you need to do is update your Android Studio to the latest version
In order to use php in .html files, you must associate them with your PHP processor in your HTTP server's config file. In Apache, that looks like this:
AddHandler application/x-httpd-php .html
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine
(In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System; using System.Diagnostics; ... Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // or Trace.Listeners.Add(new ConsoleTraceListener()); Trace.WriteLine("Hello World");
DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub
didn't work for me (ubuntu 14.04
), but you can use :
cat ~/.ssh/id_rsa.pub
to get your public key
You're trying to access a 3 dimensional array with 4 de-references
You only need 3 loops instead of 4, or int myArray[10][10][10][10];
I had have this sort situations when I copied classes from other packages/projects.
Menu->Project->Clean usually helps.
select to_char(date,'Mon') as mon,
extract(year from date) as yyyy,
sum("Sales") as "Sales"
from yourtable
group by 1,2
At the request of Radu, I will explain that query:
to_char(date,'Mon') as mon,
: converts the "date" attribute into the defined format of the short form of month.
extract(year from date) as yyyy
: Postgresql's "extract" function is used to extract the YYYY year from the "date" attribute.
sum("Sales") as "Sales"
: The SUM() function adds up all the "Sales" values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.
group by 1,2
: The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The "1,2" part is a shorthand instead of using the column aliases, though it is probably best to use the full "to_char(...)" and "extract(...)" expressions for readability.
I think this thread actually has the easiest, cleanest solution, that does not sacrifice the JSON martialing tools that Spring provides:
You declared the constructor blowfish as this:
Blowfish(BlowfishAlgorithm algorithm);
So this line cannot exist (without further initialization later):
Blowfish _blowfish;
since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.
If you want to be real smart, at the command line type:
echo svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service >CreateService.cmd
Then you have CreateService.cmd
that you can run whenever you want (.cmd
is just another extension for .bat
files)
You can access 1 line at a time by for loop
#!/bin/bash -eu
#This script prints contents of /etc/passwd line by line
FILENAME='/etc/passwd'
I=0
for LN in $(cat $FILENAME)
do
echo "Line number $((I++)) --> $LN"
done
Copy the entire content to File (say line.sh ) ; Execute
chmod +x line.sh
./line.sh
Following worked for me to get access from another machine to SQL Server using Windows Authentication. This approach may be useful only in development/test environment. E.g. you need to update password manually once you change it on your working machine.
On machine with SQL Server go to Control Panel and add new Windows User with same username and password as is on your working machine. Then create SQL Server login for this user:
CREATE LOGIN [SQLSERVERHOST\myuser] FROM WINDOWS;
Now you can use this login for Windows Authentication.
If you receive error 'The login is from an untrusted domain', this may mean that you changed password on your working machine and now need to update password on SQL Server machine.
Nuget Gallery
provides a GUI similar to the full Visual Studio. See below.
How To Use:
Nuget Gallery
from extension marketplace.View > Command Palette
or ??P (Ctrl+Shift+P on Windows and Linux). Type Nuget: Open Gallery
..csproj file
checkbox is selected, select version from dropdown, and click install button.UPDATE
Earlier versions, as noted in the comments, had an issue where the .csproj
checkbox was not visible when a package in the csproj file was missing a version number like below.
<PackageReference Include="Microsoft.AspNetCore.App" />
This has been fixed in newer versions of the extension so if you have an older version with this issue, please update it to the latest version.
You can do like:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
SELECT @variable1 = col1, @variable2 = col2
FROM table1
Use .blur().
The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as
<input>
. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.
$("#myInputID").blur();
$arr = range(strtotime("2013-12-01"),strtotime("2013-12-31"), "86400");
array_walk_recursive($arr, function(&$element) { $element = date("Y-m-d", $element); });
print_r ($arr);
To post a clarification answer here for those who get directed here by Google.
The document size includes everything in the document including the subdocuments, nested objects etc.
So a document of:
{
"_id": {},
"na": [1, 2, 3],
"naa": [
{ "w": 1, "v": 2, "b": [1, 2, 3] },
{ "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
]
}
Has a maximum size of 16 MB.
Subdocuments and nested objects are all counted towards the size of the document.
There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.
The code is based on a paper by the NCC Group.
will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass
process, in order to temporarily mark keys as exportable. This can be done using PsExec
from SysInternals' PsTools:
PsExec64.exe -s -i cmd
exportrsa.exe
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
If you have it, the lam (laminate) utility can do it, for example:
$ lam filename -s "string after each line"
I think that mobile devices dont work with fixed positions. You should try with some js plugin like skrollr.js (for example). With this kind of plugin you can select the position of your div (or whatever) in function of scrollbar position.
Try docker cp
.
Usage:
docker cp CONTAINER:PATH HOSTPATH
It copies files/folders from PATH
to the HOSTPATH
.
In SQL, the way to do this is to double the apostrophe:
'he doesn''t work for me'
If you are doing this programmatically, you should use an API that accepts parameters and escapes them for you, like prepared statements or similar, rather that escaping and using string concatenation to assemble a query.
This type use:
@Html.ActionLink("MainPage","Index","Home")
MainPage : Name of the text Index : Action View Home : HomeController
Base Use ActionLink
<html>_x000D_
<head>_x000D_
<meta name="viewport" content="width=device-width" />_x000D_
<title>_Layout</title>_x000D_
<link href="@Url.Content("~/Content/bootsrap.min.css")" rel="stylesheet" type="text/css" />_x000D_
</head>_x000D_
<body>_x000D_
<div class="container">_x000D_
<div class="col-md-12">_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("AnaSayfa","Index","Home")</button>_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("Hakkimizda", "Hakkimizda", "Home")</button>_x000D_
<button class="btn btn-default" type="submit">@Html.ActionLink("Iletisim", "Iletisim", "Home")</button>_x000D_
</div> _x000D_
@RenderBody()_x000D_
<div class="col-md-12" style="height:200px;background-image:url(/img/footer.jpg)">_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
If someone else needs a generic utility type to do this, I came up with the following solution:
/**
* Returns object T, but with T[K] overridden to type U.
* @example
* type MyObject = { a: number, b: string }
* OverrideProperty<MyObject, "a", string> // returns { a: string, b: string }
*/
export type OverrideProperty<T, K extends keyof T, U> = Omit<T, K> & { [P in keyof Pick<T, K>]: U };
I needed this because in my case, the key to override was a generic itself.
If you don't have Omit
ready, see Exclude property from type.
This worked for me Bootstrap3
@media (min-width: 768px) {
.navbar-header {
float: none;
}
.navbar-toggle {
display: block;
}
.navbar-collapse {
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
.navbar-collapse.collapse {
display: none!important;
}
.navbar-collapse.collapse.in {
display: block!important;
}
.navbar-nav {
float: none!important;
margin: 7.5px -15px;
}
.navbar-nav>li {
float: none;
}
.navbar-nav>li>a {
padding-top: 10px;
padding-bottom: 10px;
}
}
Took a while to figure these two out:
.navbar-collapse.collapse {
display: none!important;
}
.navbar-collapse.collapse.in {
display: block!important;
}
use this filter:
(dns.flags.response == 0) and (ip.src == 159.25.78.7)
what this query does is it only gives dns queries
originated from your ip
A very simple solution is to override
the toString()
method in the Node
. Then, you can call print by passing LinkedList
's head
.
You don't need to implement any kind of loop.
Code:
public class LinkedListNode {
...
//New
@Override
public String toString() {
return String.format("Node(%d, next = %s)", data, next);
}
}
public class LinkedList {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
l.insertFront(1);
l.insertFront(2);
l.insertFront(3);
//New
System.out.println(l.head);
}
}
__all__
customizes *
in from <module> import *
__all__
customizes *
in from <package> import *
A module is a .py
file meant to be imported.
A package is a directory with a __init__.py
file. A package usually contains modules.
""" cheese.py - an example module """
__all__ = ['swiss', 'cheddar']
swiss = 4.99
cheddar = 3.99
gouda = 10.99
__all__
lets humans know the "public" features of a module.[@AaronHall] Also, pydoc recognizes them.[@Longpoke]
See how swiss
and cheddar
are brought into the local namespace, but not gouda
:
>>> from cheese import *
>>> swiss, cheddar
(4.99, 3.99)
>>> gouda
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'gouda' is not defined
Without __all__
, any symbol (that doesn't start with an underscore) would have been available.
*
are not affected by __all__
>>> import cheese
>>> cheese.swiss, cheese.cheddar, cheese.gouda
(4.99, 3.99, 10.99)
>>> from cheese import swiss, cheddar, gouda
>>> swiss, cheddar, gouda
(4.99, 3.99, 10.99)
>>> import cheese as ch
>>> ch.swiss, ch.cheddar, ch.gouda
(4.99, 3.99, 10.99)
In the __init__.py
file of a package __all__
is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__
customizes the *
when wildcard-importing from the package.[@MartinStettner]
Here's an excerpt from the Python MySQL Connector __init__.py
:
__all__ = [
'MySQLConnection', 'Connect', 'custom_error_exception',
# Some useful constants
'FieldType', 'FieldFlag', 'ClientFlag', 'CharacterSet', 'RefreshOption',
'HAVE_CEXT',
# Error handling
'Error', 'Warning',
...etc...
]
The default case, asterisk with no __all__
for a package, is complicated, because the obvious behavior would be expensive: to use the file system to search for all modules in the package. Instead, in my reading of the docs, only the objects defined in __init__.py
are imported:
If
__all__
is not defined, the statementfrom sound.effects import *
does not import all submodules from the packagesound.effects
into the current namespace; it only ensures that the packagesound.effects
has been imported (possibly running any initialization code in__init__.py
) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by__init__.py
. It also includes any submodules of the package that were explicitly loaded by previous import statements.
And lastly, a venerated tradition for stack overflow answers, professors, and mansplainers everywhere, is the bon mot of reproach for asking a question in the first place:
Wildcard imports ... should be avoided, as they [confuse] readers and many automated tools.
[PEP 8, @ToolmakerSteve]
For Chrome, instead of
response.AppendHeader("X-Frame-Options", "ALLOW-FROM " + host);
you need to add Content-Security-Policy
string selfAuth = System.Web.HttpContext.Current.Request.Url.Authority;
string refAuth = System.Web.HttpContext.Current.Request.UrlReferrer.Authority;
response.AppendHeader("Content-Security-Policy", "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: *.msecnd.net vortex.data.microsoft.com " + selfAuth + " " + refAuth);
to the HTTP-response-headers.
Note that this assumes you checked on the server whether or not refAuth is allowed.
And also, note that you need to do browser-detection in order to avoid adding the allow-from
header for Chrome (outputs error on console).
For details, see my answer here.
I faced a similar problem. The problem in my case was, Number of rows in X was not equal to number of rows in y.
i.e. number of entries in feature columns was not equal to number of entires in target variable since I had dropped some rows from freature columns.
I'm not sure if I'm right, or I'm missing something, but as for now (2016-07-11, running Win7 Enterprise SP1) a LNK file adapts itself on moving or even changing the drive letter after it is run at a new place! I created a new shortcut on my USB drive and tried moving the shortcut and its target in a way that the relative position stayed unchanged, then I changed the drive letter. The shortcut worked in both cases and the target field was adapted after I double-clicked it.
It looks like Microsoft has addressed this issue in one of the past updates.
Please somebody confirm this.
sudo ln -s /usr/local/mysql-5.5.25-osx10.6-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
That worked for me. I installed MySQL from a dmg file.
Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :
public DefaultHttpClient secureClient() {
DefaultHttpClient httpclient = new DefaultHttpClient();
SSLSocketFactory sf;
KeyStore trustStore;
FileInputStream trustStream = null;
File truststoreFile;
// java.security.cert.PKIXParameters for the trustStore
PKIXParameters pkixParamsTrust;
KeyStore keyStore;
FileInputStream keyStream = null;
File keystoreFile;
// java.security.cert.PKIXParameters for the keyStore
PKIXParameters pkixParamsKey;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
truststoreFile = new File(TRUSTSTORE_FILE);
keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keystoreFile = new File(KEYSTORE_FILE);
try {
trustStream = new FileInputStream(truststoreFile);
keyStream = new FileInputStream(keystoreFile);
} catch (FileNotFoundException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
trustStore.load(trustStream, PASSWORD.toCharArray());
keyStore.load(keyStream, PASSWORD.toCharArray());
} catch (IOException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
pkixParamsTrust = new PKIXParameters(trustStore);
// accepts Server certificate generated with keytool and (auto) signed by SUN
pkixParamsTrust.setPolicyQualifiersRejected(false);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
pkixParamsKey = new PKIXParameters(keyStore);
// accepts Client certificate generated with keytool and (auto) signed by SUN
pkixParamsKey.setPolicyQualifiersRejected(false);
} catch (InvalidAlgorithmParameterException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sf = new SSLSocketFactory(trustStore);
ClientConnectionManager manager = httpclient.getConnectionManager();
manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
} catch (KeyManagementException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnrecoverableKeyException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyStoreException ex) {
Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
}
// use the httpclient for any httpRequest
return httpclient;
}
(...) it appears that pip is re-using the cache (...)
I'm pretty sure that's not what's happening. Pip used to (wrongly) reuse build directory not cache. This was fixed in version 1.4 of pip which was released on 2013-07-23.
If you have access to the Notepad++ editor on Windows there is a feature that allows you to easily get around this problem:
I did this and it solved my problems.
Hope this helps!
Read more at http://danieladeniji.wordpress.com/2013/03/07/microsoft-windows-cygwin-error-r-command-not-found/
Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.
This can be caused by having Chrome set to Continue where you left off.
command in one line:
ftp -in -u ftp://username:password@servername/path/to/ localfile