In WPF, you use a DispatcherTimer
.
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// code goes here
}
If the <div>
has id or name then you can use find_element_by_id
or find_element_by_name
You can also try with class name, css and xpath
find_element_by_class_name
find_element_by_css_selector
find_element_by_xpath
Moving Dylan's comment into a full-blown answer because TOO USEFUL:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock assaflavie/runlike YOUR-CONTAINER
What does it do? Runs https://github.com/lavie/runlike inside a container, gets you the complete docker run command, then removes the container for you.
There are multiple ways of achieving this.
The routerLink attribute requires you to import the routingModule into the feature module in case you lazy loaded the feature module or just import the app-routing-module if it is not automatically added to the AppModule imports array.
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
this._router.navigateByUrl(urlString).then((bool) => {}).catch()
I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.
Here is a jslint free version based on Mike Lewis':
/*jslint browser: true */
/*global jQuery */
(function () {
"use strict";
var browserNotSupported = (function () {
var div = document.createElement('DIV');
// http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
return div.getElementsByTagName('I').length > 0;
}());
if (browserNotSupported) {
jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
}
}());
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
Use .apply()
to have the same access to arguments
in function b
, like this:
function a(){
b.apply(null, arguments);
}
function b(){
alert(arguments); //arguments[0] = 1, etc
}
a(1,2,3);?
Yes, MySQL allows multiple NULLs in a column with a unique constraint.
CREATE TABLE table1 (x INT NULL UNIQUE);
INSERT table1 VALUES (1);
INSERT table1 VALUES (1); -- Duplicate entry '1' for key 'x'
INSERT table1 VALUES (NULL);
INSERT table1 VALUES (NULL);
SELECT * FROM table1;
Result:
x
NULL
NULL
1
This is not true for all databases. SQL Server 2005 and older, for example, only allows a single NULL value in a column that has a unique constraint.
removeEventListener
has the same signature as addEventListener
. All of the arguments must be exactly the same for it to remove the listener.
var onEnded = () => {};
audioNode.addEventListener('ended', onEnded, false);
this.cleanup = () => {
audioNode.removeEventListener('ended', onEnded, false);
}
And in componentWillUnmount call this.cleanup()
.
DECLARE @FDate DATETIME='05-05-2019' /*This is first date*/
GETDATE()/*This is Current date*/
SELECT (DATEDIFF(DAY,(@LastDate),GETDATE())) As DifferenceDays/*this query will return no of days between firstdate & Current date*/
Please install at ubuntu openjdk-7-jdk
sudo apt-get install openjdk-7-jdk
on Windows try find find openjdk
imgtag.group(0)
or imgtag.group()
. This returns the entire match as a string. You are not capturing anything else either.
Backup
..PLAIN
for Format USE INSERT COMMANDS
Use Column Inserts
if you want column names in your inserts.Backup
buttonYou can also use below script. it is very easy to run on terminal...
//Rename multiple files at a time
for file in FILE_NAME*
do
mv -i "${file}" "${file/FILE_NAME/RENAMED_FILE_NAME}"
done
Example:-
for file in hello*
do
mv -i "${file}" "${file/hello/JAISHREE}"
done
I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)
It should be
SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)
The same applies for g++.
This is how I do it, with a README.md file in each directory:
/data/*
!/data/README.md
!/data/input/
/data/input/*
!/data/input/README.md
!/data/output/
/data/output/*
!/data/output/README.md
Try to wrap wsdlLocation in wsdlUrls
<wsdlUrls>
<wsdlLocation>http://url</wsdlLocation>
</wsdlUrls>
lsof -wni tcp:3000
Then you should see the ruby process and you can run
kill -9 processid
you should be good to run the process now
rails s thin
running multiple processes doesn't seem like a good idea and from what i've read many people agree. I've noticed many memory leaks with rails unfortunately so I couldn't imagine having two processes running. I know with one overtime my page refreshes increasingly become slower because of the data being stored on memory.
If you are using AFNetworking library to download image and that images are using in UITableview then You can use below code in cellForRowAtIndexPath
[self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView];
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
if (image) {
if([ctrl isKindOfClass:[UIButton class]])
{
UIButton btn =(UIButton)ctrl;
[btn setBackgroundImage:image forState:UIControlStateNormal];
}
else
{
UIImageView imgView = (UIImageView)ctrl;
imgView.image = image;
}
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"No Image");
}];
[operation start];}
With React Functional way
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";
const App = () => {
const saySomething = (something) => {
console.log(something);
};
useEffect(() => {
saySomething("from useEffect");
});
const handleClick = (e) => {
saySomething("element clicked");
};
return (
<Button variant="contained" color="primary" onClick={handleClick}>
Hello World
</Button>
);
};
ReactDOM.render(<App />, document.querySelector("#app"));
When I first started working with CodeIgniter, not using GET really threw me off as well. But then I realized that you can simulate GET parameters by manipulating the URI using the built-in URI Class. It's fantastic and it makes your URLs look better.
Or if you really need GETs working you can put this into your controller:
parse_str($_SERVER['QUERY_STRING'], $_GET);
Which will put the variables back into the GET array.
You can provide a new testContext.xml in which the @Autowired
bean you define is of the type you need for your test.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
Greg Hewgill's answer is great but if you need more nodes per level you can use a list|dictionary to create them: And then use method to access them either by name or order (like id)
class node(object):
def __init__(self):
self.name=None
self.node=[]
self.otherInfo = None
self.prev=None
def nex(self,child):
"Gets a node by number"
return self.node[child]
def prev(self):
return self.prev
def goto(self,data):
"Gets the node by name"
for child in range(0,len(self.node)):
if(self.node[child].name==data):
return self.node[child]
def add(self):
node1=node()
self.node.append(node1)
node1.prev=self
return node1
Now just create a root and build it up: ex:
tree=node() #create a node
tree.name="root" #name it root
tree.otherInfo="blue" #or what ever
tree=tree.add() #add a node to the root
tree.name="node1" #name it
root
/
child1
tree=tree.add()
tree.name="grandchild1"
root
/
child1
/
grandchild1
tree=tree.prev()
tree=tree.add()
tree.name="gchild2"
root
/
child1
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.prev()
tree=tree.add()
tree=tree.name="child2"
root
/ \
child1 child2
/ \
grandchild1 gchild2
tree=tree.prev()
tree=tree.goto("child1") or tree=tree.nex(0)
tree.name="changed"
root
/ \
changed child2
/ \
grandchild1 gchild2
That should be enough for you to start figuring out how to make this work
I prefer a css only scheme based on horizontal scroll, like tabs on android. This's my solution, just wrap with a class nav-tabs-responsive:
<div class="nav-tabs-responsive">
<ul class="nav nav-tabs" role="tablist">
<li>...</li>
</ul>
</div>
And two css lines:
.nav-tabs { min-width: 600px; }
.nav-tabs-responsive { overflow: auto; }
600px is the point over you will be responsive (you can set it using bootstrap variables)
There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:
example.com/sitemap.xml
Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:
example.com/robots.txt
If you don't see it listed in the robots file head to Google and search this:
site:example.com filetype:xml
This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:
filetype:xml site:example.com inurl:sitemap
or
filetype:xml site:example.com inurl:products
If you still can't find it you can right-click > "View Source"
and do a search (aka: "control find" or Ctrl + F
) for .xml
to see if there is a reference to it in the code.
You can use lookups in Ansible in order to get the contents of a file, e.g.
user_data: "{{ lookup('file', user_data_file) }}"
Caveat: This lookup will work with local files, not remote files.
Here's a complete example from the docs:
- hosts: all
vars:
contents: "{{ lookup('file', '/etc/foo.txt') }}"
tasks:
- debug: msg="the value of foo.txt is {{ contents }}"
A small reminder, but I had my slashes the wrong way on Win10 cmd. According to python documentation the activate command is: C:\> <venv>\Scripts\activate.bat
When you're browsing directories it's e.g. cd .env/Scripts
So to create my venv I used python -m venv --copies .env
and to activate .env\Scripts\activate.bat
Use a template literal in ECMAScript 6:
var customer = { name: "Foo" }
var card = { amount: 7, product: "Bar", unitprice: 42 }
var message = `Hello ${customer.name},
want to buy ${card.amount} ${card.product} for
a total of ${card.amount * card.unitprice} bucks?`
I stumbled on this post looking to use scientific notation in my code, I used
4.95*Math.Pow(10,-10);
But afterwards I found out you can do
4.95E-10;
Just thought I would add this for anyone in a similar situation that I was in.
You can simply add this CSS to your header
<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>
next add this code in place where you want to display a glyph symbol.
<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->
Have fun.
No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.
Your input string is in ISO 8601 format, except that it lacks an offset from UTC.
Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.
String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();
As for generating string representations in other formats, search StackOverflow for "Joda format".
A quick tip that tripped me up: if you're invoking the linker as "gcc" or "g++", then using "--start-group" and "--end-group" won't pass those options through to the linker -- nor will it flag an error. It will just fail the link with undefined symbols if you had the library order wrong.
You need to write them as "-Wl,--start-group" etc. to tell GCC to pass the argument through to the linker.
The time problem has to do with the ID3 headers of the MP3 files, which is something your method isn't taking into account as the entire file is copied.
Do you have a language of choice that you want to use or doesn't it matter? That will affect what libraries are available that support the operations you want.
Assuming SQL Server:
e.g. if you class special characters as anything NOT alphanumeric:
DECLARE @MyString VARCHAR(100)
SET @MyString = 'adgkjb$'
IF (@MyString LIKE '%[^a-zA-Z0-9]%')
PRINT 'Contains "special" characters'
ELSE
PRINT 'Does not contain "special" characters'
Just add to other characters you don't class as special, inside the square brackets
In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.
I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.
i've been researching for that too but unfortunately the facebook device auth is still on experimental and they didn't give new keys (partner) to use the device auth.
You can find the working example here: http://oauth-device-demo.appspot.com/ Just look at the website source and you can have the appID that works with it.
The other one is twitter PIN oauth it's working and publicly available (i'm using it) https://dev.twitter.com/docs/auth/pin-based-authorization
Use:
SELECT x.*
FROM (SELECT fname
FROM MyTbl) x
WHERE ROWNUM = 1
If using Oracle9i+, you could look at using analytic functions like ROW_NUMBER() but they won't perform as well as ROWNUM.
FYI,
I've seen this strange behavior before in jQuery widgets. Part of the key is to put the updatepanel inside the modal. This allows the DOM of the updatepanel to "stay with" the modal (however it works with bootstrap).
Go to Eclipse folder, locate eclipse.ini file, add following entry (before -vmargs
if present):
-vm
C:\Program Files\Java\jdk1.7.0_10\bin\javaw.exe
Save file and execute eclipse.exe.
I am also facing the same issue and got the resolution after a day :
The exception is coming because System needs Geckodriver to run the Selenium test case. You can try this code under the main Method in Java
System.setProperty("webdriver.gecko.driver","path of/geckodriver.exe");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
For more information You can go to this https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver link.
Please let me know if the issue doesn't get resolved.
When looking for a large amount of key words in a document, use flashtext
from flashtext import KeywordProcessor
words = ['test', 'exam', 'quiz']
txt = 'this is a test'
kwp = KeywordProcessor()
kwp.add_keywords_from_list(words)
result = kwp.extract_keywords(txt, span_info=True)
Flashtext runs faster than regex on large list of search words.
#nav ul {
display: inline-block;
list-style-type: none;
}
It should work, I tested it in your site.
The array declaration should be:
Car[] garage = new Car[100];
You can also just assign directly:
garage[1] = new Car("Blue");
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.
EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
By trial and error, I've determined the following is required to set font size:
cex
doesn't work in hist()
. Use cex.axis
for the numbers on the axes, cex.lab
for the labels.cex
doesn't work in axis()
either. Use cex.axis
for the numbers on the axes.hist()
, you can set them using mtext()
. You can set the font size using cex
, but using a value of 1 actually sets the font to 1.5 times the default!!! You need to use cex=2/3
to get the default font size. At the very least, this is the case under R 3.0.2 for Mac OS X, using PDF output.pointsize
in pdf()
.I suppose it would be far too logical to expect R to (a) actually do what its documentation says it should do, (b) behave in an expected fashion.
This works perfectly fine for me:
AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);
I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)
You can use Java 7's Key and Certificate Management Tool keytool
to check the signature of a keystore or an APK without extracting any files.
# APK file
keytool -printcert -jarfile app.apk
# AAB file
keytool -printcert -jarfile app.aab
The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk
or AAB file app.aab
.
(Note that the -jarfile
argument was introduced in Java 7; see the documentation for more details.)
keytool -list -v -keystore release.jks
The output will reveal the aliases (entries) in the keystore file release.jks
, with the certificate fingerprints (MD5, SHA1 and SHA256).
If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.
You're able to get the current registry-url using docker info
:
...
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
...
That's also the url you may use to run your self hosted-registry:
docker run -d -p 5000:5000 --name registry -e REGISTRY_PROXY_REMOTEURL=https://index.docker.io registry:2
Grep & use it right away:
$ echo $(docker info | grep -oP "(?<=Registry: ).*")
https://index.docker.io/v1/
Once you get the command line tools loaded as described by Nikos M in his excellent answer above you will need to agree to the gcc license and if you are using ruby gems you may need to link llvm-gcc as gcc-4.2.
If you do not do these the gem install will report "You have to install development tools first." after you have already installed them.
The steps are:
sudo gcc
sudo ln -s /usr/bin/llvm-gcc /usr/bin/gcc-4.2
The gcc must be run once under sudo so Apple can update their license info, you don't need an input file, it will update the license before it checks its arguments. The link is needed so that ruby 1.9 can find the compiler when building certain gems, such as the debugger. This may be fixed in ruby 2.x, but I'll cross that bridge when I get there.
Solution works very well,
public List<String> savePerson(@RequestBody Person[] personArray)
For this signature you can pass Person
array from postman like
[
{
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}, {
"empId": "10001",
"tier": "Single",
"someting": 6,
"anything": 0,
"frequency": "Quaterly"
}
]
Don't forget to add consumes
tag:
@RequestMapping(value = "/getEmployeeList", method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public List<Employee> getEmployeeDataList(@RequestBody Employee[] employeearray) { ... }
You don't need any plugins to do this.
Just select all lines (Ctrl A) and then from the menu select Edit → Line → Reindent.
This will work if your file is saved with an extension that contains HTML like .html
or .php
.
If you do this often, you may find this key mapping useful:
{ "keys": ["ctrl+shift+r"], "command": "reindent" , "args": { "single_line": false } }
If your file is not saved (e.g. you just pasted in a snippet to a new window), you can manually set the language for indentation by selecting the menu View → Syntax → language of choice
before selecting the reindent option.
if I select the second row -
Dim jason As DataRowView
jason = dg1.SelectedItem
noteText.Text = jason.Item(0).ToString()
noteText will be 646. This is VB, but you get it.
If you want to use Java 8 streams and are allergic to while
loops, you could try this:
public static int countPattern(String references, Pattern referencePattern) {
Matcher matcher = referencePattern.matcher(references);
return Stream.iterate(0, i -> i + 1)
.filter(i -> !matcher.find())
.findFirst()
.get();
}
Disclaimer: this only works for disjoint matches.
Example:
public static void main(String[] args) throws ParseException {
Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
System.out.println(countPattern("[ ]", referencePattern));
}
This prints out:
2
0
1
0
This is a solution for disjoint matches with streams:
public static int countPattern(String references, Pattern referencePattern) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<Integer>() {
Matcher matcher = referencePattern.matcher(references);
int from = 0;
@Override
public boolean hasNext() {
return matcher.find(from);
}
@Override
public Integer next() {
from = matcher.start() + 1;
return 1;
}
},
Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}
the below lines would also work
!python script.py
As of 1.3, the standard library provided multi-platform support for randoms, see this answer.
If you are working with Kotlin JavaScript and don't have access to java.util.Random
, the following will work:
fun IntRange.random() = (Math.random() * ((endInclusive + 1) - start) + start).toInt()
Used like this:
// will return an `Int` between 0 and 10 (incl.)
(0..10).random()
Note that datalist
is not the same as a select
. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.
Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.
If you want to disallow user input entirely, maybe select
would be a better choice.
To show only the text value of the option
in the dropdown, we use the inner text for it and leave out the value
attribute. The actual value that we want to send along is stored in a custom data-value
attribute:
To submit this data-value
we have to use an <input type="hidden">
. In this case we leave out the name="answer"
on the regular input and move it to the hidden copy.
<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
<option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist
and fetch its data-value
. That value is inserted into the hidden input and submitted.
document.querySelector('input[list]').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
inputValue = input.value;
hiddenInput.value = inputValue;
for(var i = 0; i < options.length; i++) {
var option = options[i];
if(option.innerText === inputValue) {
hiddenInput.value = option.getAttribute('data-value');
break;
}
}
});
The id answer
and answer-hidden
on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple input
s on the same page with one or more datalist
s providing suggestions.
Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue
to hiddenInput.value = ""
Working jsFiddle examples: plain javascript and jQuery
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
You can also use Prototype's Object.inspect() method, which "Returns the debug-oriented string representation of the object".
Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0
1st Step: add gem to your Gemfile:
gem 'rack-cors', :require => 'rack/cors'
and then save and run bundle install
2nd Step: update your config/application.rb file by adding this:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
for more details you can go to https://github.com/cyu/rack-cors Specailly if you don't use rails 5.
I think the semantics being used in your class are confusing. What's probably meant by 'static' is simply "constant size", and what's probably meant by "dynamic" is "variable size". In that case then, a constant size array might look like this:
int x[10];
and a "dynamic" one would just be any kind of structure that allows for the underlying storage to be increased or decreased at runtime. Most of the time, the std::vector
class from the C++ standard library will suffice. Use it like this:
std::vector<int> x(10); // this starts with 10 elements, but the vector can be resized.
std::vector
has operator[]
defined, so you can use it with the same semantics as an array.
You can load the images at the beginning and change the css attributes to show every image.
var images = array();
for( url in your_urls_array ){
var img = document.createElement( "img" );
//here the image attributes ( width, height, position, etc )
images.push( img );
}
function player( position )
{
images[position-1].style.display = "none" //be careful working with the first position
images[position].style.display = "block";
//reset position if needed
timer = setTimeOut( "player( position )", time );
}
Try mono:
http://www.go-mono.com/mono-downloads/download.html
This download works on all versions of Windows XP, 2003, Vista and Windows 7.
Here's an example of how to validate a int and a String that you pass from the Java Controller to the JSP file.
MainController.java:
@RequestMapping(value="/ImportJavaToJSP")
public ModelAndView getImportJavaToJSP() {
ModelAndView model2= new ModelAndView("importJavaToJSPExamples");
int someNumberValue=6;
String someStringValue="abcdefg";
//model2.addObject("someNumber", someNumberValue);
model2.addObject("someString", someStringValue);
return model2;
}
importJavaToJSPExamples.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>${someNumber}</p>
<c:if test="${not empty someNumber}">
<p>someNumber is Not Empty</p>
</c:if>
<c:if test="${empty someNumber}">
<p>someNumber is Empty</p>
</c:if>
<p>${someString}</p>
<c:if test="${not empty someString}">
<p>someString is Not Empty</p>
</c:if>
<c:if test="${empty someString}">
<p>someString is Empty</p>
</c:if>
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
Add the following lines to your ~/.bash_profile
or ~/.zshrc
file(s).
export LC_CTYPE=C
export LANG=C
I added the .ico file to my project, setting the Build Action to Embedded Resource. I specified the path to that file as the project's icon in the project settings, and then I used the code below in the form's constructor to share it. This way, I don't need to maintain a resources file anywhere with copies of the icon. All I need to do to update it is to replace the file.
var exe = System.Reflection.Assembly.GetExecutingAssembly();
var iconStream = exe.GetManifestResourceStream("Namespace.IconName.ico");
if (iconStream != null) Icon = new Icon(iconStream);
You'll have to write the SQL DML yourself explicitly. i.e.
UPDATE <table>
SET <column> = NULL;
Once it has completed you'll need to commit your updates
commit;
If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.
As your original question is pretty vague I hope this covers what you want.
??
should be preferred to ||
because it checks only for nulls and undefined.
All The expressions below are true:
(null || 'x') === 'x' ;
(undefined || 'x') === 'x' ;
//Most of the times you don't want the result below
('' || 'x') === 'x' ;
(0 || 'x') === 'x' ;
(false || 'x') === 'x' ;
//-----
//Using ?? is preferred
(null ?? 'x') === 'x' ;
(undefined ?? 'x') === 'x' ;
//?? works only for null and undefined, which is in general safer
('' ?? 'x') === '' ;
(0 ?? 'x') === 0 ;
(false ?? 'x') === false ;
Bottom line:
int j=i ?? 10;
is perfectly fine to use in javascript also. Just replace int
with let
.
Asterisk: Check browser compatibility and if you really need to support these other browsers use babel.
Another common option is when you do want multiple plots in a single window
f = figure;
hold on
plot(x1,y1)
plot(x2,y2)
...
plots multiple data sets on the same (new) figure.
Liquibase was getting this error for me. I resolved this after I debugged and watched liquibase try to load the libraries and found that it was erroring on the manifest files for commons-codec-1.6.jar. Essentially, there is either a corrupt zip file somewhere in your path or there is a incompatible version being used. When I did an explore on Maven repository for this library, I found there were newer versions and added the newer version to the pom.xml. I was able to proceed at this point.
Maybe you like my "Streamer" solution to really do it in one line:
#include <iostream>
#include <sstream>
using namespace std;
class Streamer // class for one line string generation
{
public:
Streamer& clear() // clear content
{
ss.str(""); // set to empty string
ss.clear(); // clear error flags
return *this;
}
template <typename T>
friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer
string str() // get current string
{ return ss.str();}
private:
stringstream ss;
};
template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}
Streamer streamer; // make this a global variable
class MyTestClass // just a test class
{
public:
MyTestClass() : data(0.12345){}
friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
double data;
};
ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}
int main()
{
int i=0;
string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str(); // test strings
string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str(); // test with test class
cout<<"s1: '"<<s1<<"'"<<endl;
cout<<"s2: '"<<s2<<"'"<<endl;
cout<<"s3: '"<<s3<<"'"<<endl;
}
Try this from different folder:
sudo tar -cvjSf folder.tar.bz2 folder/*
Yes. I use them for dynamically hiding/revealing the relevant part of a table, e.g. a course. Viz.
<table>
<tbody id="day1" style="display:none">
<tr><td>session1</td><tr>
<tr><td>session2</td><tr>
</tbody>
<tbody id="day2">
<tr><td>session3</td><tr>
<tr><td>session4</td><tr>
</tbody>
<tbody id="day3" style="display:none">
<tr><td>session5</td><tr>
<tr><td>session6</td><tr>
</tbody>
</table>
A button can be provided to toggle between everything or just the current day by manipulating tbodies without processing many rows individually.
This is the best way, I know of to create dynamic variables in python.
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
I found a similar, but not the same question here Creating dynamically named variables from user input
Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).
Virtual functions are declared and defined in normal class.
Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.
An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.
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.
libs and Assets folder in Android Studio:
Create libs folder inside app folder and Asset folder inside main in the project directory by exploring project directory.
Now come back to Android Studio and switch the combo box from Android to Project. enjoy...
You should put it into command line in windows.
mysqladmin -u [username] -p flush-hosts
**** [MySQL password]
or
mysqladmin flush-hosts -u [username] -p
**** [MySQL password]
For network login use the following command:
mysqladmin -h <RDS ENDPOINT URL> -P <PORT> -u <USER> -p flush-hosts
mysqladmin -h [YOUR RDS END POINT URL] -P 3306 -u [DB USER] -p flush-hosts
you can permanently solution your problem by editing my.ini file[Mysql configuration file] change variables max_connections = 10000;
or
login into MySQL using command line -
mysql -u [username] -p
**** [MySQL password]
put the below command into MySQL window
SET GLOBAL max_connect_errors=10000;
set global max_connections = 200;
check veritable using command-
show variables like "max_connections";
show variables like "max_connect_errors";
Linux Ubuntu 18:04 user here. I tried all the solutions on this board to date. Even though I read above in the accepted answer that "From later versions, there is no need to manually install gulp-util.", it was the thing that worked for me. (...maybe bc I'm on Ubuntu? I don't know. )
To recap, I kept getting the "cannot find module 'gulp-util'" error when just checking to see if gulp was installed by running:
gulp --version
...again, the 'gulp-util' error kept appearing...
So, I followed the npm install [package name] advice listed above, but ended up getting several other packages that needed to be installed as well. And one had a issue of already existing, and i wasn't sure how to replace it. ...I will put all the packages/install commands that I had to use here, just as reference in case someone else experiences this problem:
sudo npm install -g gulp-util
(then I got an error for 'pretty-hrtime' so I added that, and then the others as Error: Cannot find module ___ kept popping up after each gulp --version check. ...so I just kept installing each one.)
sudo npm install -g pretty-hrtime
sudo npm install -g chalk
sudo npm install -g semver --force
(without --force, on my system I got an error: "EEXIST: file already exists, symlink". --force is not recommended, but idk any other way. )
sudo npm install -g archy
sudo npm install -g liftoff
sudo npm install -g tildify
sudo npm install -g interpret
sudo npm install -g v8flags
sudo npm install -g minimist
And now gulp --version is finally showing: CLI version 3.9.1 Local version 3.9.1
Since Java 9.0 JDWP supports only local connections by default. http://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435
For remote debugging one should run program with *:
in address:
-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8000
I would go with Collections.emptyList()
if the returned list is not being modified in any way (as the list is immutable), otherwise I would go with option 2.
The benefit of Collections.emptyList()
is that the same static instance is returned each time and so there is not instance creation occurring for each call.
JavaScript is a scripting language and therefore stays in human readable form until it is time for it to be interpreted and executed by the JavaScript runtime.
The only way to partially hide it, at least from the less technical minds, is to obfuscate.
Obfuscation makes it harder for humans to read it, but not impossible for the technically savvy.
If you don't care about IE =6, you could use pure CSS ...
.forum:hover { background-color: #380606; }
.forum { color: white; }_x000D_
.forum:hover { background-color: #380606 !important; }_x000D_
/* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */_x000D_
_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
With jQuery, usually it is better to create a specific class for this style:
.forum_hover { background-color: #380606; }
and then apply the class on mouseover, and remove it on mouseout.
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});
$(document).ready(function(){_x000D_
$('.forum').hover(function(){$(this).toggleClass('forum_hover');});_x000D_
});
_x000D_
.forum_hover { background-color: #380606 !important; }_x000D_
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
If you must not modify the class, you could save the original background color in .data()
:
$('.forum').data('bgcolor', '#380606').hover(function(){
var $this = $(this);
var newBgc = $this.data('bgcolor');
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
});
$(document).ready(function(){_x000D_
$('.forum').data('bgcolor', '#380606').hover(function(){_x000D_
var $this = $(this);_x000D_
var newBgc = $this.data('bgcolor');_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);_x000D_
});_x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
or
$('.forum').hover(
function(){
var $this = $(this);
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
},
function(){
var $this = $(this);
$this.css('background-color', $this.data('bgcolor'));
}
);
$(document).ready(function(){_x000D_
$('.forum').hover(_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');_x000D_
},_x000D_
function(){_x000D_
var $this = $(this);_x000D_
$this.css('background-color', $this.data('bgcolor'));_x000D_
}_x000D_
); _x000D_
});
_x000D_
.forum { color: white; }_x000D_
#blue { background-color: blue; }
_x000D_
<meta charset=utf-8>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p class="forum" style="background-color:red;">Red</p>_x000D_
<p class="forum" style="background:green;">Green</p>_x000D_
<p class="forum" id="blue">Blue</p>
_x000D_
You can, if uploading an entire folder is an option for you
<input type="file" webkitdirectory directory multiple/>
change event will contain:
.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
start_time = time.time()
# your code
elapsed_time = time.time() - start_time
You can also write simple decorator to simplify measurement of execution time of various functions:
import time
from functools import wraps
PROF_DATA = {}
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = time.time() - start_time
if fn.__name__ not in PROF_DATA:
PROF_DATA[fn.__name__] = [0, []]
PROF_DATA[fn.__name__][0] += 1
PROF_DATA[fn.__name__][1].append(elapsed_time)
return ret
return with_profiling
def print_prof_data():
for fname, data in PROF_DATA.items():
max_time = max(data[1])
avg_time = sum(data[1]) / len(data[1])
print "Function %s called %d times. " % (fname, data[0]),
print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)
def clear_prof_data():
global PROF_DATA
PROF_DATA = {}
Usage:
@profile
def your_function(...):
...
You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():
A matrix is actually an array of arrays.
int rows = ..., cols = ...;
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
Of course, to delete the matrix, you should do the following:
for (int i = 0; i < rows; ++i)
delete [] matrix[i];
delete [] matrix;
I have just figured out another possibility:
int rows = ..., cols = ...;
int** matrix = new int*[rows];
if (rows)
{
matrix[0] = new int[rows * cols];
for (int i = 1; i < rows; ++i)
matrix[i] = matrix[0] + i * cols;
}
Freeing this array is easier:
if (rows) delete [] matrix[0];
delete [] matrix;
This solution has the advantage of allocating a single big block of memory for all the elements, instead of several little chunks. The first solution I posted is a better example of the arrays of arrays concept, though.
I Created this module to help make this process piece of cake
You can do things like:
$routeProvider
.state('secret',
{
...
permissions: {
only: ['admin', 'god']
}
});
Or also
$routeProvider
.state('userpanel',
{
...
permissions: {
except: ['not-logged-in']
}
});
It's brand new but worth checking out!
The javadoc for File.delete()
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.
So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.
Changing these line
for(String filePath : folderList) {
File tempFile = new File(filePath);
tempFile.delete();
}
to this
for(int i = folderList.size()-1;i>=0;i--) {
File tempFile = new File(folderList.get(i));
tempFile.delete();
}
should cause your code to delete the sub folders first.
The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.
I was looking for a different answer for the question title, so maybe other people will be too.
To set type as an ObjectId (so you may reference author
as the author of book
, for example), you may do like:
const Book = mongoose.model('Book', {
author: {
type: mongoose.Schema.Types.ObjectId, // here you set the author ID
// from the Author colection,
// so you can reference it
required: true
},
title: {
type: String,
required: true
}
});
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
I started with node-csvtojson, but it brought too many dependencies for my linking.
Building on your question and the answer by brnd, I used node-csv and underscore.js.
var attribs;
var json:
csv()
.from.string(csvString)
.transform(function(row) {
if (!attribs) {
attribs = row;
return null;
}
return row;
})
.to.array(function(rows) {
json = _.map(rows, function(row) {
return _.object(attribs, row);
});
});
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';
const methods = {
componentDidMount(props) {
console.log('I mounted! Here are my props: ', props);
}
};
const Channels = props => (
<h1>Hello</h1>
)
export default lifecycle(methods)(Channels);
To stop the Media Player without the risk of an Illegal State Exception, you must do
try {
mp.reset();
mp.prepare();
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
rather than just
try {
mp.stop();
mp.release();
mp=null;
}
catch (Exception e)
{
e.printStackTrace();
}
I believe it would be like this
takedata.match(/(\[.+\])/g);
the g
at the end means global, so it doesn't stop at the first match.
There are differences with some exceptions, e.g. KeyboardInterrupt.
Reading PEP8:
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).
Pickle is best for these cases. Suppose you have a ndarray named x_train
. You can dump it into a file and revert it back using the following command:
import pickle
###Load into file
with open("myfile.pkl","wb") as f:
pickle.dump(x_train,f)
###Extract from file
with open("myfile.pkl","rb") as f:
x_temp = pickle.load(f)
One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:
These are just a few of the problems faced.
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
Use the built-in function dir()
.
Updating gradle/wrapper/gradle-wrapper.properties
with the following version fixed it for me:
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
i think the easiest way is to use the Adobe PDF reader COM Component
i hope this helps
When running python (cpython) on windows the <built-in function system>
os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.
On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.
That said, an important piece of advice comes from os.system docs, which says:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
You can use GeometryReader in a handy extension to fill the parent
extension View {
func fillParent(alignment:Alignment = .center) -> some View {
return GeometryReader { geometry in
self
.frame(width: geometry.size.width,
height: geometry.size.height,
alignment: alignment)
}
}
}
so using the requested example, you get
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
}
.fillParent(alignment:.topLeading)
.background(Color.red)
}
}
(note the spacer is no longer needed)
For Swift use this...
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "ImageName.png")?.draw(in: self.view.bounds)
if let image = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
}else{
UIGraphicsEndImageContext()
debugPrint("Image not available")
}
Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.
Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.
var updater = {};
function geoCodeCity(goocoord) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': goocoord
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
updater.currentLocation = results[1].formatted_address;
} else {
if (status == "ERROR") {
console.log(status);
}
}
});
};
Try to use this free way to this, https://freenetexcel.codeplex.com
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
//Initialize worksheet
Worksheet sheet = workbook.Worksheets[0];
DataTable dataTable = sheet.ExportDataTable();
Cygwin mount
now support bind method which lets you mount a directory. Hence you can simply add the following line to /etc/fstab
, then restart your shell:
c:/Users /home none bind 0 0
With n
being the line number:
ng
: Jump to line number n. Default is the start of the file.nG
: Jump to line number n. Default is the end of the file.So to go to line number 320123, you would type 320123g
.
Copy-pasted straight from Wikipedia.
Finally found this method:
basename($_SERVER['REQUEST_URI']);
This will return all URLs with page name. (e.g.: index.php?id=1&name=rr&class=10
).
isset
will return true even if the variable is "". isset
returns false only if a variable is null. What you should be doing:
if (!empty($web)) {
// foo
}
This will check that he variable is not empty.
Hope this helps
Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:
private DataTable LoadExcelData(string fileName)
{
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);
myCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
return dt;
}
You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
I've always heard them used in the opposite sense:
&
is the reference operator -- it gives you a reference (pointer) to some object
*
is the dereference operator -- it takes a reference (pointer) and gives you back the referred to object;
min(df['some_property'])
max(df['some_property'])
The built-in functions work well with Pandas Dataframes.
I have same issue, i used simple solution
1)create sliding_out_right.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-50%p"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
2) create sliding_in_left.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="50%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
3) simply using fragment transaction setCustomeAnimations() with two custom xml and two default xml for animation as follows :-
fragmentTransaction.setCustomAnimations(R.anim.sliding_in_left, R.anim.sliding_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right );
MSSQL does not support BEFORE
triggers. The closest you have is INSTEAD OF
triggers but their behavior is different to that of BEFORE
triggers in MySQL.
You can learn more about them here, and note that INSTEAD OF
triggers "Specifies that the trigger is executed instead of the triggering SQL statement, thus overriding the actions of the triggering statements." Thus, actions on the update may not take place if the trigger is not properly written/handled. Cascading actions are also affected.
You may instead want to use a different approach to what you are trying to achieve.
hi i have a code to save the contact in your database by shared preference here is my code
public class Main22Activity extends AppCompatActivity {
EditText nameInput,phoneInput;
TextView LargeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main22);
nameInput = (EditText) findViewById(R.id.nameInput);
phoneInput = (EditText) findViewById(R.id.phoneInput);
LargeText = (TextView) findViewById(R.id.textView2);
}
public void saveInfo (View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
SharedPreferences.Editor editor= sharedPref.edit();
editor.putString("name", nameInput.getText().toString());
editor.putString("phone", phoneInput.getText().toString());
editor.apply();
Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();
}
public void displayData(View view){
SharedPreferences sharedPref = getSharedPreferences("nameInfo" , Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
String ph = sharedPref.getString ("phone","");
LargeText.setText(name + " " + ph);
}
}
Escape sequence \R
matches a generic newline
that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by
\v
(vertical whitespace), and the multi character sequence\x0D\x0A
...
$string = preg_replace('/\R+/', " ", $string);
In 8-bit non-UTF-8 mode
\R
is equivalent to the following:(?>\r\n|\n|\x0b|\f|\r|\x85)
... pcre.org
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
The heap part gets worse, my friends. UTF-16 isn't guaranteed to be limited to 16 bits and can expand to 32
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
<FilesMatch "\.(js|css)$">
ExpiresActive On
ExpiresDefault A1
Header append Cache-Control must-revalidate
</FilesMatch>
Extra instructions when following @Luke-West's + @Vaiden's solutions:
Also, I did not have to use step 3 of @Vaiden's solution. Just running rm -rf Pods/
in terminal got rid of all old pod files
I also did not have to use step 9 in @Vaiden's solution, instead I just removed the OLD project named framework under Link Binary Libraries (the NEWLY named framework was already there)
So the updated steps would be as follows:
Step 1 - Rename the project
Step 2 - Rename the Scheme
Step 3 - Rename the folder with your assets
Step 4 - Rename the Build plist data
Step 5 Handling Podfile
pod deintegrate
You should be able to build with no errors after you have followed all of the steps successfully
To only get those errors that cause the application to stop working, use:
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING | E_DEPRECATED));
This will stop showing notices, warnings, and deprecated errors.
You can use simple trick which is import flask app variable from main inside another file, like:
test-routes.py
from __main__ import app
@app.route('/test', methods=['GET'])
def test():
return 'it works!'
and in your main files, where you declared flask app, import test-routes, like:
app.py
from flask import Flask, request, abort
app = Flask(__name__)
# import declared routes
import test-routes
It works from my side.
According to TypeScript documentation, we can do this via Enum with static functions.
Get Enum Name with static functions
enum myEnum {
entry1,
entry2
}
namespace myEnum {
export function GetmyEnumName(m: myEnum) {
return myEnum[m];
}
}
now we can call it like below
myEnum.GetmyEnumName(myEnum.entry1);
// result entry1
for reading more about Enum with static function follow the below link https://basarat.gitbooks.io/typescript/docs/enums.html
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$text = "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded = multiexplode(array(",",".","|",":"),$text);
print_r($exploded);
//And output will be like this:
// Array
// (
// [0] => here is a sample
// [1] => this text
// [2] => and this will be exploded
// [3] => this also
// [4] => this one too
// [5] => )
// )
Source: php@metehanarslan at php.net
Here is the cleanest way to do this:
<p ng-show="{{foo === undefined}}">Show this if $scope.foo === undefined</p>
No need to create a helper function in the controller!
Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
(For future reference.)
Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).
Memory Mapped files are supported in managed code in .NET 4.0.
But as noted, you need to profile, and expect to switch to native code for maximum performance.
Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.
The :nth-child
CSS3 selector is in fact more capable than you ever imagined!
For example, this will select the last 2 elements of #container
:
#container :nth-last-child(-n+2) {}
But this is just the beginning of a beautiful friendship.
#container :nth-last-child(-n+2) {
background-color: cyan;
}
_x000D_
<div id="container">
<div>a</div>
<div>b</div>
<div>SELECT THIS</div>
<div>SELECT THIS</div>
</div>
_x000D_
These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo.
To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.
Prophylactic measures to prevent you getting the error again
The best way to avoid syntactic errors is to write stylish code. That way, when you mistype things, the problem will be easier to spot. There are many R style guides linked from the SO R tag info page. You can also use the formatR
package to automatically format your code into something more readable. In RStudio, the keyboard shortcut CTRL + SHIFT + A will reformat your code.
Consider using an IDE or text editor that highlights matching parentheses and braces, and shows strings and numbers in different colours.
Common syntactic mistakes that generate these errors
Mismatched parentheses, braces or brackets
If you have nested parentheses, braces or brackets it is very easy to close them one too many or too few times.
{}}
## Error: unexpected '}' in "{}}"
{{}} # OK
Missing *
when doing multiplication
This is a common mistake by mathematicians.
5x
Error: unexpected symbol in "5x"
5*x # OK
Not wrapping if, for, or return values in parentheses
This is a common mistake by MATLAB users. In R, if
, for
, return
, etc., are functions, so you need to wrap their contents in parentheses.
if x > 0 {}
## Error: unexpected symbol in "if x"
if(x > 0) {} # OK
Not using multiple lines for code
Trying to write multiple expressions on a single line, without separating them by semicolons causes R to fail, as well as making your code harder to read.
x + 2 y * 3
## Error: unexpected symbol in "x + 2 y"
x + 2; y * 3 # OK
else
starting on a new line
In an if
-else
statement, the keyword else
must appear on the same line as the end of the if
block.
if(TRUE) 1
else 2
## Error: unexpected 'else' in "else"
if(TRUE) 1 else 2 # OK
if(TRUE)
{
1
} else # also OK
{
2
}
=
instead of ==
=
is used for assignment and giving values to function arguments. ==
tests two values for equality.
if(x = 0) {}
## Error: unexpected '=' in "if(x ="
if(x == 0) {} # OK
Missing commas between arguments
When calling a function, each argument must be separated by a comma.
c(1 2)
## Error: unexpected numeric constant in "c(1 2"
c(1, 2) # OK
Not quoting file paths
File paths are just strings. They need to be wrapped in double or single quotes.
path.expand(~)
## Error: unexpected ')' in "path.expand(~)"
path.expand("~") # OK
Quotes inside strings
This is a common problem when trying to pass quoted values to the shell via system
, or creating quoted xPath
or sql
queries.
Double quotes inside a double quoted string need to be escaped. Likewise, single quotes inside a single quoted string need to be escaped. Alternatively, you can use single quotes inside a double quoted string without escaping, and vice versa.
"x"y"
## Error: unexpected symbol in ""x"y"
"x\"y" # OK
'x"y' # OK
Using curly quotes
So-called "smart" quotes are not so smart for R programming.
path.expand(“~”)
## Error: unexpected input in "path.expand(“"
path.expand("~") # OK
Using non-standard variable names without backquotes
?make.names
describes what constitutes a valid variable name. If you create a non-valid variable name (using assign
, perhaps), then you need to access it with backquotes,
assign("x y", 0)
x y
## Error: unexpected symbol in "x y"
`x y` # OK
This also applies to column names in data frames created with check.names = FALSE
.
dfr <- data.frame("x y" = 1:5, check.names = FALSE)
dfr$x y
## Error: unexpected symbol in "dfr$x y"
dfr[,"x y"] # OK
dfr$`x y` # also OK
It also applies when passing operators and other special values to functions. For example, looking up help on %in%
.
?%in%
## Error: unexpected SPECIAL in "?%in%"
?`%in%` # OK
Sourcing non-R code
The source
function runs R code from a file. It will break if you try to use it to read in your data. Probably you want read.table
.
source(textConnection("x y"))
## Error in source(textConnection("x y")) :
## textConnection("x y"):1:3: unexpected symbol
## 1: x y
## ^
Corrupted RStudio desktop file
RStudio users have reported erroneous source errors due to a corrupted .rstudio-desktop
file. These reports only occurred around March 2014, so it is possibly an issue with a specific version of the IDE. RStudio can be reset using the instructions on the support page.
Using expression without paste in mathematical plot annotations
When trying to create mathematical labels or titles in plots, the expression created must be a syntactically valid mathematical expression as described on the ?plotmath
page. Otherwise the contents should be contained inside a call to paste.
plot(rnorm(10), ylab = expression(alpha ^ *)))
## Error: unexpected '*' in "plot(rnorm(10), ylab = expression(alpha ^ *"
plot(rnorm(10), ylab = expression(paste(alpha ^ phantom(0), "*"))) # OK
In xml add
<ListView android:longClickable="true">
In java file
lv.setLongClickable(true)
try this setOnItemLongClickListener()
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
//final String category = "Position at : "+pos;
final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
args = new Bundle();
args.putString("category", category);
return false;
}
});
Apart from price and features, the throughput also varies greatly (as mentioned by user1677120):
Taken from EBS docs:
| EBS volume | Throughput | Throughput |
| type | MiB/s | dependent on.. |
|------------|------------|-------------------------------|
| gp2 (SSD) | 128-160 | volume size |
| io1 (SSD) | 0.25-500 | IOPS (256Kib/s per IOPS) |
| st1 (HDD) | 20-500 | volume size (40Mib/s per TiB) |
| sc1 (HDD) | 6-250 | volume size (12Mib/s per TiB) |
Note, that for io1, st1 and sc1 you can burst throughput traffic to at least 125Mib/s, but to 500Mib/s, depending on volume size.
You can further increase throughput by e.g. deploying EBS volumes as RAID0
Taken from EFS docs
| Filesystem | Base | Burst |
| Size | Throughput | Throughput |
| GiB | MiB/s | MiB/s |
|------------|------------|------------|
| 10 | 0.5 | 100 |
| 256 | 12.5 | 100 |
| 512 | 25.0 | 100 |
| 1024 | 50.0 | 100 |
| 1536 | 75.0 | 150 |
| 2048 | 100.0 | 200 |
| 3072 | 150.0 | 300 |
| 4096 | 200.0 | 400 |
The base throughput is guaranteed, burst throughput uses up credits you gathered while being below the base throughput (so you'll only have this for a limited time, see here for more details.
S3 is a total different thing, so it cannot really be compared to EBS and EFS. Plus: There are no published throughput metrics for S3. You can improve throughput by downloading in parallel (I somewhere read AWS states you would have basically unlimited throughput this way), or adding CloudFront to the mix
One issue with your ContentLoader is that internally it operates sequentially. A better pattern is to parallelize the work and then sychronize at the end, so we get
public class PageViewModel : IHandle<SomeMessage>
{
...
public async void Handle(SomeMessage message)
{
ShowLoadingAnimation();
// makes UI very laggy, but still not dead
await this.contentLoader.LoadContentAsync();
HideLoadingAnimation();
}
}
public class ContentLoader
{
public async Task LoadContentAsync()
{
var tasks = new List<Task>();
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoIoBoundWorkAsync());
tasks.Add(DoCpuBoundWorkAsync());
tasks.Add(DoSomeOtherWorkAsync());
await Task.WhenAll(tasks).ConfigureAwait(false);
}
}
Obviously, this doesn't work if any of the tasks require data from other earlier tasks, but should give you better overall throughput for most scenarios.
It's just common stuff for making cin input work faster.
For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.
The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).
You can Use sender argument
@IBAction func TickToeButtonClick(sender: AnyObject) {
sender.setTitle("my text here", forState: .normal)
}
Pseudo code, something like:
CASE
When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'
This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
int x = 10;
Thread t1 =new Thread(new ParameterizedThreadStart(order1));
t1.IsBackground = true;//i can stope
t1.Start(x);
Thread t2=new Thread(order2);
t2.Priority = ThreadPriority.Highest;
t2.Start();
Console.ReadKey();
}//Main
static void order1(object args)
{
int x = (int)args;
for (int i = 0; i < x; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(i.ToString() + " ");
}
}
static void order2()
{
for (int i = 100; i > 0; i--)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(i.ToString() + " ");
}
}`enter code here`
}
}
Actually, there is no need to restore the database in native SQL Server terms, since you "want to fiddle with some data" and "browse through the data of that .bak file"
You can use ApexSQL Restore – a SQL Server tool that attaches both native and natively compressed SQL database backups and transaction log backups as live databases, accessible via SQL Server Management Studio, Visual Studio or any other third-party tool. It allows attaching single or multiple full, differential and transaction log backups
Moreover, I think that you can do the job while the tool is in fully functional trial mode (14 days)
Disclaimer: I work as a Product Support Engineer at ApexSQL
Here is how to get rid of the top section header in a grouped UITableView, in Swift:
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
you can create batch file and insert into it the bellow line:
cmd /k start chrome "http://yourWebSite.com
after that you do just double click on this batch file.
TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free
The + operator can work between a string and a string, char, integer, double or float data type value. It just converts the value to its string representation before concatenation.
The concat operator can only be done on and with strings. It checks for data type compatibility and throws an error, if they don't match.
Except this, the code you provided does the same stuff.
Check out DecimalFormat: http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
You'll do something like:
new DecimalFormat("$#.00").format(shippingCost);
Or since you're working with currency, you could see how NumberFormat.getCurrencyInstance()
works for you.
Linux Users:
cp -r Android AndroidUnity
cd AndroidUnity/Sdk
rm -rf tools
wget http://dl-ssl.google.com/android/repository/tools_r25.2.5-windows.zip
unzip tools_r25.2.5-windows.zip
In Unity preferences change to this newly created sdk folder.
It's been a while, but leaving a note for others. I achieved what is needed with an attribute and I decorated my model class fields with that attribute as I want.
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
Got the help of these 2 articles:
What I did:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
public string DefaultValue { get; set; }
}
modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
private void SetAnnotatedColumn(ColumnModel col)
{
AnnotationValues values;
if (col.Annotations.TryGetValue("SqlDefaultValue", out values))
{
col.DefaultValueSql = (string)values.NewValue;
}
}
Then in the Migration Configuration constructor, register the custom SQL generator.
SetSqlGenerator("System.Data.SqlClient", new CustomMigrationSqlGenerator());
This works in webpack 3:
in the webpack.config.babel.js file:
resolve: {
alias: {
jquery: "jquery/src/jquery"
},
....
}
And use ProvidePlugin
new webpack.ProvidePlugin({
'$': 'jquery',
'jQuery': 'jquery',
})
__get
, __set
, __call
and __callStatic
are invoked when the method or property is inaccessible. Your $bar
is public and therefor not inaccessible.
See the section on Property Overloading in the manual:
__set()
is run when writing data to inaccessible properties.__get()
is utilized for reading data from inaccessible properties.
The magic methods are not substitutes for getters and setters. They just allow you to handle method calls or property access that would otherwise result in an error. As such, there are much more related to error handling. Also note that they are considerably slower than using proper getter and setter or direct method calls.
For Atlassian Connect Apps, use
AP.navigator.reload();
See details here
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
@ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
You want to enclose it with a scrollView
.
The solution is not good, even you fixed your naming and unreachable statement of that print out.
things you should pay attention also 1. randomness seed, and large data, will num of item is so big returned num of that random < itemlist.size().
You can right click on your project, then choose Properties
, on Debug
tab you should uncheck launch browser
checkbox.
CDATA is necessary in any XML dialect, because text within an XML node is treated as a child element before being evaluated as JavaScript. This is also the reason why JSLint complains about the <
character in regexes.
References
Answer has been updated
count
is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:
$wordCount = count($wordlist);
If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count
method. Example:
$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();
There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478
However as of now, the query builder always returns an array.
Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:
$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
$wordCount = $wordlist->count();
However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:
// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->count();
// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();
Below is the best all-around solution I could build to vertically and horizontally center a fixed-width, flexible height content box. It was tested and working for recent versions of Firefox, Opera, Chrome, and Safari.
.outer {_x000D_
display: table;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.middle {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
width: 400px;_x000D_
/*whatever width you want*/_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="middle">_x000D_
<div class="inner">_x000D_
<h1>The Content</h1>_x000D_
<p>Once upon a midnight dreary...</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
View A Working Example With Dynamic Content
I built in some dynamic content to test the flexibility and would love to know if anyone sees any problems with it. It should work well for centered overlays also -- lightbox, pop-up, etc.
To make an Image fill its parent, simply wrap it into a FittedBox
:
FittedBox(
child: Image.asset('foo.png'),
fit: BoxFit.fill,
)
FittedBox
here will stretch the image to fill the space.
(Note that this functionality used to be provided by BoxFit.fill
, but the API has meanwhile changed such that BoxFit
no longer provides this functionality. FittedBox
should work as a drop-in replacement, no changes need to be made to the constructor arguments.)
Alternatively, for complex decorations you can use a Container
instead of an Image
– and use decoration
/foregroundDecoration
fields.
To make the Container
will its parent, it should either:
alignment
property not null
Here's an example that combines two images and a Text
in a single Container
, while taking 100% width/height of its parent:
Container(
foregroundDecoration: const BoxDecoration(
image: DecorationImage(
image: NetworkImage(
'https://p6.storage.canalblog.com/69/50/922142/85510911_o.png'),
fit: BoxFit.fill),
),
decoration: const BoxDecoration(
image: DecorationImage(
alignment: Alignment(-.2, 0),
image: NetworkImage(
'http://www.naturerights.com/blog/wp-content/uploads/2017/12/Taranaki-NR-post-1170x550.png'),
fit: BoxFit.cover),
),
alignment: Alignment.bottomCenter,
padding: EdgeInsets.only(bottom: 20),
child: Text(
"Hello World",
style: Theme.of(context)
.textTheme
.display1
.copyWith(color: Colors.white),
),
),
Yes, but be careful when using between for dates.
BETWEEN '20090101' AND '20090131'
is really interpreted as 12am, or
BETWEEN '20090101 00:00:00' AND '20090131 00:00:00'
so will miss anything that occurred during the day of Jan 31st. In this case, you will have to use:
myDate >= '20090101 00:00:00' AND myDate < '20090201 00:00:00' --CORRECT!
or
BETWEEN '20090101 00:00:00' AND '20090131 23:59:59' --WRONG! (see update!)
UPDATE: It is entirely possible to have records created within that last second of the day, with a datetime as late as 20090101 23:59:59.997
!!
For this reason, the BETWEEN (firstday) AND (lastday 23:59:59)
approach is not recommended.
Use the myDate >= (firstday) AND myDate < (Lastday+1)
approach instead.
I think it depends on the webpage execution. If the page that you want to display can not displayed properly without loading JavaScript first then you should include JavaScript file first. But If you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from an user's point of view it would seems like that page is loading faster.
https://developers.google.com/chrome-developer-tools/docs/settings
The following query will get the current datetime and convert into string. with the following format yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar(25), getdate(), 120)
I love this
$data = str_getcsv($CsvString, "\n"); //parse the rows
foreach ($data as &$row) {
$row = str_getcsv($row, "; or , or whatever you want"); //parse the items in rows
$this->debug($row);
}
in my case I am going to get a csv through web services, so in this way I don't need to create the file. But if you need to parser with a file, it's only necessary to pass as string
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
I just checked the status of the response object:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});
I ran into this issue while executing an Ansible playbook so I want to add my 2 cents here. I noticed a warning message about missing Visual Studio 14. Visual Studio version 14 was released in 2015 and the solution to my problem was installing Visual Studio 2015 Professional on the host machine of my Azure DevOps agent.
def post(self,request):
serializer = ProductSerializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
Center vertically and horizontally:
.parent{
height: 100%;
position: absolute;
width: 100%;
top: 0;
left: 0;
}
.c{
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
}
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
For copy directory use following command
cp -r source Destination
For example
cp -r /home/hasan /opt
For copy file use command without -r
cp /home/file /home/hasan/
Following things are not mentioned in the existing answers : Buffer size configuration HTTP Header and Nesting.
Buffer size configuration for ob_start :
ob_start(null, 4096); // Once the buffer size exceeds 4096 bytes, PHP automatically executes flush, ie. the buffer is emptied and sent out.
The above code improve server performance as PHP will send bigger chunks of data, for example, 4KB (wihout ob_start call, php will send each echo to the browser).
If you start buffering without the chunk size (ie. a simple ob_start()), then the page will be sent once at the end of the script.
Output buffering does not affect the HTTP headers, they are processed in different way. However, due to buffering you can send the headers even after the output was sent, because it is still in the buffer.
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Nicely explained here : https://phpfashion.com/everything-about-output-buffering-in-php
First check your imports, when you use session, transaction it should be org.hibernate
and remove @Transactinal
annotation. and most important in Entity class if you have used @GeneratedValue(strategy=GenerationType.AUTO)
or any other then at the time of model object creation/entity object creation should not create id.
final conclusion is if you want pass id filed i.e PK then remove @GeneratedValue
from entity class.
Read these tutorials Asp.net Update Panel and Introduction to the UpdatePanel Control
Simple and understandable
I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.
const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
mimeType = 'image/jpeg';
}
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const file = new File([u8arr], imgName, {type: mimeType});
My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.
Hope this helps connects the dots for others.
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
you need double quotes in all your three if
statements, eg.:
IF "%a%"=="2" (
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if "!param1!"=="" goto :param1Prompt
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
USB Write is Unlocked!
)
)
pause
simple:
Tags are expected to always point at the same version of a project, while heads are expected to advance as development progresses.
You can pipe grep
result to head
in conjunction with stdbuf.
Note, that in order to ensure stopping after Nth match, you need to using stdbuf
to make sure grep
don't buffer its output:
stdbuf -oL grep -rl 'pattern' * | head -n1
stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1
As soon as head
consumes 1 line, it terminated and grep
will receive SIGPIPE
because it still output something to pipe while head
was gone.
This assumed that no file names contain newline.
I was able to fix this in Android Studio 0.2.0 by changing API from API 18: Android 4.3 to API 17: Android 4.2.2
This is under the Android icon menu in the top right of the design window.
This was a solution from http://www.hankcs.com/program/mobiledev/idea-this-version-of-the-rendering-library-is-more-recent-than-your-version-of-intellij-idea-please-update-intellij-idea.html.This required a Google translation into English since it was in another language.
Hope it helps.
Target server must allowed cross-origin request. In order to allow it through express, simply handle http options request :
app.options('/url...', function(req, res, next){
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods', 'POST');
res.header("Access-Control-Allow-Headers", "accept, content-type");
res.header("Access-Control-Max-Age", "1728000");
return res.sendStatus(200);
});
I had exact same error but I am using Visual Studio Community 2017 Version 15.2 (26430.14) to build .Net Core projects.
I have a ASP.NET Core MVC web project and a separate security project using ASP.NET Core Identity. The web project contains connection string in aspsettings.json config file.
I also installed Bundler & Minifier and Web Essentials 2017 extensions in Visual Studio so that I can compile, minify and bundle my assets and put them to wwwroot.
I figured out it was the MSBuild those 2 extensions secretly download that caused the problem, because I had Enable Bundle on Build and Enable Compile on Build on. After I disable that, everything works fine.
Probably not the cause to your problem, but might be worthy to just give it a try.
using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
cmd.Parameters.AddWithValue("@id", index);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
}
}
}
You appear to have no main function, which is supposed to be the entry-point for your program.
(1) Your <script>
tag should be placed before the closing </body>
tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object.
What you are passing to the controller's Json method, though, is a JSON-formatted string object, so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem).
I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available.
return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here,
// or if that is done automatically
Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.
select <column list> into <table name> from <source> where <whereclause>
if you want use with expression, the rigth way is :
<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>
but the best way is using ng-class
Shared hosting no ssh or shell access?
Here is how i did it;
my solution is similar to the solution given by Server Themes. Do check it once:
localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
if (e.keyCode == 116) {
localStorage.setItem("validNavigation", true);
}
});
// Attach the event click for all links in the page
$(document).on("click", "a", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
$(document).bind("click", "button[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {
if (localStorage.getItem("validNavigation") === "false") {
event.returnValue = "Write something clever here..";
console.log("Test success!");
localStorage.setItem("validNavigation", false);
}
};
If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.
Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/
As Adrian said, the plugins are going to work the same way. There are three basic parts you're going to need:
1: Event handler for 'contextmenu'
event:
$(document).bind("contextmenu", function(event) {
event.preventDefault();
$("<div class='custom-menu'>Custom menu</div>")
.appendTo("body")
.css({top: event.pageY + "px", left: event.pageX + "px"});
});
Here, you could bind the event handler to any selector that you want to show a menu for. I've chosen the entire document.
2: Event handler for 'click'
event (to close the custom menu):
$(document).bind("click", function(event) {
$("div.custom-menu").hide();
});
3: CSS to control the position of the menu:
.custom-menu {
z-index:1000;
position: absolute;
background-color:#C0C0C0;
border: 1px solid black;
padding: 2px;
}
The important thing with the CSS is to include the z-index
and position: absolute
It wouldn't be too tough to wrap all of this in a slick jQuery plugin.
You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
Depending on your requirements, you might use a Generic class like the one below to make access easier:
import java.util.ArrayList;
class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
public void addToInnerArray(int index, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
this.get(index).add(element);
}
public void addToInnerArray(int index, int index2, T element) {
while (index >= this.size()) {
this.add(new ArrayList<T>());
}
ArrayList<T> inner = this.get(index);
while (index2 >= inner.size()) {
inner.add(null);
}
inner.set(index2, element);
}
}
Well yes, the access exception is due to the fact that document.domain
must match in your parent and your iframe, and before they do, you won't be able to programmatically set the document.domain
property of your iframe.
I think your best option here is to point the page to a template of your own:
iframe.src = '/myiframe.htm#' + document.domain;
And in myiframe.htm:
document.domain = location.hash.substring(1);
Question 1:
@IBOutlet var countDownLabel: UILabel!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
var timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
}
func update() {
if(count > 0) {
countDownLabel.text = String(count--)
}
}
Question 2:
You can do both. SpriteKit is the SDK you use for scene, motion, etc. Simple View Application is the project template. They should not conflict
For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:
#!/bin/bash
export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost
You might be interested in How to run the sftp command with a password from Bash script?