My ngninx logs are located here:
/usr/local/var/log/nginx/*
You can also check your nginx.conf
to see if you have any directives dumping to custom log.
run nginx -t
to locate your nginx.conf
.
# in ngingx.conf
error_log /usr/local/var/log/nginx/error.log;
error_log /usr/local/var/log/nginx/error.log notice;
error_log /usr/local/var/log/nginx/error.log info;
Nginx is usually set up in /usr/local
or /etc/
. The server could be configured to dump logs to /var/log
as well.
If you have an alternate location for your nginx install and all else fails, you could use the find
command to locate your file of choice.
find /usr/ -path "*/nginx/*" -type f -name '*.log'
, where /usr/
is the folder you wish to start searching from.
For MySQL you can directly put conditions in SUM()
function and it will be evaluated as Boolean 0
or 1
and thus you can have your count based on your criteria without using IF/CASE
statements
SELECT
company_name,
SUM(action = 'EMAIL')AS Email,
SUM(action = 'PRINT' AND pagecount = 1)AS Print1Pages,
SUM(action = 'PRINT' AND pagecount = 2)AS Print2Pages,
SUM(action = 'PRINT' AND pagecount = 3)AS Print3Pages
FROM t
GROUP BY company_name
DEMO
There is no straight way, as Kev said. In most cases, it is simpler to spawn another CMD box. More annoyingly, running programs are not aware of changes either (although IIRC there might be a broadcast message to watch to be notified of such change).
It have been worse: in older versions of Windows, you had to log off then log back to take in account the changes...
This works on Laravel 5:
{!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}
import sys
def class_meta(frame):
class_context = '__module__' in frame.f_locals
assert class_context, 'Frame is not a class context'
module_name = frame.f_locals['__module__']
class_name = frame.f_code.co_name
return module_name, class_name
def print_class_path():
print('%s.%s' % class_meta(sys._getframe(1)))
class MyClass(object):
print_class_path()
you could disable transaction via "set_isolation_level(0)"
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
gzip > stdin.gz
perhaps? Otherwise, you need to flesh out your question.
If it's just for passing values between pages and you only require it for the one request. Use Context.
Context
The Context object holds data for a single user, for a single request, and it is only persisted for the duration of the request. The Context container can hold large amounts of data, but typically it is used to hold small pieces of data because it is often implemented for every request through a handler in the global.asax. The Context container (accessible from the Page object or using System.Web.HttpContext.Current) is provided to hold values that need to be passed between different HttpModules and HttpHandlers. It can also be used to hold information that is relevant for an entire request. For example, the IBuySpy portal stuffs some configuration information into this container during the Application_BeginRequest event handler in the global.asax. Note that this only applies during the current request; if you need something that will still be around for the next request, consider using ViewState. Setting and getting data from the Context collection uses syntax identical to what you have already seen with other collection objects, like the Application, Session, and Cache. Two simple examples are shown here:
// Add item to
Context Context.Items["myKey"] = myValue;
// Read an item from the
Context Response.Write(Context["myKey"]);
http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S6
Using the above. If you then do a Server.Transfer
the data you've saved in the context will now be available to the next page. You don't have to concern yourself with removing/tidying up this data as it is only scoped to the current request.
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
xsd.exe does not work well when you have circular references (ie a type can own an element of its own type directly or indirectly).
When circular references exist, I use Xsd2Code. Xsd2Code handles circular references well and works within the VS IDE, which is a big plus. It also has a lot of features you can use like generating the serialization/deserialization code. Make sure you turn on the GenerateXMLAttributes if you are generating serialization though (otherwise you'll get exceptions for ordering if not defined on all elements).
Neither works well with the choice feature. you'll end up with lists/collections of object instead of the type you want. I'd recommend avoiding choice in your xsd if possible as this does not serialize/deserialize well into a strongly typed class. If you don't care about this, though, then it's not a problem.
The any feature in xsd2code deserializes as System.Xml.XmlElement which I find really convenient but may be an issue if you want strong typed objects. I often use any when allowing custom config data, so an XmlElement is convenient to pass to another XML deserializer that is custom defined elsewhere.
@Cort3z: if the problem is still present, this hotfix: https://support.microsoft.com/en-us/kb/2891362 should solve it (from win7 sp1 to 8.1)
Am trying to grep pattern from dozen files .tar.gz but its very slow
tar -ztf file.tar.gz | while read FILENAME do if tar -zxf file.tar.gz "$FILENAME" -O | grep "string" > /dev/null then echo "$FILENAME contains string" fi done
That's actually very easy with ugrep option -z
:
-z, --decompress
Decompress files to search, when compressed. Archives (.cpio,
.pax, .tar, and .zip) and compressed archives (e.g. .taz, .tgz,
.tpz, .tbz, .tbz2, .tb2, .tz2, .tlz, and .txz) are searched and
matching pathnames of files in archives are output in braces. If
-g, -O, -M, or -t is specified, searches files within archives
whose name matches globs, matches file name extensions, matches
file signature magic bytes, or matches file types, respectively.
Supported compression formats: gzip (.gz), compress (.Z), zip,
bzip2 (requires suffix .bz, .bz2, .bzip2, .tbz, .tbz2, .tb2, .tz2),
lzma and xz (requires suffix .lzma, .tlz, .xz, .txz).
Which requires just one command to search file.tar.gz
as follows:
ugrep -z "string" file.tar.gz
This greps each of the archived files to display matches. Archived filenames are shown in braces to distinguish them from ordinary filenames. For example:
$ ugrep -z "Hello" archive.tgz
{Hello.bat}:echo "Hello World!"
Binary file archive.tgz{Hello.class} matches
{Hello.java}:public class Hello // prints a Hello World! greeting
{Hello.java}: { System.out.println("Hello World!");
{Hello.pdf}:(Hello)
{Hello.sh}:echo "Hello World!"
{Hello.txt}:Hello
If you just want the file names, use option -l
(--files-with-matches
) and customize the filename output with option --format="%z%~"
to get rid of the braces:
$ ugrep -z Hello -l --format="%z%~" archive.tgz
Hello.bat
Hello.class
Hello.java
Hello.pdf
Hello.sh
Hello.txt
Using the second form gives you a variable (named based upon the as
clause, in your example e
) in the except
block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
background-image
instead of background
This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}
You could do it like this :
body {
background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
background-size:20px 20px
}
Which works in FF5 and Opera but not in IE8.
mandatory parts:
tbody {
overflow-y: scroll; (could be: 'overflow: scroll' for the two axes)
display: block;
with: xxx (a number or 100%)
}
thead {
display: inline-block;
}
chmod does not allow you to set ownership of a file. To set the ownership of the file you must use the chown command.
I know it's late, I have the same issue with an old custom theme, just added to boostrap.css:
.embed-responsive {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
border: 0;
}
.embed-responsive-16by9 {
padding-bottom: 56.25%;
}
.embed-responsive-4by3 {
padding-bottom: 75%;
}
And for the video:
<div class="embed-responsive embed-responsive-16by9" >
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/jVIxe3YLNs8"></iframe>
</div>
barplot(data)
barplot(data, yaxp=c(0, max(data), 5))
yaxp=c(minY-axis, maxY-axis, Interval)
Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t
. I am glad that you did.
Anyways, You have a .c
source file, and most of the code looks as per C standards, except that #include <iostream>
and using namespace std;
C equivalent for the built-in functions of C++ standard #include<iostream>
can be availed through #include<stdio.h>
#include <iostream>
with #include <stdio.h>
, delete using namespace std;
With #include <iostream>
taken off, you would need a C standard alternative for cout << endl;
, which can be done by printf("\n");
or putchar('\n');
Out of the two options, printf("\n");
works the faster as I observed.
When used printf("\n");
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.031s
user 0m0.030s
sys 0m0.030s
When used putchar('\n');
in the code above in place of cout<<endl;
$ time ./thread.exe
1 2 3 4 5 6 7 8 9 10
real 0m0.047s
user 0m0.030s
sys 0m0.030s
Compiled with Cygwin gcc (GCC) 4.8.3
version. results averaged over 10 samples. (Took me 15 mins)
You can give this simple jQuery plugin (AnimateScroll) a whirl. It is quite easy to use.
1. Scroll to the top of the page:
$('body').animatescroll();
2. Scroll to an element with ID section-1
:
$('#section-1').animatescroll({easing:'easeInOutBack'});
Disclaimer: I am the author of this plugin.
npm install
now supports thisnpm install --save ../path/to/mymodule
For this to work mymodule
must be configured as a module with its own package.json
. See Creating NodeJS modules.
As of npm 2.0, local dependencies are supported natively. See danilopopeye's answer to a similar question. I've copied his response here as this question ranks very high in web search results.
This feature was implemented in the version 2.0.0 of npm. For example:
{ "name": "baz", "dependencies": { "bar": "file:../foo/bar" } }
Any of the following paths are also valid:
../foo/bar ~/foo/bar ./foo/bar /foo/bar
Since npm install
copies mymodule
into node_modules
, changes in mymodule
's source will not automatically be seen by the dependent project.
There are two ways to update the dependent project with
Update the version of mymodule
and then use npm update
: As you can see above, the package.json
"dependencies" entry does not include a version specifier as you would see for normal dependencies. Instead, for local dependencies, npm update
just tries to make sure the latest version is installed, as determined by mymodule
's package.json
. See chriskelly's answer to this specific problem.
Reinstall using npm install
. This will install whatever is at mymodule
's source path, even if it is older, or has an alternate branch checked out, whatever.
You can also use the tag, this works in divs and everything else:
<center><form></form></center>
This link will help you with the tag:
From the documentation I get the impression that in your example it would be intended to use:
@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)
Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:
BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types
Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:
<header class="siteHeader">
<img src="img" class="siteLogo" />
</header>
You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:
.siteHeader{
width: 50px;
height: 50px;
overflow: hidden;
}
.siteHeader .siteLogo{
margin: -100px;
}
Demo can be seen in this JSFiddle.
Only seems to work in IE>9, and probably all significant versions of all other browsers.
run > regedit > HKEY_LOCAL_MACHINE > SOFTWARE > WOW6432Node > Microsoft > Microsoft SQL Server > 90 > SQL Browser > SsrpListener=0
On a current netcat (v0.7.1) you have a -c switch:
-c, --close close connection on EOF from stdin
Hence,
echo "hi" | nc -cu localhost 8000
should do the trick.
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
It tells you that there is some unprocessed migration in your application and it requires running Update-Database
before you can add another migration.
Here is a
Usage example:
timeout 1 | TimeIt.cmd
Execution took ~969 milliseconds.
Copy & paste this into some editor like for example Notepad++ and save it as TimeIt.cmd:
:: --- TimeIt.cmd ----
@echo off
setlocal enabledelayedexpansion
call :ShowHelp
:: Set pipeline initialization time
set t1=%time%
:: Wait for stdin
more
:: Set time at which stdin was ready
set t2=!time!
:: Calculate difference
Call :GetMSeconds Tms1 t1
Call :GetMSeconds Tms2 t2
set /a deltaMSecs=%Tms2%-%Tms1%
echo Execution took ~ %deltaMSecs% milliseconds.
endlocal
goto :eof
:GetMSeconds
Call :Parse TimeAsArgs %2
Call :CalcMSeconds %1 %TimeAsArgs%
goto :eof
:CalcMSeconds
set /a %1= (%2 * 3600*1000) + (%3 * 60*1000) + (%4 * 1000) + (%5)
goto :eof
:Parse
:: Mask time like " 0:23:29,12"
set %1=!%2: 0=0!
:: Replace time separators with " "
set %1=!%1::= !
set %1=!%1:.= !
set %1=!%1:,= !
:: Delete leading zero - so it'll not parsed as octal later
set %1=!%1: 0= !
goto :eof
:ShowHelp
echo %~n0 V1.0 [Dez 2015]
echo.
echo Usage: ^<Command^> ^| %~nx0
echo.
echo Wait for pipe getting ready... :)
echo (Press Ctrl+Z ^<Enter^> to Cancel)
goto :eof
^ - Based on 'Daniel Sparks' Version
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
I had the same issue, luckily I found the below code
@Html.CheckBoxFor(model => model.As, htmlAttributes: new { @checked = true} )
You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.
Try __weak
if you get any warning regarding retain cycle else use __block
Person *strongPerson = [Person new];
__weak Person *weakPerson = person;
Now you can refer weakPerson
object inside block.
Add android:noHistory="true" in manifest file .
<manifest >
<activity
android:name="UI"
android:noHistory="true"/>
</manifest>
The reindent script did not work for me, due to some missing module. Anyway, I found this sed
command which does the job perfect for me:
sed -r 's/^([ ]*)([^ ])/\1\1\2/' file.py
Yes. Problem is in wrong notation. Use:
$this->sendRequest($uri)
Instead. Or
self::staticMethod()
for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php
I ran into this exact same thing and the problem was that the wordcount plugin was taking too long to initialize. 30+ seconds. The user would click into the view displaying the ckeditor, then cancel, thereby ajax-loading a new page into the dom. The plugin was complaining because the iframe or whatever contentWindow is pointing to was no longer visible by the time it was ready to add itself to the contentWindow. You can verify this by clicking into your view and then waiting for the Word Count to appear in the bottom right of the editor. If you cancel now, you won't have a problem. If you don't wait for it, you'll get the i.contentWindow is null error. To fix it, just scrap the plugin:
if (CKEDITOR.instances['textarea_name'])
{
CKEDITOR.instances['textarea_name'].destroy();
}
CKEDITOR.replace('textarea_name', { removePlugins: "wordcount" } );
If you need a word counter, register for the paste and keyup events on the editor with a function that counts the words.
Sometimes it is not eligible to set height to pixel values.
However, it is possible to show vertical scrollbar through setting height of div to 100%
and overflow
to auto
.
Let me show an example:
<div id="content" style="height: 100%; overflow: auto">
<p>some text</p>
<ul>
<li>text</li>
.....
<li>text</li>
</div>
The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.
Hence let's create an HTTP entity and send the headers and parameter in body.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
I actually had a failure in the Microsoft uninstall. I had installed node-v8.2.1-x64 and needed to run version node-v6.11.1-x64.
The uninstalled was failing with the error: "Windows cannot access the specified device, path, or file" or similar.
I ended up going to the Downloads folder right clicking the node-v8.2.1-x64 MSI and selecting uninstall.. this worked.
Regards, Jon
I ran into a similar problem today (but with mod_wsgi
). It might be an Apache 2.2-to-2.4 problem. A comprehensive list of changes can be found here.
For me, it helped to add an additional <Directory>
-entry for every path the error-log was complaining about and filling the section with Require all granted
.
So in your case you could try
<Directory /usr/lib/cgi-bin/php5-fcgi>
Require all granted
Options FollowSymLinks
</Directory>
and I had to move my configuration file from folder conf.d
to folder sites-enabled
.
All in all, that did the trick for me, but I don't guarantee it works in your case as well.
when you want to use your data existing in your data frame as y value, you must add stat = "identity" in mapping parameter. Function geom_bar have default y value. For example,
ggplot(data_country)+
geom_bar(mapping = aes(x = country, y = conversion_rate), stat = "identity")
<input type="hidden" name="item[]" value="[anyvalue]">
Let it be in a repeated mode it will post this element in the form as an array and use the
print_r($_POST['item'])
To retrieve the item
My opinion,
Task.Delay()
is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep()
doesn't return anything ). You can check if this task is completed(use Task.IsCompleted
property) later after another time-consuming process.
Thread.Sleep()
doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.
As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep()
in production code. I couldn't find any use case for it.
Maybe that's because I mostly do web application development.
For tesseract 3, i try to create config file according FAQ.
BEFORE calling an Init function or put this in a text file called tessdata/configs/digits
:
tessedit_char_whitelist 0123456789
then, it works by using the command: tesseract imagename outputbase digits
I've made a small snippet you can use:
from django.conf import settings
from django.db import connection
def sql_echo(method, *args, **kwargs):
settings.DEBUG = True
result = method(*args, **kwargs)
for query in connection.queries:
print(query)
return result
# HOW TO USE EXAMPLE:
#
# result = sql_echo(my_method, 'whatever', show=True)
It takes as parameters function (contains sql queryies) to inspect and args, kwargs needed to call that function. As the result it returns what function returns and prints SQL queries in a console.
SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;
Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:
SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.
An issue I just had was accidentally calling a string
"Foo" ("Bar" if bar else "Baz")
You can concatenate string by just putting them next to each other like so
"Foo" "Bar"
however because of the open brace in the first example it thought I was trying to call "Foo"
CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
I figure out the answer! You need to use the window.onload function as shown below. Thanks to Tec guy and Karim for the help. Note: You still need to use the document ready function too.
window.onload = function() {$('#logo').hide().fadeIn(3000);};
$(function() {$("#div").load(function() {$('#div').hide().fadeIn(750););
It also worked for me when placed right after the image...Thanks
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}
The pip's proxy parameter is, according to pip --help
, in the form scheme://[user:passwd@]proxy.server:port
You should use the following:
pip install --proxy http://user:password@proxyserver:port TwitterApi
Also, the HTTP_PROXY
env var should be respected.
Note that in earlier versions (couldn't track down the change in the code, sorry, but the doc was updated here), you had to leave the scheme://
part out for it to work, i.e. pip install --proxy user:password@proxyserver:port
Thank you for your help. At last I could draw a line on the map. This is how I done it:
/** Called when the activity is first created. */
private List<Overlay> mapOverlays;
private Projection projection;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = (LinearLayout) findViewById(R.id.zoomview);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
mapOverlays.add(new MyOverlay());
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
class MyOverlay extends Overlay{
public MyOverlay(){
}
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(2);
GeoPoint gP1 = new GeoPoint(19240000,-99120000);
GeoPoint gP2 = new GeoPoint(37423157, -122085008);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
Projection projection=mapv.getProjection();
projection.toPixels(gP1, p1);
projection.toPixels(gP2, p2);
path.moveTo(p2.x, p2.y);
path.lineTo(p1.x,p1.y);
canvas.drawPath(path, mPaint);
}
Straight out from the documentation:
Suppose the website example.com would like to send notifications to its users via a Telegram bot. Here's what they could do to enable notifications for a user with the ID 123.
memcache_key = "vCH1vGWJxfSeofSAs0K5PA"
/start
. If the key exists, record the chat_id passed to the webhook as telegram_chat_id for the user 123. Remove the key from Memcache.telegram_chat_id
. If yes, use the sendMessage
method in the Bot API to send them a message in Telegram.UPDATE It is now possible:
https://developers.facebook.com/docs/instagram-api/content-publishing
The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.
First, Install pylint-django
using pip
as follows:
pip install pylint-django
Goto settings.json
find and make sure python linting enabled
is true
like this:
At the bottom write "python.linting.pylintPath": "pylint_django"
like this:
OR,
Go to Settings
and search for python linting
make sure Python > Linting: Pylint Enabled
is checked
Under that Python > Linting: Pylint Path
write pylint_django
Now in react with es6/7 you can bind function to current context with arrow function like this, make request and resolve promises like this :
listMovies = async () => {
const request = await VK.api('users.get',{fields: 'photo_50'});
const data = await request.json()
if (data) {
this.setState({movies: data})
}
}
With this method you can easily call this function in the componentDidMount and wait the data before render your html in your render function.
I don't know the size of your project but I personally advise against using the current state of the component to manipulate datas. You should use external state like Redux or Flux or something else for that.
String[] w = {"a", "b", "c", "d", "e"};
List<String> wL = Arrays.asList(w);
Both algorithms (AES and twofish) are considered very secure. This has been widely covered in other answers.
However, since AES is much widely used now in 2016, it has been specifically hardware-accelerated in several platforms such as ARM and x86. While not significantly faster than twofish before hardware acceleration, AES is now much faster thanks to the dedicated CPU instructions.
Hammer time!
I have used Hammer JS and it work with gesture. Read details from here: https://hammerjs.github.io/
Good thing that it is much more light weight and fast then jQuery mobile. You can test it on their website as well.
We can use zPosition in ios
if we have a view named salonDetailView
eg : @IBOutlet weak var salonDetailView: UIView!
and have UIView for GMSMapView
eg : @IBOutlet weak var mapViewUI: GMSMapView!
To show the View salonDetailView upper of the mapViewUI
use zPosition as below
salonDetailView.layer.zPosition = 1
You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.
This is one way to do it:
Fiddle here: http://jsfiddle.net/4Mvan/1/
HTML:
<div class='container'>
<a href='#'>
<img class='resize_fit_center'
src='http://i.imgur.com/H9lpVkZ.jpg' />
</a>
</div>
CSS:
.container {
margin: 10px;
width: 115px;
height: 115px;
line-height: 115px;
text-align: center;
border: 1px solid red;
}
.resize_fit_center {
max-width:100%;
max-height:100%;
vertical-align: middle;
}
You have to import the following two libraries:
import java.util.*
import kotlin.concurrent.schedule
and after that use it in this way:
Timer().schedule(10000){
//do something
}
There's a tagName
property, and a attributes
property as well:
var element = document.getElementById("wtv");
var openTag = "<"+element.tagName;
for (var i = 0; i < element.attributes.length; i++) {
var attrib = element.attributes[i];
openTag += " "+attrib.name + "=" + attrib.value;
}
openTag += ">";
alert(openTag);
See also How to iterate through all attributes in an HTML element? (I did!)
To get the contents between the open and close tags you could probably use innerHTML
if you don't want to iterate over all the child elements...
alert(element.innerHTML);
... and then get the close tag again with tagName
.
var closeTag = "</"+element.tagName+">";
alert(closeTag);
+1 the recommendation for Joda-time. If you plan on doing anything more than a simple Hello World example, I suggest reading this:
I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.
You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.
Edit:
Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.
For instance:
public ActionResult Index()
{
return View();
}
[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
// load object and return in view
ViewModel viewModel = Load(id);
// get the previous url and store it with view model
viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
// Attempt to save the posted object if it works, return index if not return the Edit view again
bool success = Save(viewModel);
if (success)
{
return Redirect(viewModel.PreviousUrl);
}
else
{
ModelState.AddModelError("There was an error");
return View(viewModel);
}
}
The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:
@model ViewModel
@using (Html.BeginForm())
{
...
<input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}
Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.
This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.
ERROR:
could not find driver (SQL: select * from tests
where slug
= a limit 1)
I was getting the above error in my laravel project, i am using nginx server on ubuntu 16.04
This error is because, php-mysql
driver is missing. To install it type following command.
sudo apt-get install php7.2-mysql
Please specify your current php version
in above command.
Open php.ini
file and uncomment the followling line of code(Remove Semicolon).
;extension=pdo_mysql
Then Restart the nginx and php service
sudo systemctl restart php7.2-fpm
sudo systemctl restart nginx
It worked for me.
try running SHOW CREATE VIEW my_view_name
in the sql portion of phpmyadmin and you will have a better idea of what is inside the view
I used the Multiple SCMs Plugin in conjunction with the Git Plugin successfully with Jenkins.
@DanielVelkov answer is the proper one BUT using string literals is faster:
# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
You also can create Firbase Dynamic links which will work as per your requirement. It supports multiple platforms. This link can be created, manually as well as via programming. You can then embed this link in QR code.
If the target app is installed, the link will redirect user to app. If its not installed it will redirect to Play Store/App store/Any other configured website.
To avoid using the .Select
method, you can set a variable equal to the property that you want.
? For instance, if you want the value in Cell A1
you could set a variable equal to the value property of that cell.
valOne = Range("A1").Value
? For instance, if you want the codename of 'Sheet3you could set a variable equal to the
Codename` property of that worksheet.
valTwo = Sheets("Sheet3").Codename
git diff 15dc8 15dce~1
~1 means 'parent', ~2 'grandparent, etc.
Another important difference are the languages supported by default.
Both could be extended to other platforms, but these are the languages bindings available out-of-the-box.
You could check if the scroll-offsets are in the bounds. If they go beyond, set them back.
var scrollX = 0;
var scrollY = 0;
var scrollMinX = 0;
var scrollMinY = 0;
var scrollMaxX = document.body.scrollWidth - window.innerWidth;
var scrollMaxY = document.body.scrollHeight - window.innerHeight;
// make sure that we work with the correct dimensions
window.addEventListener('resize', function () {
scrollMaxX = document.body.scrollWidth - window.innerWidth;
scrollMaxY = document.body.scrollHeight - window.innerHeight;
}, false);
// where the magic happens
window.addEventListener('scroll', function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
if (scrollX <= scrollMinX) scrollTo(scrollMinX, window.scrollY);
if (scrollX >= scrollMaxX) scrollTo(scrollMaxX, window.scrollY);
if (scrollY <= scrollMinY) scrollTo(window.scrollX, scrollMinY);
if (scrollY >= scrollMaxY) scrollTo(window.scrollX, scrollMaxY);
}, false);
Browser development progresses:
Number.toLocaleString(locale);
// E.g.
parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
"1,234,567.891"
Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class
myObj:any = {
doSomething: function () { console.log('doing something'); return 'doing something'; },
};
myArray:any;
constructor() { }
ngOnInit() {
this.myArray = [this.myObj];
}
You can use it in template html file as following:
<div>test-1: {{ myObj?.doSomething()}}</div>
<div>test-2: {{ myArray[0].doSomething()}}</div>
<div>test-3: {{ myArray[2]?.doSomething()}}</div>
It only worked for me in Firefox when accessing it from the window
object.
Example...
window.onload = function()
{
window.localStorage.clear();
}
I ended up using BackgroundWorker, it is definitely asynchronous unlike some of the above solutions, it handles returning to the GUI thread for you, and it is very easy to understand.
It is also very easy to handle exceptions, as they end up in the RunWorkerCompleted method, but make sure you read this: Unhandled exceptions in BackgroundWorker
I used WebClient but obviously you could use HttpWebRequest.GetResponse if you wanted.
var worker = new BackgroundWorker();
worker.DoWork += (sender, args) => {
args.Result = new WebClient().DownloadString(settings.test_url);
};
worker.RunWorkerCompleted += (sender, e) => {
if (e.Error != null) {
connectivityLabel.Text = "Error: " + e.Error.Message;
} else {
connectivityLabel.Text = "Connectivity OK";
Log.d("result:" + e.Result);
}
};
connectivityLabel.Text = "Testing Connectivity";
worker.RunWorkerAsync();
Use theme():
d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
This worked for me as well:
Get-ADUser -Filter * -SearchBase "ou=OU,dc=Domain,dc=com" -Properties Enabled, CanonicalName, Displayname, Givenname, Surname, EmployeeNumber, EmailAddress, Department, StreetAddress, Title | select Enabled, CanonicalName, Displayname, GivenName, Surname, EmployeeNumber, EmailAddress, Department, Title | Export-CSV "C:\output.csv"
Nothing from above worked for me. The problem for me was that I had wrong source in my Java Build Path for android-support-v7-appcompat. When you go to Project> Build Path> Configure Build Path>. Under the Source tab make sure you have android-support-v7-appcompat/gen , android-support-v7-appcompat/libs and android-support-v7-appcompat/src and nothing else. Click OK and it should work.
This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a
public class ExportImportDB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");
if(!direct.exists())
{
if(direct.mkdir())
{
//directory is created;
}
}
exportDB();
importDB();
}
//importing database
private void importDB() {
// TODO Auto-generated method stub
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File backupDB= new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
//exporting database
private void exportDB() {
// TODO Auto-generated method stub
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
}
Dont forget to add this permission to proceed it
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
Enjoy
try changing that line-height change to a margin-top or padding-top change instead
#btnhome:active{
margin-top : 25px;
}
Edit: You could also try adding a span inside the button
<div id="header">
<button id="btnhome"><span>Home</span></button>
<button id="btnabout">About</button>
<button id="btncontact">Contact</button>
<button id="btnsup">Help Us</button>
</div>
Then style that
#btnhome span:active { padding-top:25px;}
There are multiple ways. You may use this too.
echo "Your string here"| tr ' ' '\n' | tail -n1
> here
Obviously, the blank space input for tr command should be replaced with the delimiter you need.
Assuming everything descends from object
(you are on your own if it doesn't), Python computes a method resolution order (MRO) based on your class inheritance tree. The MRO satisfies 3 properties:
If no such ordering exists, Python errors. The inner workings of this is a C3 Linerization of the classes ancestry. Read all about it here: https://www.python.org/download/releases/2.3/mro/
Thus, in both of the examples below, it is:
When a method is called, the first occurrence of that method in the MRO is the one that is called. Any class that doesn't implement that method is skipped. Any call to super
within that method will call the next occurrence of that method in the MRO. Consequently, it matters both what order you place classes in inheritance, and where you put the calls to super
in the methods.
super
first in each methodclass Parent(object):
def __init__(self):
super(Parent, self).__init__()
print "parent"
class Left(Parent):
def __init__(self):
super(Left, self).__init__()
print "left"
class Right(Parent):
def __init__(self):
super(Right, self).__init__()
print "right"
class Child(Left, Right):
def __init__(self):
super(Child, self).__init__()
print "child"
Child()
Outputs:
parent
right
left
child
super
last in each methodclass Parent(object):
def __init__(self):
print "parent"
super(Parent, self).__init__()
class Left(Parent):
def __init__(self):
print "left"
super(Left, self).__init__()
class Right(Parent):
def __init__(self):
print "right"
super(Right, self).__init__()
class Child(Left, Right):
def __init__(self):
print "child"
super(Child, self).__init__()
Child()
Outputs:
child
left
right
parent
IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.
An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.
Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.
Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.
m
- for classes that set margin, like this :
mt
- for classes that set margin-top
mb
- for classes that set margin-bottom
ml
- for classes that set margin-left
mr
- for classes that set margin-right
mx
- for classes that set both margin-left
and margin-right
my
- for classes that set both margin-top
and margin-bottom
Where size is one of margin :
0
- for classes that eliminate the margin by setting it to
0, like mt-0
1
- (by default) for classes that set the margin to
$spacer * .25, like mt-1
2
- (by default) for classes that set the margin to
$spacer * .5, like mt-2
3
- (by default) for classes that set the margin to
$spacer, like mt-3
4
- (by default) for classes that set the margin to
$spacer * 1.5, like mt-4
5
- (by default) for classes that set the margin to $spacer * 3, like mt-5
auto
- for classes that set the margin to auto, like mx-auto
In order to prevent phishing, some mail servers prevent the From from being rewritten.
Well, you should also try adding the Javascript code into a function, then calling the function after document body has loaded..it worked for me :)
If you're accessing this via a View then try sp_recompile
or refreshing views.
sp_recompile
:
Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.
Arguments
[ @objname= ] 'object'
The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.
Return Code Values
0 (success) or a nonzero number (failure)
Remarks
sp_recompile
looks for an object in the current database only.
The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.
tl;dr
Add the line:
export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home'
to the file
~/.bash_profile
(replace jdk1.8.0_144.jdk with your downloaded version)
then source ~/.bash_profile
Here is an example where both the FULL OUTER JOIN and CROSS JOIN return the same result set without NULL returned. Please note the 1 = 1 in the ON clause for the FULL OUTER JOIN:
declare @table1 table ( col1 int, col2 int )
declare @table2 table ( col1 int, col2 int )
insert into @table1 select 1, 11 union all select 2, 22
insert into @table2 select 10, 101 union all select 2, 202
select *
from @table1 t1 full outer join @table2 t2
on 1 = 1
(2 row(s) affected) (2 row(s) affected) col1 col2 col1 col2 ----------- ----------- ----------- ----------- 1 11 10 101 2 22 10 101 1 11 2 202 2 22 2 202
select *
from @table1 t1 cross join @table2 t2
col1 col2 col1 col2 ----------- ----------- ----------- ----------- 1 11 10 101 2 22 10 101 1 11 2 202 2 22 2 202 (4 row(s) affected)
in my case adding process.env.PORT || 3000
to my http server script, resolved.
My heroku log reported 'H20' error and 503 http status.
Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.
Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.
You can count how many digits you want to print first
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int number, result, counter=0, zeros;
do{
cout << "Introduce un numero entero: ";
cin >> number;
}while (number < 0);
// We count how many digits we are going print
for(int i = number; i > 0; i = i/10)
counter++;
while(number > 0){
zeros = pow(10, counter - 1);
result = number / zeros;
number = number % zeros;
counter--;
//Muestra resultados
cout << " " << result;
}
cout<<endl;
}
Specify the name of columns in the CSV in the load data infile statement.
The code is like this:
LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);
Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.
The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.
Thank you.
If you have the process ID (PID
) you can kill this process as follow:
Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):
EDIT: edited for pasting values only based on comments below.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Set copySheet = Worksheets("Sheet1")
Set pasteSheet = Worksheets("Sheet2")
copySheet.Range("A3:E3").Copy
pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
This is how it looks like in Kotlin
main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
<item
android:id="@+id/action_logout"
android:orderInCategory="101"
android:title="@string/sign_out"
app:showAsAction="never" />
Then in MainActivity
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
This is onOptionsItemSelected function
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when(item.itemId){
R.id.action_settings -> {
true
}
R.id.action_logout -> {
signOut()
true
}
else -> return super.onOptionsItemSelected(item)
}
}
For starting new activity
private fun signOut(){
MySharedPreferences.clearToken()
startSplashScreenActivity()
}
private fun startSplashScreenActivity(){
val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
startActivity(intent)
finish()
}
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
PostgreSQL also supports full POSIX regular expressions:
select * from table where value ~* 'foo|bar|baz';
The ~*
is for a case insensitive match, ~
is case sensitive.
Another option is to use ANY:
select * from table where value like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.
Incidentally, if your span
class is even-numbered (e.g. span8
) you can add an offset
class to center it – for span8
that would be offset2
(assuming the default 12-column grid), for span6
it would be offset3
and so on (basically, half the number of remaining columns if you subtract the span
-number from the total number of columns in the grid).
UPDATE
Bootstrap 3 renamed a lot of classes so all the span*
classes should be col-md-*
and the offset
classes should be col-md-offset-*
, assuming you're using the medium-sized responsive grid.
I created a quick demo here, hope it helps: http://codepen.io/anon/pen/BEyHd.
I recommend two steps to address the bloated SDK problem.
First, I removed all but two versions of Android:
The current version, e.g. 6.0 Marshmallow as of this writing. This version is to test and develop to the latest and greatest that the current Nexus handsets are running plus a couple of other brands.
An older version, e.g. 4.04 Ice Cream Sandwich. This is to provide compatibility for the vast majority of handsets. You lose some functionality of the newer versions, but you gain a lowest common denominator of compatibility.
Second, I removed the emulators, and kept only the above two. I told it not to store the complete system state to disk, which it does indeed warn you will take up a lot of space, though it does make start-up faster. Just start up the emulator before you go make your coffee in the morning :)
If that's too much space, remove the emulators completely. Pick up a couple of older handsets off Ebay that will provide you with all the test platforms you need. They don't even have to be completely functional -- many apps don't need a SIM and cellular connectivity, for example.
My Android environment was taking up 32 gigs on my 128-gig Macbook Air. Couldn't keep doing this. Some day they'll make terabyte Macbook Airs but until then, got to slim down.
Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):
Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);
It seems that using mongoose there is a limit of more than 1000 documents, when using
Potato.collection.insert(potatoBag, onInsert);
You can use:
var bulk = Model.collection.initializeOrderedBulkOp();
async.each(users, function (user, callback) {
bulk.insert(hash);
}, function (err) {
var bulkStart = Date.now();
bulk.execute(function(err, res){
if (err) console.log (" gameResult.js > err " , err);
console.log (" gameResult.js > BULK TIME " , Date.now() - bulkStart );
console.log (" gameResult.js > BULK INSERT " , res.nInserted)
});
});
But this is almost twice as fast when testing with 10000 documents:
function fastInsert(arrOfResults) {
var startTime = Date.now();
var count = 0;
var c = Math.round( arrOfResults.length / 990);
var fakeArr = [];
fakeArr.length = c;
var docsSaved = 0
async.each(fakeArr, function (item, callback) {
var sliced = arrOfResults.slice(count, count+999);
sliced.length)
count = count +999;
if(sliced.length != 0 ){
GameResultModel.collection.insert(sliced, function (err, docs) {
docsSaved += docs.ops.length
callback();
});
}else {
callback()
}
}, function (err) {
console.log (" gameResult.js > BULK INSERT AMOUNT: ", arrOfResults.length, "docsSaved " , docsSaved, " DIFF TIME:",Date.now() - startTime);
});
}
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
To make a text default in a select box use the $form->select()
method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female
in the list box by default.
Keep baking...
For future visitors, you can also (best IMHO) import WordUtil
from Apache
and add a lot of useful methods to you app, like capitalize
as shown here:
How to capitalize the first character of each word in a string
It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name. my_data
is obviously a typedef for a struct
type that has a member name
of type char *
or char [N]
.
I'd a custom function written on one of my models __init__.py
file. It was causing the error. When I moved this function from __init__.py
it worked.
Did you check the MSDN documentation (or IntelliSense)? How about the String.Substring
method?
You can get the length using the Length
property, subtract two from this, and return the substring from the beginning to 2 characters from the end.
For example:
string str = "Hello Marco !";
str = str.Substring(0, str.Length - 2);
Yes, it is valid to use the anchor tag without a href
attribute.
If the
a
element has nohref
attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.
Yes, you can use class
and other attributes, but you can not use target
, download
, rel
, hreflang
, and type
.
The
target
,download
,rel
,hreflang
, andtype
attributes must be omitted if the href attribute is not present.
As for the "Should I?" part, see the first citation: "where a link might otherwise have been placed if it had been relevant". So I would ask "If I had no JavaScript, would I use this tag as a link?". If the answer is yes, then yes, you should use <a>
without href
. If no, then I would still use it, because productivity is more important for me than edge case semantics, but this is just my personal opinion.
Additionally, you should watch out for different behaviour and styling (e.g. no underline, no pointer cursor, not a :link
).
Source: W3C HTML5 Recommendation
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
The best video playback/encoding library I have ever seen is ffmpeg. It plays everything you throw at it. (It is used by MPlayer.) It is written in C but I found some Java wrappers.
What ultimately worked for me was the following steps:
This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:
{
"time": {
"daysInMonth": 31,
"millisecond": 283,
"second": 42,
"minute": 55,
"hour": 1,
"date": 6,
"day": 3,
"week": 10,
"month": 2,
"year": 2013,
"zone": "+0000"
},
"formatted": {
"weekday": "Wednesday",
"month": "March",
"ago": "a few seconds",
"calendar": "Today at 1:55 AM",
"generic": "2013-03-06T01:55:42+00:00",
"time": "1:55 AM",
"short": "03/06/2013",
"slim": "3/6/2013",
"hand": "Mar 6 2013",
"handTime": "Mar 6 2013 1:55 AM",
"longhand": "March 6 2013",
"longhandTime": "March 6 2013 1:55 AM",
"full": "Wednesday, March 6 2013 1:55 AM",
"fullSlim": "Wed, Mar 6 2013 1:55 AM"
},
"array": [
2013,
2,
6,
1,
55,
42,
283
],
"offset": 1362534942283,
"unix": 1362534942,
"utc": "2013-03-06T01:55:42.283Z",
"valid": true,
"integer": false,
"zone": 0
}
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
This is how to get the html DOM element purely with JS:
var htmlElement = document.getElementsByTagName("html")[0];
or
var htmlElement = document.querySelector("html");
And if you want to use jQuery to get attributes from it...
$(htmlElement).attr(INSERT-ATTRIBUTE-NAME);
(B)|(A)
then use what group 2 captures...
Try putting both columns in the same orderby.
orderby p.LowestPrice.HasValue descending, p.LowestPrice
Otherwise each orderby is a separate operation on the collection re-ordering it each time.
This should order the ones with a value first, "then" the order of the value.
Method 1:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
//Identify your elements and go ahead testing...
This will definetly not show any error and browser will open and also will navigate to the URL.
BUT This will not identify any element and hence you can not proceed.
Why? Because we have simly suppressed the error and asked IE to open and get that URL. However Selenium will identify elements only if the browser zoom is 100% ie. default. So the final code would be
Method 2 The robust and full proof way:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true);
System.setProperty("webdriver.ie.driver","D:\\IEDriverServer_Win32_2.33.0\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver(capabilities);
driver.get(baseURl);
driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL,"0"));
//Identify your elements and go ahead testing...
Hope this helps. Do let me know if further information is required.
If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:
some_string = " Hello, world!\n "
new_string = some_string.strip()
# new_string is now "Hello, world!"
This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.
But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split()
and " ".join
, like this:
some_string = "\t Hello, \n\t world!\n "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"
In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.
background.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:width="3dp"
android:color="#0FECFF" />
//specify gradient
<gradient
android:startColor="#ffffffff"
android:endColor="#110000FF"
android:angle="90"/>
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="210dp"
android:orientation="vertical"
android:layout_marginBottom="10dp"
android:background="@drawable/background">
I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.
Before:
<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">
After:
<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">
When I do what explains some answers:
The result is:
So, anybody can explain really really how to delete an old App ID?
My opinion is: Apple does not let you remove them. I suppose it is a way to maintain the traceability or the historical of the published.
And of course: application is no longer available in the App Store. It was available (in the past), yes.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
You can send Email by Jquery just follow these steps
include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :
$( document ).ready(function() {
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
I found this thread while trying to carry out a similar task. In the end, I used
Range("F:F").SpecialCells(xlBlanks).Areas(1)(1).Select
Which works fine as long as there is a blank cell in the intersection of the specified range and the used range of the worksheet.
The areas property is not needed to find the absolute first blank in the range, but is useful for finding subsequent non consecutive blanks.
numpy.array
is a function that returns a numpy.ndarray
. There is no object type numpy.array.
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
Here some useful resource, hope can help you to chose your CDN. MS has recently add a new domain for delivery Libraries trough their CDN.
Old Format: http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.1.js New Format: http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js
This should not send all cookies for microsoft.com. http://www.asp.net/ajaxlibrary/cdn.ashx#Using_jQuery_from_the_CDN_11
Here some statistics about most popular technology used on the web across all technology. http://trends.builtwith.com/
Hope can help you to choose.
Try the following
for ( const auto &p : table )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
The same can be written using an ordinary for loop
for ( auto it = table.begin(); it != table.end(); ++it )
{
std::cout << it->first << '\t' << it->second << std::endl;
}
Take into account that value_type for std::map
is defined the following way
typedef pair<const Key, T> value_type
Thus in my example p is a const reference to the value_type where Key is std::string
and T is int
Also it would be better if the function would be declared as
void output( const map<string, int> &table );
It is possible using position:fixed
on <th>
(<th>
being the top row).
A more verbose, but broadly applicable solution to this sort of problem is to use a pair of data structures: a list to contain the ordering, and a map to contain the relations.
For Example:
{
"items":
[
{
"WR":"qwe",
"QU":"asd",
"QA":"end",
"WO":"hasd",
"NO":"qwer"
},
],
"itemOrder":
["WR", "QU", "QA", "WO", "NO"]
}
You iterate the itemOrder list, and use those to look up the map values. Ordering is preserved, with no kludges.
I have used this method many times.
You should use finish()
when the user clicks on the button in order to go to the previous activity.
Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Alternatively, if you really need to, you can try to trigger your own back key press:
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Execute both of these.
I use the following code to write files on my web directory.
write_file.html
<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>
write_file.php
<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);
// Show the msg, if the code string is empty
if (empty($cd))
echo "Nothing to write";
// if the code string is not empty then open the target file and put form data in it
else
{
$file = fopen("demo.php", "w");
echo fwrite($file, $cd);
// show a success msg
echo "data successfully entered";
fclose($file);
}
?>
This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.
Good luck.
what about just have the option number:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
int op;
cin >> s >> op;
switch (op) {
case 1: break;
case 2: break;
default:
}
return 0;
}
My suggestion would be to use a StringIO
object. They emulate files, but reside in memory. So you could do something like this:
# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'
import zipfile
from StringIO import StringIO
zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()
# output: "hey, foo"
Or more simply (apologies to Vishal):
myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
[ ... ]
In Python 3 use BytesIO instead of StringIO:
import zipfile
from io import BytesIO
filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
[ ... ]
Going by the comments as well as personal experience, I say no, there is no need for range(len(a))
. Everything you can do with range(len(a))
can be done in another (usually far more efficient) way.
You gave many examples in your post, so I won't repeat them here. Instead, I will give an example for those who say "What if I want just the length of a
, not the items?". This is one of the only times you might consider using range(len(a))
. However, even this can be done like so:
>>> a = [1, 2, 3, 4]
>>> for _ in a:
... print True
...
True
True
True
True
>>>
Clements answer (as shown by Allik) can also be reworked to remove range(len(a))
:
>>> a = [6, 3, 1, 2, 5, 4]
>>> sorted(range(len(a)), key=a.__getitem__)
[2, 3, 1, 5, 4, 0]
>>> # Note however that, in this case, range(len(a)) is more efficient.
>>> [x for x, _ in sorted(enumerate(a), key=lambda i: i[1])]
[2, 3, 1, 5, 4, 0]
>>>
So, in conclusion, range(len(a))
is not needed. Its only upside is readability (its intention is clear). But that is just preference and code style.
if Edittext
parent layout is Linear
then add
android:focusable="true"
android:focusableInTouchMode="true"
like below
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:focusableInTouchMode="true">
<EditText/>
............
when Edittext parent layout is Relative then
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
like
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true">
<EditText/>
............
I use this to open a workbook and then copy that workbook's data to the template.
Private Sub CommandButton24_Click()
Set Template = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "I:\Group - Finance" ' Yu can select any folder you want
.Filters.Clear
.Title = "Your Title"
If Not .Show Then
MsgBox "No file selected.": Exit Sub
End If
Workbooks.OpenText .SelectedItems(1)
'The below is to copy the file into a new sheet in the workbook and paste those values in sheet 1
Set myfile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Copy after:=ThisWorkbook.Sheets(1)
myfile.Close
Template.Activate
ActiveSheet.Cells.Select
Selection.Copy
Sheets("Sheet1").Select
Cells.Select
ActiveSheet.Paste
End With
getAttribute() -> It fetches the text that contains one of any attribute in the HTML tag. Suppose there is an HTML tag like
<input name="Name Locator" value="selenium">Hello</input>
Now getAttribute() fetches the data of the attribute of 'value', which is "Selenium".
Returns:
The attribute's current value or null if the value is not set.
driver.findElement(By.name("Name Locator")).getAttribute("value") //
The field value is retrieved by the getAttribute("value") Selenium WebDriver predefined method and assigned to the String object.
getText() -> delivers the innerText of a WebElement. Get the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace.
Returns:
The innerText of this element.
driver.findElement(By.name("Name Locator")).getText();
'Hello' will appear
autoconf
and automake
:configure
, make
and sudo make install
:./configure # Creates Makefile (from Makefile.in).
make # Creates the application (from the Makefile just created).
sudo make install # Installs the application
# Often, by default its files are installed into /usr/local
Notation below is roughly: inputs --> programs --> outputs
DEVELOPER runs these:
configure.ac -> autoconf -> configure (script) --- (*.ac = autoconf)
configure.in --> autoconf -> configure (script) --- (configure.in
depreciated. Use configure.ac)
Makefile.am -> automake -> Makefile.in ----------- (*.am = automake)
INSTALLER runs these:
Makefile.in -> configure -> Makefile (*.in = input file)
Makefile -> make ----------> (puts new software in your downloads or temporary directory)
Makefile -> make install -> (puts new software in system directories)
"autoconf is an extensible package of M4 macros that produce shell scripts to automatically configure software source code packages. These scripts can adapt the packages to many kinds of UNIX-like systems without manual user intervention. Autoconf creates a configuration script for a package from a template file that lists the operating system features that the package can use, in the form of M4 macro calls."
"automake is a tool for automatically generating Makefile.in files compliant with the GNU Coding Standards. Automake requires the use of Autoconf."
Manuals:
GNU AutoTools (The definitive manual on this stuff)
m4 (used by autoconf)
Free online tutorials:
The main configure.ac used to build LibreOffice is over 12k lines of code, (but there are also 57 other configure.ac files in subfolders.)
From this my generated configure is over 41k lines of code.
And while the Makefile.in and Makefile are both only 493 lines of code. (But, there are also 768 more Makefile.in's in subfolders.)
Take a look here
That is the source code for Ants' SCP task. The code in the "execute" method is where the nuts and bolts of it are. This should give you a fair idea of what is required. It uses JSch i believe.
Alternatively you could also directly execute this Ant task from your java code.
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.
Additionally, it offers actions to do to the locked file in question such as deleting it.
Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.
Some errors you might get that Unlocker can help with include:
- Cannot delete file: Access is denied.
- There has been a sharing violation.
- The source or destination file may be in use.
- The file is in use by another program or user.
- Make sure the disk is not full or write-protected and that the file is not currently in use.
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
Javascript has a ternary operator you could use:
var i = result ? 1 : 0;
a bug(?!) in iOS10/Swift3/Xcode 8?
if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
let playerItem = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300)
self.view.layer.addSublayer(playerLayer)
}
does not work (empty rect...)
this works:
if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
let player = AVPlayer(url: url)
let controller=AVPlayerViewController()
controller.player=player
controller.view.frame = self.view.frame
self.view.addSubview(controller.view)
self.addChildViewController(controller)
player.play()
}
Same URL...
In Windows 10 PC, it is saved at:
C:\Users\<user>\.gradle\caches\modules-2\files-2.1\
Thanking Daniel Jimenez for his perfect solution to fetch column names alone from my csv, I extend his solution to use DictReader so we can iterate over the rows using column names as indexes. Thanks Jimenez.
with open('myfile.csv') as csvfile:
rest = []
with open("myfile.csv", "rb") as f:
reader = csv.reader(f)
i = reader.next()
i=i[1:]
re=csv.DictReader(csvfile)
for row in re:
for x in i:
print row[x]
If you don't mind not using ng-click
, it works OK. You can just rename it to something else and still read the attribute, while avoiding the click handler being triggered twice problem there is at the moment.
http://plnkr.co/edit/YWr6o2?p=preview
I think the problem is terminal
instructs other directives not to run. Data-binding with {{ }}
is just an alias for the ng-bind
directive, which is presumably cancelled by terminal
.
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
I... don't think so. You can redirect the subdomain (such as blah.something.com
) to point to something.com:25566
, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.
First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.
Set up your variable like this:
IEnumerable<IEnumerable<string>> data = new[] {
new[]{"...", "...", "..."},
... etc ...
};
Then you'd simply go:
var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null);
The Where makes sure it prunes any nulls if you have an empty list as an item inside.
Alternatively you can implement it as:
string[][] = new[] {
new[]{"...","...","..."},
new[]{"...","...","..."},
... etc ...
};
This could be used similarly to a [x,y]
array but it's used like this: [x][y]
My guess is that you are trying to restore in lower versions which wont work
(This answer is mostly for googlers, because OP has solved his problem already.)
The meaning of prepended ::
- scope resulution operator - has been described in other answers, but I'd like to add why people are using it.
The meaning is "take name from global namespace, not anything else". But why would this need to be spelled explicitly?
Use case - namespace clash
When you have the same name in global namespace and in local/nested namespace, the local one will be used. So if you want the global one, prepend it with ::
. This case was described in @Wyatt Anderson's answer, plese see his example.
Use case - emphasise non-member function
When you are writing a member function (a method), calls to other member function and calls to non-member (free) functions look alike:
class A {
void DoSomething() {
m_counter=0;
...
Twist(data);
...
Bend(data);
...
if(m_counter>0) exit(0);
}
int m_couner;
...
}
But it might happen that Twist
is a sister member function of class A
, and Bend
is a free function. That is, Twist
can use and modify m_couner
and Bend
cannot. So if you want to ensure that m_counter
remains 0, you have to check Twist
, but you don't need to check Bend
.
So to make this stand out more clearly, one can either write this->Twist
to show the reader that Twist
is a member function or write ::Bend
to show that Bend
is free. Or both. This is very useful when you are doing or planning a refactoring.
There seems to be a bug in Visual Studio 2015 community. For a 64-bit project, the include folder isn't found unless it's in the win32 bit configuration Additional Include Folders list.
For Linux Mate 17.1 Go to Menu/All applications/Keyboard/Layouts tab/Click Add/Pick out your layout by country or by language/Click Add and a language icon (US, PT and so on) will show at Panel/Close Keyboard Preferences and just click over it at Panel to switch the input language.
It's better to avoid using unnecessary javascript. You can take advantage of the label tag to expand the click target of the input like so:
<label>
<input type="file" style="display: none;">
<a>Open</a>
</label>
Even though input is hidden, the link still works as a click target for it, and you can style it however you want.
In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add @Html.AntiForgeryToken()
if you use razor form element or if you use IHtmlHelper.BeginForm and if the form's method isn't GET.
It will generate input element for your form similar to this:
<input name="__RequestVerificationToken" type="hidden"
value="CfDJ8HSQ_cdnkvBPo-jales205VCq9ISkg9BilG0VXAiNm3Fl5Lyu_JGpQDA4_CLNvty28w43AL8zjeR86fNALdsR3queTfAogif9ut-Zd-fwo8SAYuT0wmZ5eZUYClvpLfYm4LLIVy6VllbD54UxJ8W6FA">
And when user submits form this token is verified on server side if validation is enabled.
[ValidateAntiForgeryToken]
attribute can be used against actions. Requests made to actions that have this filter applied are blocked unless the request includes a valid antiforgery token.
[AutoValidateAntiforgeryToken]
attribute can be used against controllers. This attribute works identically to the ValidateAntiForgeryToken attribute, except that it doesn't require tokens for requests made using the following HTTP methods:
GET HEAD OPTIONS TRACE
Additional information: docs.microsoft.com/aspnet/core/security/anti-request-forgery
The error you receive is from another method than the one you show here. It's a method that takes a parameter with the name "source". In your Visual Studio Options dialog, disable "Just my code", disable "Step over properties and operators" and enable "Enable .NET Framework source stepping". Make sure the .NET symbols can be found. Then the debugger will break inside the .NET method if it isn't your own. then check the stacktrace to find which value is passed that's null, but shouldn't.
What you should look for is a value that becomes null
and prevent that. From looking at your code, it may be the itemsal.Add
line that breaks.
Since you seem to have trouble with debugging in general and LINQ especially, let's try to help you out step by step (also note the expanded first section above if you still want to try it the classic way, I wasn't complete the first time around):
null
with something deliberately not null
;First make the code a bit more readable by splitting it in manageable pieces:
// in your using-section, add this:
using Roundsman.BAL;
// keep this in your normal location
var nCounts = from sale in sal
select new
{
SaleID = sale.OrderID,
LineItem = GetLineItem(sale.LineItems)
};
foreach (var item in nCounts)
{
foreach (var itmss in item.LineItem)
{
itemsal.Add(CreateWeeklyStockList(itmss));
}
}
// add this as method somewhere
WeeklyStockList CreateWeeklyStockList(LineItem lineItem)
{
string name = itmss.Item.Name.ToString(); // isn't Name already a string?
string code = itmss.Item.Code.ToString(); // isn't Code already a string?
string description = itmss.Item.Description.ToString(); // isn't Description already a string?
int quantity = Convert.ToInt32(itmss.Item.Quantity); // wouldn't (int) or "as int" be enough?
return new WeeklyStockList(
name,
code,
description,
quantity,
2, 2, 2, 2, 2, 2, 2, 2, 2
);
}
// also add this as a method
LineItem GetLineItem(IEnumerable<LineItem> lineItems)
{
// add a null-check
if(lineItems == null)
throw new ArgumentNullException("lineItems", "Argument cannot be null!");
// your original code
from sli in lineItems
group sli by sli.Item into ItemGroup
select new
{
Item = ItemGroup.Key,
Weeks = ItemGroup.Select(s => s.Week)
}
}
The code above is from the top of my head, of course, because I cannot know what type of classes you have and thus cannot test the code before posting. Nevertheless, if you edit it until it is correct (if it isn't so out of the box), then you already stand a large chance the actual error becomes a lot clearer. If not, you should at the very least see a different stacktrace this time (which we still eagerly await!).
The next step is to meticulously replace each part that can result in a null reference exception. By that I mean that you replace this:
select new
{
SaleID = sale.OrderID,
LineItem = GetLineItem(sale.LineItems)
};
with something like this:
select new
{
SaleID = 123,
LineItem = GetLineItem(new LineItem(/*ctor params for empty lineitem here*/))
};
This will create rubbish output, but will narrow the problem down even further to your potential offending line. Do the same as above for other places in the LINQ statements that can end up null
(just about everything).
This step you'll have to do yourself. But if LINQ fails and gives you such headaches and such unreadable or hard-to-debug code, consider what would happen with the next problem you encounter? And what if it fails on a live environment and you have to solve it under time pressure=
The moral: it's always good to learn new techniques, but sometimes it's even better to grab back to something that's clear and understandable. Nothing against LINQ, I love it, but in this particular case, let it rest, fix it with a simple loop and revisit it in half a year or so.
Actually, nothing to conclude. I went a bit further then I'd normally go with the long-extended answer. I just hope it helps you tackling the problem better and gives you some tools understand how you can narrow down hard-to-debug situations, even without advanced debugging techniques (which we haven't discussed).
In order to set the color of highlighted item you need to set the color of cell.SelectionStyle
in iOS.
This example is to set the color of tapped item to transparent.
If you want you can change it with other colors from UITableViewCellSelectionStyle
. This is to be written in the platform project of iOS by creating a new Custom ListView renderer in your Forms project.
public class CustomListViewRenderer : ListViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control == null)
{
return;
}
if (e.PropertyName == "ItemsSource")
{
foreach (var cell in Control.VisibleCells)
{
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
}
}
}
}
For android you can add this style in your values/styles.xml
<style name="ListViewStyle.Light" parent="android:style/Widget.ListView">
<item name="android:listSelector">@android:color/transparent</item>
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
yo can extend your JS with a select method like this
Array.prototype.select = function(closure){
for(var n = 0; n < this.length; n++) {
if(closure(this[n])){
return this[n];
}
}
return null;
};
now you can use this:
var x = [1,2,3,4];
var a = x.select(function(v) {
return v == 2;
});
console.log(a);
or for objects in a array
var x = [{id: 1, a: true},
{id: 2, a: true},
{id: 3, a: true},
{id: 4, a: true}];
var a = x.select(function(obj) {
return obj.id = 2;
});
console.log(a);
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
How About this..
string str = "The quick brown fox jumps over the lazy dog,";
StringBuilder sb = new StringBuilder(str);
sb.Remove(str.Length - 1, 1);
simply I think you are missing a single quote in your code
if ((hr==20)) document.write("Good Night"); document.getElementById('Night"here").style.display=''
it should be like this
if ((hr==20)) document.write("Good Night"); document.getElementById('Night').style.display=''
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
MD5, AES, no padding
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import static org.apache.commons.io.Charsets.UTF_8;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class PasswordUtils {
private PasswordUtils() {}
public static String encrypt(String text, String pass) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(text.getBytes(UTF_8));
byte[] encoded = Base64.getEncoder().encode(encrypted);
return new String(encoded, UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Cannot encrypt", e);
}
}
public static String decrypt(String text, String pass) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(DECRYPT_MODE, key);
byte[] decoded = Base64.getDecoder().decode(text.getBytes(UTF_8));
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, UTF_8);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
throw new RuntimeException("Cannot decrypt", e);
}
}
}
I have made a method which is much more general :
so :
DECLARE @a NVARCHAR(MAX)='images/test.jpg';
--Touch here
DECLARE @keysValueToSearch NVARCHAR(4000) = '/'
DECLARE @untilThisCharAppears NVARCHAR(4000) = '.'
DECLARE @keysValueToSearchPattern NVARCHAR(4000) = '%' + @keysValueToSearch + '%'
--Nothing to touch here
SELECT SUBSTRING(
@a,
PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch),
CHARINDEX(
@untilThisCharAppears,
@a,
PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch)
) -(PATINDEX(@keysValueToSearchPattern, @a) + LEN(@keysValueToSearch))
)
The simple way to do this is doing a div within a div
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 1_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 2_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 3_x000D_
</div>_x000D_
</div>
_x000D_
SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.
You can use git stash
. You have to specify --include-untracked
, otherwise you'll end up with the original problem.
git stash --include-untracked
Then just drop the last entry in the stash
git stash drop
You can make a handy-dandy alias for that, and call it git discard
for example:
git config --global alias.discard "! git stash -q --include-untracked && git stash drop -q"
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
I got into this situation ("Missing private key.") after Xcode failed to create new distribution certificate - an unknown error occurred.
Then, I struggled to obtain the private key or to generate new certificate. From the certificate manager in Xcode I got strange errors like "The passphrase you entered is wrong". But it did not even ask me for any passphrase.
What helped me was:
After that, Xcode was able to create new distribution certificate and no private key was missing.
Lesson learned: Restart your Mac as much as your Windows ;)
You can't "execute" a DLL. You can execute functions within the DLL, as explained in the other answers. Although .EXE files and .DLL files are essentially identical in terms of format, the distinguishing feature of an .EXE is that it contains a designated "entry point" to go and do the thing the EXE was created to do. DLLs actually have something similar, but the purpose of the "dll main" is just to perform initialization and not fulfill the primary purpose of the DLL; that is for the (presumably) various other functions it contains.
You can execute any of the functions exported by a DLL, assuming you know which one you want to execute; an EXE may contain a whole lot of functions, but one and only one is specially designated to be executed simply by "running" it.
This worked for me:
Give selected
attribute to all options like this
$('#countries option').attr('selected', 'selected');
Usage:
$('#select_all').click( function() {
$('#countries option').attr('selected', 'selected');
});
In case you are using 1.6+, better option would be to use .prop()
instead of .attr()
$('#select_all').click( function() {
$('#countries option').prop('selected', true);
});
You have a few options using programs along with grep
. The simplest in my opinion is to use head
:
head -n10 filename | grep ...
head
will output the first 10 lines (using the -n
option), and then you can pipe that output to grep
.
The thread will block, but the process is still alive.
In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.
Try this:
package my_default;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook();
// Get first/desired sheet from the workbook
XSSFSheet sheet = createSheet(workbook, "Sheet 1", false);
// XSSFSheet sheet = workbook.getSheetAt(1);//Don't use this line
// because you get Sheet index (1) is out of range (no sheets)
//Write some information in the cells or do what you want
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c2 = row1.createCell(0);
r1c2.setCellValue("NAME");
XSSFCell r1c3 = row1.createCell(1);
r1c3.setCellValue("AGE");
//Save excel to HDD Drive
File pathToFile = new File("D:\\test.xlsx");
if (!pathToFile.exists()) {
pathToFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(pathToFile);
workbook.write(fos);
fos.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
private static XSSFSheet createSheet(XSSFWorkbook wb, String prefix, boolean isHidden) {
XSSFSheet sheet = null;
int count = 0;
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
String sName = wb.getSheetName(i);
if (sName.startsWith(prefix))
count++;
}
if (count > 0) {
sheet = wb.createSheet(prefix + count);
} else
sheet = wb.createSheet(prefix);
if (isHidden)
wb.setSheetHidden(wb.getNumberOfSheets() - 1, XSSFWorkbook.SHEET_STATE_VERY_HIDDEN);
return sheet;
}
}
You can use header files.
Good practice.
You can create a file called player.h
declare all functions that are need by other cpp files in that header file and include it when needed.
player.h
#ifndef PLAYER_H // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H
#include "stdafx.h"
#include <SFML/Graphics.hpp>
int playerSprite();
#endif
player.cpp
#include "player.h" // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"
int playerSprite(){
sf::Texture Texture;
if(!Texture.loadFromFile("player.png")){
return 1;
}
sf::Sprite Sprite;
Sprite.setTexture(Texture);
return 0;
}
main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h" //Here. Again player.h must be in the current directory. or use relative or absolute path to it.
int main()
{
// ...
int p = playerSprite();
//...
Not such a good practice but works for small projects. declare your function in main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"
int playerSprite(); // Here
int main()
{
// ...
int p = playerSprite();
//...
Try this:
import cv2
import cv
color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)
I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.
OK, first of all I'm not sure how it works when you create a div using (document.createElement('div'))
, so I might be wrong now, but wouldn't it be possible to use the :target pseudo class selector for this?
If you look at the code below, you can se I've used a link to target the div, but in your case it might be possible to target #new from the script instead and that way make the div fade in without user interaction, or am I thinking wrong?
Here's the code for my example:
HTML
<a href="#new">Click</a>
<div id="new">
Fade in ...
</div>
CSS
#new {
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
}
#new:target {
-webkit-transition: opacity 2.0s ease-in;
-moz-transition: opacity 2.0s ease-in;
-o-transition: opacity 2.0s ease-in;
opacity: 1;
}
... and here's a jsFiddle
@sebarmeli's approach is the best in my opinion, but if you only want data to persist for the life of a session then sessionStorage
is probably a better option:
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.
I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.