Try:
onclick="this.select()"
It works great for me.
This is my solution is use display: inline
Some text <div class="dropdown" style="display:inline">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Separated link</a></li>
</ul>
</div> is here
a
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" rel="stylesheet" />_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />Your text_x000D_
<div class="dropdown" style="display: inline">_x000D_
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">_x000D_
Dropdown_x000D_
<span class="caret"></span>_x000D_
</button>_x000D_
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
<li><a href="#">Action</a>_x000D_
</li>_x000D_
<li><a href="#">Another action</a>_x000D_
</li>_x000D_
<li><a href="#">Something else here</a>_x000D_
</li>_x000D_
<li><a href="#">Separated link</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>is here
_x000D_
You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria
That is working for me. Could be a browser issue as mentioned, or maybe jQuery isn't registered properly, or perhaps the real issue is more complicated (that you made a simpler version to ask this). PS - did have to click out of the text box to make it fire.
To get the textbox value, you can use the jQuery val()
function.
For example,
$('input:textbox').val()
– Get textbox value.
$('input:textbox').val("new text message")
– Set the textbox value.
If you want to read only one field value, I think, using the template reference variables is the easiest way
Template
<input #phone placeholder="phone number" />
<input type="button" value="Call" (click)="callPhone(phone.value)" />
**Component**
callPhone(phone): void
{
console.log(phone);
}
If you have a number of fields, using the reactive form one of the best ways.
There are some use cases suitable to UDP transport and others suitable to TCP transport.
The use case also dictates encoding settings for the video. When broadcasting soccer match focus is on quality and for video conference focus is on latency.
When using multicast to deliver video to your customers then UDP is used.
Requirement for multicast is expensive networking hardware between broadcasting server and customer. In practice this means if your company owns network infrastructure you can use UDP and multicast for live video streaming. Even then quality-of-service is also implemented to mark video packets and prioritize them so no packet loss happens.
Multicast will simplify broadcasting software because network hardware will handle distributing packets to customers. Customers subscribe to multicast channels and network will reconfigure to route packets to new subscriber. By default all channels are available to all customers and can be optimally routed.
This workflow places dificulty on authorization process. Network hardware does not differentiate subscribed users from other users. Solution to authorization is in encrypting video content and enabling decryption in player software when subscription is valid.
Unicast (TCP) workflow allows server to check client's credentials and only allow valid subscriptions. Even allow only certain number of simultaneous connections.
Multicast is not enabled over internet.
For delivering video over internet TCP must be used. When UDP is used developers end up re-implementing packet re-transmission, for eg. Bittorrent p2p live protocol.
"If you use TCP, the OS must buffer the unacknowledged segments for every client. This is undesirable, particularly in the case of live events".
This buffer must exist in some form. Same is true for jitter buffer on player side. It is called "socket buffer" and server software can know when this buffer is full and discard proper video frames for live streams. It is better to use unicast/TCP method because server software can implement proper frame dropping logic. Random missing packets in UDP case will just create bad user experience. like in this video: http://tinypic.com/r/2qn89xz/9
"IP multicast significantly reduces video bandwidth requirements for large audiences"
This is true for private networks, Multicast is not enabled over internet.
"Note that if TCP loses too many packets, the connection dies; thus, UDP gives you much more control for this application since UDP doesn't care about network transport layer drops."
UDP also doesn't care about dropping entire frames or group-of-frames so it does not give any more control over user experience.
"Usually a video stream is somewhat fault tolerant"
Encoded video is not fault tolerant. When transmitted over unreliable transport then forward error correction is added to video container. Good example is MPEG-TS container used in satellite video broadcast that carry several audio, video, EPG, etc. streams. This is necessary as satellite link is not duplex communication, meaning receiver can't request re-transmission of lost packets.
When you have duplex communication available it is always better to re-transmit data only to clients having packet loss then to include overhead of forward-error-correction in stream sent to all clients.
In any case lost packets are unacceptable. Dropped frames are ok in exceptional cases when bandwidth is hindered.
The result of missing packets are artifacts like this one:
Some decoders can break on streams missing packets in critical places.
Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement")
below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
It looks like you are passing an NSString
parameter where you should be passing an NSData
parameter:
NSError *jsonError;
NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
Reposting @glefait 's answer with an if condition at the end to avoid os error 20. The first key it gets is the folder name itself which cannot be written in the destination path.
def download_dir(client, resource, dist, local='/tmp', bucket='your_bucket'):
paginator = client.get_paginator('list_objects')
for result in paginator.paginate(Bucket=bucket, Delimiter='/', Prefix=dist):
if result.get('CommonPrefixes') is not None:
for subdir in result.get('CommonPrefixes'):
download_dir(client, resource, subdir.get('Prefix'), local, bucket)
for file in result.get('Contents', []):
print("Content: ",result)
dest_pathname = os.path.join(local, file.get('Key'))
print("Dest path: ",dest_pathname)
if not os.path.exists(os.path.dirname(dest_pathname)):
print("here last if")
os.makedirs(os.path.dirname(dest_pathname))
print("else file key: ", file.get('Key'))
if not file.get('Key') == dist:
print("Key not equal? ",file.get('Key'))
resource.meta.client.download_file(bucket, file.get('Key'), dest_pathname)enter code here
Adding a right JRE System through build path is the solution but your eclipse still may have the error. To solve that go to Java Build path --> Order and Export and move your JRE system library on the top. This has solved my problem.
You must specify :
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")
For the file to be opened directly in the browser instead of being downloaded
Just to make concrete emory's answer, the executable code is the following :
Map<String,Callable<USer>> map = new HashMap<String,Callable<User>>();
map.put( "test" , new Callable<User> () { public User call (){ return fillUser("test" ); }} ) ;
map.put( "admin" , new Callable<Utente> () { public Utente call (){ return fillUser("admin" ); }} ) ;
where user is a POJO, and then
User user = map.get(USERNAME).call();
finally the called method is somewhere :
private User fillUser(String x){
User user = new User();
// set something in User
return user;
}
I do like that:
interface XYZ {
x: number;
y: number;
z: number;
}
const a:XYZ = {x:1, y:2, z:3};
const { x, y, ...last } = a;
const { z, ...firstTwo} = a;
console.log(firstTwo, last);
Documenting in detail for future readers:
The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url)
method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.
The below is the skeleton on how you would accomplish this:
class CustomWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Based on some condition you need to determine if you are going to load the url
// in your web view itself or in a browser.
// You can use `host` or `scheme` or any part of the `uri` to decide.
if (/* any condition */) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// e.g. open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
}
Just like shouldOverrideUrlLoading
, you can come up with a similar approach for shouldInterceptRequest
method.
If you are working on Windows then do the following:
From this directory:
C:\Users\ [your username] \AppData\Roaming , delete NPM folder then install Angular using this command npm install -g @angular/cli
This should help if you need a publicly exposed website but you're on a dev pc. Also to answer (I can't comment yet): "How do I post to an internal only running development server with this? – stryba "
NGROK creates a secure public URL to a local webserver on your development machine (Permanent URLs available for a fee, temporary for free).
1) Run ngrok.exe to open command line (on desktop)
2) Type ngrok.exe http 80 to start a tunnel,
3) test by browsing to the displayed web address which will forward and display the local default 80 page on your dev pc
Then use some of the tools recommended above to POST to your ngrok site ('https://xxxxxx.ngrok.io') to test your local code.
The FAQ session on tensor flow has an answer to exactly the same question. I will just go ahead and leave it here:
If t
is a Tensor
object, t.eval()
is shorthand for sess.run(t)
(where sess
is the current default session. The two following snippets of code are equivalent:
sess = tf.Session()
c = tf.constant(5.0)
print sess.run(c)
c = tf.constant(5.0)
with tf.Session():
print c.eval()
In the second example, the session acts as a context manager, which has the effect of installing it as the default session for the lifetime of the with
block. The context manager approach can lead to more concise code for simple use cases (like unit tests); if your code deals with multiple graphs and sessions, it may be more straightforward to explicit calls to Session.run()
.
I'd recommend that you at least skim throughout the whole FAQ, as it might clarify a lot of things.
If worse comes to worse, you can create an interface and adapter pair. You would change all uses of ConcreteClass to use the interface instead, and always pass the adapter instead of the concrete class in production code.
The adapter implements the interface, so the mock can also implement the interface.
It's more scaffolding than just making a method virtual or just adding an interface, but if you don't have access to the source for the concrete class it can get you out of a bind.
Use a generator function to generate an iterator.
def foo_gen():
n = 0
while True:
n+=1
yield n
Then use it like
foo = foo_gen().next
for i in range(0,10):
print foo()
If you want an upper limit:
def foo_gen(limit=100000):
n = 0
while n < limit:
n+=1
yield n
If the iterator terminates (like the example above), you can also loop over it directly, like
for i in foo_gen(20):
print i
Of course, in these simple cases it's better to use xrange :)
Here is the documentation on the yield statement.
Somewhere in your initialisation put this code.
Array.prototype.contains = function contains(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] === obj) {
return true;
}
}
return false;
};
Then, you can use it this way:
<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>
Very simple methods Just go to the terminal and the type following
rails g devise:controllers users //This will create devise controllers in controllers/users folder
Next to use custom views
rails g devise:views users //This will create devise views in views/users folder
now in your route.rb file
devise_for :users, controllers: {
:sessions => "users/sessions",
:registrations => "users/registrations" }
You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.
Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !
mimetype headers are recognised by the browser for the purpose of a (fast) possible identifying a handler to use the downloaded file as target, for example, PDF would be downloaded and your Adobe Reader program would be executed with the path of the PDF file as an argument,
If your needs are to write a browser extension to handle your downloaded file, through your operation-system, or you simply want to make you project a more 'professional looking' go ahead and select a unique mimetype for you to use, it would make no difference since the operation-system would have no handle to open it with (some browsers has few bundled-plugins, for example new Google Chrome versions has a built-in PDF-reader),
if you want to make sure the file would be downloaded have a look at this answer: https://stackoverflow.com/a/34758866/257319
if you want to make your file type especially organised, it might be worth adding a few letters in the first few bytes of the file, for example, every JPG has this at it's file start:
if you can afford a jump of 4 or 8 bytes it could be very helpful for you in the rest of the way
:)
No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.
For instance, consider a class that has a method get_data
. This method does an external lookup (on a database or web API, for example), and various other methods in the class call it. However, in a unit test, you don't want to depend on the external data source - so you dynamically replace the get_data
method with a stub that returns some fixed data.
Because Python classes are mutable, and methods are just attributes of the class, you can do this as much as you like - and, in fact, you can even replace classes and functions in a module in exactly the same way.
But, as a commenter pointed out, use caution when monkeypatching:
If anything else besides your test logic calls get_data
as well, it will also call your monkey-patched replacement rather than the original -- which can be good or bad. Just beware.
If some variable or attribute exists that also points to the get_data
function by the time you replace it, this alias will not change its meaning and will continue to point to the original get_data
. (Why? Python just rebinds the name get_data
in your class to some other function object; other name bindings are not impacted at all.)
This is easily achieved either programmatically, in your code, or declaratively in either the web.config or the app.config.
You can programmatically create a proxy like so:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("[ultimate destination of your request]");
WebProxy myproxy = new WebProxy("[your proxy address]", [your proxy port number]);
myproxy.BypassProxyOnLocal = false;
request.Proxy = myproxy;
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
You're basically assigning the WebProxy
object to the request
object's proxy
property. This request
will then use the proxy
you define.
To achieve the same thing declaratively, you can do the following:
<system.net>
<defaultProxy>
<proxy
proxyaddress="http://[your proxy address and port number]"
bypassonlocal="false"
/>
</defaultProxy>
</system.net>
within your web.config or app.config. This sets a default proxy that all http requests will use. Depending upon exactly what you need to achieve, you may or may not require some of the additional attributes of the defaultProxy / proxy element, so please refer to the documentation for those.
Yes, the SSL connection is between the TCP layer and the HTTP layer. The client and server first establish a secure encrypted TCP connection (via the SSL/TLS protocol) and then the client will send the HTTP request (GET, POST, DELETE...) over that encrypted TCP connection.
Check this out:
SELECT
p.Person,
p.`Group`,
p.Age
FROM
people p
INNER JOIN
(
SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`
UNION
SELECT MAX(p3.Age) AS Age, p3.`Group` FROM people p3 INNER JOIN (SELECT MAX(Age) AS Age, `Group` FROM people GROUP BY `Group`) p4 ON p3.Age < p4.Age AND p3.`Group` = p4.`Group` GROUP BY `Group`
) p2 ON p.Age = p2.Age AND p.`Group` = p2.`Group`
ORDER BY
`Group`,
Age DESC,
Person;
SQL Fiddle: http://sqlfiddle.com/#!2/cdbb6/15
Did you try format?
@font-face {
font-family: 'The name of the Font Family Here';
src: URL('font.ttf') format('truetype');
}
Read this article: http://css-tricks.com/snippets/css/using-font-face/
Also, might depend on browser as well.
One more working solution: wokeDyno Here is a blog post how it works: It's integrated in the app very easy:
/* Example: as used with an Express app */
const express = require("express")
const wakeDyno = require("woke-dyno");
// create an Express app
const app = express();
// start the server, then call wokeDyno(url).start()
app.listen(PORT, () => {
wakeDyno(DYNO_URL).start(); // DYNO_URL should be the url of your Heroku app
});
@IanDevlin is correct. MDN's rules say the following:
"The HTML Header Element "" defines a page header — typically containing the logo and name of the site and possibly a horizontal menu..."
The word "possibly" there is key. It goes on to say that the header doesn't necessarily need to be a site header. For instance you could include a "header" on a pop-up modal or on other modular parts of the document where there is a header and it would be helpful for a user on a screen reader to know about it.
It terms of the implicit use of NAV you can use it anywhere there is grouped site navigation, although it's usually omitted from the "footer" section for mini-navs / important site links.
Really it comes down to personal / team choice. Decide what you and your team feel is more semantic and more important and the try to be consistent. For me, if the nav is inline with the logo and the main site's "h1" then it makes sense to put it in the "header" but if you have a different design choice then decide on a case by case basis.
Most importantly check out the docs and be sure if you choose to omit or include you understand why you are making that particular decision.
You know the adage - beauty is in the eyes of the beholder.
Some people swear by NetBeans and some by IntelliJ IDEA, some by Python and some by PHP.
In some shops you could lose your job if you insist on doing this:
public void hello()
{
if (....)
{
....
}
}
The question is all about visibility and maintainability.
I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.
Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.
I remember 20 years ago, a colleague of mine was fired for employing what today would be called agile development strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can't incrementally release features to users! You must stick with the waterfall." His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to "customer's requirement".
We are frequently guilty for breaking data normalization, MVP and MVC boundaries. We inline instead of constructing a function. We take shortcuts.
Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules
quality = precision, maintainability and profitability.
All other rules fade into the background. And of course this rule never fades:
Laziness is the virtue of a good programmer.
Try this -
EditText myEditText = (EditText) findViewById(R.id.vnosEmaila);
String text = myEditText.getText().toString();
don't forget to
chmod ~/.local/share/applications/postman.desktop +x
otherwise it won't show in the Unity Launcher
Extending https://stackoverflow.com/users/5540715/surendra-shrestha answer for linux (~mint) users:
1. Install Android Studio (many tools have been deprecated for command line, so this is likely required). Asuming you follow the author instrucctions, your Android Studio will be installed in /usr/local/android-studio/. At the time of writing, the gradle version in Android Studio is 3.2, look at yours with ls /usr/local/android-studio/gradle/
.
2. Add your gradle command, this can be done extending the PATH, as @surendra-shrestha suggested (should be written in ~/.bashrc to preserve the PATH change), adding an alias echo 'export alias gradle=/usr/local/android-studio/gradle/gradle-3.2/bin/gradle' >> ~/.bashrc && source ~/.bashrc
. Or making a symbolic link: sudo ln -sn /usr/local/android-studio/gradle/gradle-3.2/bin/gradle /usr/bin/gradle
(this was my choice).
3. Run cordova requirements
to check everyhing is OK, should output something like:
Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-26,android-25,android-24,android-23,android-22,android-21,android-19,Google Inc.:Google APIs:19
Gradle: installed /usr/local/android-studio/gradle/gradle-3.2/bin/gradle
The *_test.go
file is a Go source like the others, you can initialize a new logger every time if you need to dump complex data structure, here an example:
// initZapLog is delegated to initialize a new 'log manager'
func initZapLog() *zap.Logger {
config := zap.NewDevelopmentConfig()
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
config.EncoderConfig.TimeKey = "timestamp"
config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
logger, _ := config.Build()
return logger
}
Then, every time, in every test:
func TestCreateDB(t *testing.T) {
loggerMgr := initZapLog()
// Make logger avaible everywhere
zap.ReplaceGlobals(loggerMgr)
defer loggerMgr.Sync() // flushes buffer, if any
logger := loggerMgr.Sugar()
logger.Debug("START")
conf := initConf()
/* Your test here
if false {
t.Fail()
}*/
}
@Logan has put this perfectly. Potentially something worth pointing out also is that you can use
printf(whatever you want to print);
For example if you were printing a string:
printf("hello");
Rarely, a hardened HTTP server is configured to give no server information or misleading server information. In those scenarios if the server has PHP enabled you can add:
<?php phpinfo(); ?>
in a file and browse to it and look for the
_SERVER["SERVER_SOFTWARE"]
entry. This is susceptible to the same hardening lack of information/misleading though I would imagine that it's not altered often, because this method first requires access to the machine to create the PHP file.
You can also use the ES6 Reflect
object:
x = {'key': 1};
Reflect.has( x, 'key'); // returns true
Documentation on MDN for Reflect.has
can be found here.
The static
Reflect.has()
method works like the in operator as a function.
You may not necessarily want/need to stash your work/files in your working directory but instead simply get rid of them completely. The command git clean
will do this for you.
Some common use cases for doing this would be to remove cruft that has been generated by merges or external tools or remove other files so that you can run a clean build.
Keep in mind you will want to be very cautious of this command, since its designed to remove files from your local working directory that are NOT TRACKED. if you suddently change your mind after executing this command, there is no going back to see the content of the files that were removed. An alternative which is safer is to execute
git stash --all
which will remove everything but save it all in a stash. This stash can then later be used.
However, if you truly DO want to remove all the files and clean your working directory, you should execute
git clean -f -d
This will remove any files and also any sub-directories that don't have any items as a result of the command. A smart thing to do before executing the git clean -f -d
command is to run
git clean -f -d -n
which will show you a preview of what WILL be removed after executing git clean -f -d
So here is a summary of your options from most aggressive to least aggressive
Option 1: Remove all files locally(Most aggressive)
git clean -f -d
Option 2: Preview the above impact(Preview most aggressive)
git clean -f -d -n
Option 3: Stash all files (Least aggressive)
`git stash --all`
We can define maximum pool size in following way:
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>200</max-pool-size>
<prefill>true</prefill>
<use-strict-min>true</use-strict-min>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
You need to have a SQLite JDBC driver in your classpath.
Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name sqlite-jdbc. It bundles the native drivers for major platforms so you don't need to configure them separately.
Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”:
sub.data<-data[ data[,1] != "b" & data[,1] != "d" & data[,1] != "e" , ]
Larger but simple to understand (I guess) and can be used with multiple columns, even with !is.na( data[,1])
.
New, resurrected project site (Win7 compability and more!): http://sshwindows.sourceforge.net
1st January 2012
- OpenSSH for Windows 5.6p1-2 based release created!!
- Happy New Year all! Since COpSSH has started charging I've resurrected this project
- Updated all binaries to current releases
- Added several new supporting DLLs as required by all executables in package
- Renamed switch.exe to bash.exe to remove the need to modify and compile mkpasswd.exe each build
- Please note there is a very minor bug in this release, detailed in the docs. I'm working on fixing this, anyone who can code in C and can offer a bit of help it would be much appreciated
public class EvenOddNumberPrintUsingTwoThreads {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread() {
public void run() {
for (int i = 0; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println("Even : " + i);
}
}
}
};
Thread t2 = new Thread() {
// int i=0;
public void run() {
for (int i = 0; i <= 10; i++) {
if (i % 2 == 1) {
System.out.println("Odd : " + i);
}
}
}
};
t1.start();
t2.start();
}
}
To me it seems @atomicules has the simplest answer, but I think it can be simplified a little more. You need to put an @
before anything you want to be global, so that it compiles to this.anything
and this
refers to the global object.
@bawbag = (x, y) ->
z = (x * y)
bawbag(5, 10)
this.bawbag = function(x, y) {
var z;
return z = x * y;
};
bawbag(5, 10);
(function() {
this.bawbag = function(x, y) {
var z;
return z = x * y;
};
console.log(bawbag(5,13)) // works here
}).call(this);
console.log(bawbag(5,11)) // works here
Just load it into a new object on process .. process.gulp = {}
and have the task look there.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
// Edit: Tool was already mentioned in another answer, so give all credits to Kuryaki.
Just found SupoSE which is a java based command line tool which scans a repository to create an index and afterwards is able to answer certain kinds of queries. We're still evaluating the tool but it looks promising. It's worth to mention that it makes a full index of all revisions including source code files and common office formats.
Maybe for UWP C#
public static async Task<IStorageItem> AsIStorageItemAsync(this string iStorageItemPath)
{
if (string.IsNullOrEmpty(iStorageItemPath)) return null;
IStorageItem storageItem = null;
try
{
storageItem = await StorageFolder.GetFolderFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
try
{
storageItem = await StorageFile.GetFileFromPathAsync(iStorageItemPath);
if (storageItem != null) return storageItem;
} catch { }
return storageItem;
}
You need an instance of the class containing the non static method.
Is like when you try to invoke the non-static method startsWith
of class String
without an instance:
String.startsWith("Hello");
What you need is to have an instance and then invoke the non-static method:
String greeting = new String("Hello World");
greeting.startsWith("Hello"); // returns true
So you need to create and instance to invoke it.
The R file can't be generated if your layout contains errors. If your res
folder is empty, then it's safe to assume that there's no res/layout
folder with any layouts in it, but your activity is probably calling setContentView
and not finding anything -- that qualifies as a problem with your layout.
You should try using the File System Object or FSO. There are many methods belonging to this object that check if folders exist as well as creating new folders.
Firebug 2 does now incorporate DOM events debugging / inspection.
I was getting this same error, in our case it was caused by a load balancer. We hade to make sure that the persistance was set to Source IP. Otherwise the login form was opened by one server, and processed by the other, which would fail to set the authentication cookie correctly. Maybe this helps someone else
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
With Guava:
final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));
I my case, I was using syncthing. It created a duplicate that I was not aware of and my compilation was failing.
I just spent an hour on a similar problem. For me the answer turned out to be embarrassingly simple.
(dataGridViewFields.DataSource as DataTable).DefaultView.RowFilter = string.Format("Field = '{0}'", textBoxFilter.Text);
The DUAL table is a special one-row table present by default in all Oracle database installations. It is suitable for use in selecting a pseudocolumn such as SYSDATE or USER
The table has a single VARCHAR2(1) column called DUMMY that has a value of "X"
You can read all about it in http://en.wikipedia.org/wiki/DUAL_table
use:
#ifdef __linux__
//linux code goes here
#elif _WIN32
// windows code goes here
#else
#endif
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
According to this article on the w3c website:
CDATA is a sequence of characters from the document character set and may include character entities. User agents should interpret attribute values as follows:
- Replace character entities with characters,
- Ignore line feeds,
- Replace each carriage return or tab with a single space.
This means that (at least) CR and LF won't work inside title attribute. I suggest that you use a tooltip plugin. Most of these plugins allow arbitrary HTML to be displayed as an element's tooltip.
Here is a practical example of Anchor tag with different
There is a minimal amount of "default" buffer when you startup a 'screen' session within your 'putty session'. I use screens a lot in my work, so I can tell you that you will not have a combination of 'screen' buffer & 'putty' buffer within your 'screen' session.
Setting the default number of scrollback lines by adding defscrollback 10000
to your ~/.screenrc
file is the correct solution.
By the way, I use "defscrollback 200000" in my ./screenrc
file.
Some of the key differences are in the complexity requirements.
A map
requires O(log(N))
time for inserts and finds operations, as it's implemented as a Red-Black Tree data structure.
An unordered_map
requires an 'average' time of O(1)
for inserts and finds, but is allowed to have a worst-case time of O(N)
. This is because it's implemented using Hash Table data structure.
So, usually, unordered_map
will be faster, but depending on the keys and the hash function you store, can become much worse.
For those using Windows, I had this issue because :
npm uninstall -g @ angular/cli
, the folder AppData\Roaming\npm
were still containing a ng
fileI tried then to remove the ng
file manually, but for some reasons it was not possible (I did not have the right), even as admin.
The only hack I found was using a 'linux based' command (I used Git bash) as admin and removing this file from command line:
cd AppData/Roaming/npm
rm ng.cmd
For information: this was with the version 6 of the CLI. There is not problem anymore to remove manually this specific file after the update.
You could also do:
body > #root > div {
height: 100vh;
}
Yes, take a look at getting a list of threads. Lots of examples on that page.
That's to do it programmatically. If you just want a list on Linux at least you can just use this command:
kill -3 processid
and the VM will do a thread dump to stdout.
Create rectangle.xml
using Shape Drawable Like this put in to your Drawable Folder...
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<corners android:radius="12px"/>
<stroke android:width="2dip" android:color="#000000"/>
</shape>
put it in to an ImageView
<ImageView
android:id="@+id/rectimage"
android:layout_height="150dp"
android:layout_width="150dp"
android:src="@drawable/rectangle">
</ImageView>
Hope this will help you.
on Jupyter notebook, try this:
pwd #this shows the current directory
if this is not the directory you like and you would like to change, try this:
import os
os.chdir ('THIS SHOULD BE YOUR DESIRED DIRECTORY')
Then try pwd again to see if the directory is what you want.
It works for me.
I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
System.Web.HttpContext.Current.Server.MapPath("~/")
gives null if we call it from a thread.
So, Try to use
System.Web.Hosting.HostingEnvironment.MapPath("~/")
FOR ANGULAR 7+
Actually since Angular 7.2 there is not need to use a service for saving the previous url. You could just use the state object to set the last url before linking to the login page. Here is an example for a login scenario.
@Component({ ... })
class SomePageComponent {
constructor(private router: Router) {}
checkLogin() {
if (!this.auth.loggedIn()) {
this.router.navigate(['login'], { state: { redirect: this.router.url } });
}
}
}
@Component({...})
class LoginComponent {
constructor(private router: Router) {}
backToPreviousPage() {
const { redirect } = window.history.state;
this.router.navigateByUrl(redirect || '/homepage');
}
}
----------------
Additionally you could also pass the data in the template:
@Component({
template: '<a routerLink="/some-route" [state]="{ redirect: router.url}">Go to some route</a>'
})
class SomePageComponent {
constructor(public router: Router) {}
}
I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.
#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation
#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
$hash = @{
"Name" = $bName
"Primary Type" = $bPrimaryType
}
$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force
I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.
It works in powershell 3 and above.
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
Open a command prompt as an Administrator.
Enter slmgr /upk
and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.
Enter slmgr /cpky
and wait for this to complete. This will remove the product key from the registry if it's still there.
Enter slmgr /rearm
and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.
This should put the system back to a pre-key state.
Hope this helps you out!
What about detached or unrelated shells and code [args]
support?
While other answers talk about how to configure and use the VScode integrated WSL bash
terminal support, they don't solve the problem of "detached shells": shells which were not launched from within VScode, or which somehow get "disconnected" from the VScode server instance associated with the IDE.
Such shells can give errors like:
Command is only available in WSL or inside a Visual Studio Code terminal.
or...
Unable to connect to VS Code server.
Error in request
Here's a script which makes it easy to solve this problem.
I use this daily to connect shells in a tmux
session with a specific VScode server instance, or to fix an integrated shell that's become detached from its hosting IDE.
#!/bin/bash
# codesrv-connect
#
# Purpose:
# Copies the vscode connection environment from one shell to another, so that you can use the
# vscode integrated terminal's "code [args]" command to communicate with that instance of vscode
# from an unrelated shell.
#
# Usage:
# 1. Open an integrated terminal in vscode, and run codesrv-connect
# 2. In the target shell, cd to the same directory and run
# ". .codesrv-connect", or follow the instruction printed by codesrv-connect.
#
# Setup:
# Put "codesrv-connect somewhere on your PATH (e.g. ~/bin)"
#
# Cleanup:
# - Delete abandoned .codesrv-connect files when their vscode sessions die.
# - Do not add .codesrv-connect files to git repositories.
#
# Notes:
# The VSCODE_IPC_HOOK_CLI environment variable points to a socket which is rather volatile, while the long path for the 'code' alias is more stable: vscode doesn't change the latter even across a "code -r ." reload. But the former is easily detached and so you need a fresh value if that happens. This is what codesrv-connect does: it captures the value of these two and writes them to .codesrv-connect in the current dir.
#
# Verinfo: v1.0.0 - [email protected] - 2020-03-31
#
function errExit {
echo "ERROR: $@" >&2
exit 1
}
[[ -S $VSCODE_IPC_HOOK_CLI ]] || errExit "VSCODE_IPC_HOOK_CLI not defined or not a pipe [$VSCODE_IPC_HOOK_CLI]"
if [[ $(which code) != *vscode-server* ]]; then
errExit "The 'code' command doesn't refer to something under .vscode-server: $(type -a code)"
fi
cat <<EOF >.codesrv-connect
# Temp file created by $(which codesrv-connect): source this into your working shell like '. .codesrv-connect'
# ( git hint: add ".codesrv-connect" to .gitignore )
#
cd "$PWD"
if ! test -S "$VSCODE_IPC_HOOK_CLI"; then
echo "ERROR: $VSCODE_IPC_HOOK_CLI not a socket. Dead session."
else
export VSCODE_IPC_HOOK_CLI="$VSCODE_IPC_HOOK_CLI"
alias code=$(which code)
echo "Done: the 'code' command will talk to socket \"$VSCODE_IPC_HOOK_CLI\" now."
echo "You can delete .codesrv-connect when the vscode server context dies, or reuse it in other shells until then."
fi
EOF
echo "# OK: run this to connect to vscode server in a destination shell:"
echo ". $PWD/.codesrv-connect"
Have a try on the listings
package. Here is an example of what I used some time ago to have a coloured Java listing:
\usepackage{listings}
[...]
\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}
[...]
\begin{lstlisting}
public void here() {
goes().the().code()
}
[...]
\end{lstlisting}
You may want to customize that. There are several references of the listings package. Just google them.
Well at the place of openssl ... you have to put actually the path to your openssl folder that you have downloaded. Your actual command should look like:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | "C:\Users\abc\openssl\bin\openssl.exe" sha1 -binary | "C:\Users\abc\openssl\bin\openssl.exe" base64
Remember, path that you will enter will be the path where you have installed the openssl...hope this helps..:-)
Edit:
you can download openssl for windows 32 and 64 bit from the respective links below:
Dim
have had different meanings attributed to it.
I've found references about Dim
meaning "Declare In Memory", the more relevant reference is a document on Dim Statement published Oracle as part of the Siebel VB Language Reference. Of course, you may argue that if you do not declare the variables in memory where do you do it? Maybe "Declare in Module" is a good alternative considering how Dim
is used.
In my opinion, "Declare In Memory" is actually a mnemonic, created to make easier to learn how to use Dim
. I see "Declare in Memory" as a better meaning as it describes what it does in current versions of the language, but it is not the proper meaning.
In fact, at the origins of Basic Dim
was only used to declare arrays. For regular variables no keyword was used, instead their type was inferred from their name. For instance, if the name of the variable ends with $
then it is a string (this is something that you could see even in method names up to VB6, for example Mid$
). And so, you used Dim
only to give dimension to the arrays (notice that ReDim
resizes arrays).
Really, Does It Matter? I mean, it is a keyword it has its meaning inside an artificial language. It doesn't have to be a word in English or any other natural language. So it could just mean whatever you want, all that matters is that it works.
Anyhow, that is not completely true. As BASIC is part of our culture, and understanding why it came to be as it is - I hope - will help improve our vision of the world.
I sit in from of my computer with a desire to help preserve this little piece of our culture that seems lost, replaced by our guessing of what it was. And so, I have dug MSDN both current and the old CDs from the 1998 version. I have also searched the documention for the old QBasic [Had to use DOSBox] and managed to get some Darthmouth manual, all to find how they talk about Dim
. For my disappointment, they don't say what does Dim
stand for, and only say how it is used.
But before my hope was dim, I managed to find this BBC Microcomputer System Used Guide (that claims to be from 1984, and I don't want to doubt it). The BBC Microcomputer used a variant of BASIC called BBC BASIC and it is described in the document. Even though, it doesn't say what does Dim
stand for, it says (on page 104):
... you can dimension N$ to have as many entries as you want. For example, DIM N$(1000) would create a string array with space for 1000 different names.
As I said, it doesn't say that Dim
stands for dimension, but serves as proof to show that associating Dim
with Dimension
was a common thing at the time of writing that document.
Now, I got a rewarding surprise later on (at page 208), the title for the section that describes the DIM keyword (note: that is not listed in the contents) says:
DIM dimension of an array
So, I didn't get the quote "Dim stands for..." but I guess it is clear that any decent human being that is able to read those document will consider that Dim
means dimension.
With renewed hope, I decided to search about how Dim
was chosen. Again, I didn't find an account on the subject, still I was able to find a definitive quote:
Before you can use an array, you must define it in a DIM (dimension) statement.
You can find this as part of the True BASIC Online User's Guides at the web page of True BASIC inc, a company founded by Thomas Eugene Kurtz, co-author of BASIC.
So, In reallity, Dim
is a shorthand for DIMENSION
, and yes. That existed in FORTRAN before, so it is likely that it was picked by influence of FORTRAN as Patrick McDonald said in his answer.
Dim sum as string = "this is not a chinese meal" REM example usage in VB.NET ;)
The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.
Try the :host > /deep/ :
Add the following to the parent.component.less file
:host {
/deep/ app-child-component {
//your child style
}
}
Replace the app-child-component by your child selector
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
The problem was caused by missing inclusion of ngRoute module. Since version 1.1.6 it's a separate part:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
var app = angular.module('myapp', ['ngRoute']);
This is getting reference from: AngularJS 1.2 $injector:modulerr David answer
If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.
Click inside the actual report layout.
Now select "View" from the main menu bar.
Now select "Report Data" which is the last item.
If you're in bash
, you can say:
bash-3.2$ var=abcd
bash-3.2$ echo ${var:0:2}
ab
This may be just what you need…
This code is worked for me without setAutoResizeModes.
TableColumnModel columnModel = jTable1.getColumnModel();
columnModel.getColumn(1).setPreferredWidth(170);
columnModel.getColumn(1).setMaxWidth(170);
columnModel.getColumn(2).setPreferredWidth(150);
columnModel.getColumn(2).setMaxWidth(150);
columnModel.getColumn(3).setPreferredWidth(40);
columnModel.getColumn(3).setMaxWidth(40);
I had to check System.ValueTuple.dll file was under source control and correct its reference in .cssproj files:
< Reference Include="System.ValueTuple" >
< HintPath >
....\ProjectName\ProjectName\obj\Release\Package\PackageTmp\bin\System.ValueTuple.dll
< /HintPath >
< /Reference >
into
< Reference Include="System.ValueTuple" >
< HintPath >
..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll
< /HintPath >
< /Reference >
(Optional): 7. solve same problems with another .dll files this way
I have tested a full layout using flexbox it contains header, footer, main body with left, center and right panels and the panels can contain menu items or footer and headers that should scroll. Pretty complex
IE11 and even IE EDGE have some problems displaying the flex content but it can be overcome. I have tested it in most browsers and it seems to work.
Some fixed i have applies are IE11 height bug, Adding height:100vh and min-height:100% to the html/body. this also helps to not have to set height on container in the dom. Also make the body/html a flex container. Otherwise IE11 will compress the view.
html,body {
display: flex;
flex-flow:column nowrap;
height:100vh; /* fix IE11 */
min-height:100%; /* fix IE11 */
}
A fix for IE EDGE that overflows the flex container: overflow:hidden on main flex container. if you remove the overflow, IE EDGE wil push the content out of the viewport instead of containing it inside the flex main container.
main{
flex:1 1 auto;
overflow:hidden; /* IE EDGE overflow fix */
}
You can see my testing and example on my codepen page. I remarked the important css parts with the fixes i have applied and hope someone finds it useful.
Another way that doesn't use group by:
SELECT * FROM tblpm n
WHERE date_updated=(SELECT date_updated FROM tblpm n
ORDER BY date_updated desc LIMIT 1)
Alternatively (just for comparison), if you have Rails installed (actually just ActiveSupport):
require 'activesupport'
array.sum
Given the general support of .innerHTML
these days, the only effective difference now is that .html()
will execute code in any <script>
tags if there are any in the html you give it. .innerHTML
, under HTML5, will not.
From the jQuery docs:
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example,
<img onload="">
). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Note: both .innerHTML
and .html()
can execute js other ways (e.g the onerror
attribute).
Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.
Your code will result in compiler errors. Your first code fragment:
char buf[10] ; buf = ''
is doubly illegal. First, in C, there is no such thing as an empty char
. You can use double quotes to designate an empty string, as with:
char* buf = "";
That will give you a pointer to a NUL
string, i.e., a single-character string with only the NUL
character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL
character, you have to specify it:
char buf = '\0';
The backslash is necessary to disambiguate from character '0'
.
char buf = 0;
accomplishes the same thing, but the former is a tad less ambiguous to read, I think.
Secondly, you cannot initialize arrays after they have been defined.
char buf[10];
declares and defines the array. The array identifier buf
is now an address in memory, and you cannot change where buf
points through assignment. So
buf = // anything on RHS
is illegal. Your second and third code fragments are illegal for this reason.
To initialize an array, you have to do it at the time of definition:
char buf [10] = ' ';
will give you a 10-character array with the first char being the space '\040'
and the rest being NUL
, i.e., '\0'
. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0
. There will not be any "random content".
If you declare and define the array but don't initialize it, as in the following:
char buf [10];
you will have random content in all the elements.
You can flip a value like so:
myVal = !myVal;
so your code would shorten down to:
switch(wParam) {
case VK_F11:
flipVal = !flipVal;
break;
case VK_F12:
otherVal = !otherVal;
break;
default:
break;
}
An alternate solution that copies one file at a time and does not require ROBOCOPY:
@echo off
setlocal enabledelayedexpansion
set "SOURCE_DIR=C:\Source"
set "DEST_DIR=C:\Destination"
set FILENAMES_TO_COPY=data.zip info.txt
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
The outer for statement generates any possible path combination of subdirectory in SOURCE_DIR
and name in FILENAMES_TO_COPY
. For each existing file xcopy is invoked. FILE_INTERMEDIATE_DIR
holds the file's subdirectory path within SOURCE_DIR
which needs to be created in DEST_DIR
.
Reason of the error: Package name left blank while creating a class. This make use of default package. Thus causes this error.
Quick fix:
helloWorld
inside the src
folder.helloWorld.java
file in that package. Just drag and drop on
the package. Error should disappear.Explanation:
Latest version of Eclipse required java11 or above. The module
feature is introduced in java9 and onward. It was proposed in 2005 for Java7 but later suspended. Java is object oriented based. And module is the moduler approach which can be seen in language like C. It was harder to implement it, due to which it took long time for the release. Source: Understanding Java 9 Modules
When you create a new project in Eclipse then by default module feature is selected. And in Eclipse-2020-09-R, a pop-up appears which ask for creation of module-info.java
file. If you select don't create
then module-info.java
will not create and your project will free from this issue.
Best practice is while crating project, after giving project name. Click on next
button instead of finish
. On next page at the bottom it ask for creation of module-info.java
file. Select or deselect as per need.
If selected: (by default) click on finish
button and give name for module. Now while creating a class don't forget to give package name. Whenever you create a class just give package name. Any name, just don't left it blank.
If deselect: No issue
They are the same.
One thing to be careful of, is if you are using this against a DATETIME, the match for the end date will be the beginning of the day:
<= 20/10/2009
is not the same as:
<= 20/10/2009 23:59:59
(it would match against <= 20/10/2009 00:00:00.000
)
If your method is called externally, start with something like this:
public void method(Object object) {
if (object == null) {
throw new IllegalArgumentException("...");
}
Then, in the rest of that method, you'll know that object
is not null.
If it is an internal method (not part of an API), just document that it cannot be null, and that's it.
Example:
public String getFirst3Chars(String text) {
return text.subString(0, 3);
}
However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.
This really depends. If find that I often do something like this:
if (object == null) {
// something
} else {
// something else
}
So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?
It's actually rare for me to use the idiom "if (object != null && ...
".
It may be easier to give you examples, if you show examples of where you typically use the idiom.
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
Don't forget that integers can be negative:
^\s*-?[0-9]{1,10}\s*$
Here's the meaning of each part:
^
: Match must start at beginning of string\s
: Any whitespace character
*
: Occurring zero or more times-
: The hyphen-minus character, used to denote a negative integer
?
: May or may not occur[0-9]
: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
{1,10}
: Occurring at least one, but not more than ten times\s
: Any whitespace character
*
: Occurring zero or more times$
: Match must end at end of stringThis ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.
Call this in the project:
svn diff -r REVNO:HEAD --summarize
REVNO
is the start revision number and HEAD
is the end revision number. If HEAD is equal to the last revision number, it can skip it.
The command returns a list with all files that are changed/added/deleted in this revision period.
The command can be called with the URL revision parameter to check changes like this:
svn diff -r REVNO:HEAD --summarize SVN_URL
What about something like this :
cat texte.txt | sed -e 's/\s/,/g' > texte-new.txt
(Yes, with some useless catting and piping ; could also use < to read from the file directly, I suppose -- used cat first to output the content of the file, and only after, I added sed to my command-line)
EDIT : as @ghostdog74 pointed out in a comment, there's definitly no need for thet cat/pipe ; you can give the name of the file to sed :
sed -e 's/\s/,/g' texte.txt > texte-new.txt
If "texte.txt" is this way :
$ cat texte.txt
this is a text
in which I want to replace
spaces by commas
You'll get a "texte-new.txt" that'll look like this :
$ cat texte-new.txt
this,is,a,text
in,which,I,want,to,replace
spaces,by,commas
I wouldn't go just replacing the old file by the new one (could be done with sed -i, if I remember correctly ; and as @ghostdog74 said, this one would accept creating the backup on the fly) : keeping might be wise, as a security measure (even if it means having to rename it to something like "texte-backup.txt")
<?xml version="1.0" encoding="utf-8"?>_x000D_
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
xmlns:app="http://schemas.android.com/apk/res-auto"_x000D_
xmlns:tools="http://schemas.android.com/tools"_x000D_
android:id="@+id/main_content"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:fitsSystemWindows="true"_x000D_
tools:context=".ui.MainActivity"_x000D_
>_x000D_
<android.support.design.widget.AppBarLayout_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">_x000D_
_x000D_
<android.support.v7.widget.Toolbar_x000D_
android:id="@+id/toolbar"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_alignParentTop="true"_x000D_
android:background="?attr/colorPrimary"_x000D_
android:elevation="6dp"_x000D_
android:minHeight="?attr/actionBarSize"_x000D_
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"_x000D_
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />_x000D_
_x000D_
<android.support.design.widget.TabLayout_x000D_
android:id="@+id/tabs"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
app:tabMode="fixed"_x000D_
app:tabGravity="fill"_x000D_
>_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_1" />_x000D_
_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem2"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_2" />_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem3"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_3" />_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tItemab4"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_4" />_x000D_
</android.support.design.widget.TabLayout>_x000D_
</android.support.design.widget.AppBarLayout>_x000D_
<android.support.v4.view.ViewPager_x000D_
android:id="@+id/container"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:layout_below="@id/tabs"_x000D_
app:layout_behavior="@string/appbar_scrolling_view_behavior"_x000D_
tools:ignore="NotSibling"/>_x000D_
</android.support.constraint.ConstraintLayout>
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
xmlns:tools="http://schemas.android.com/tools"_x000D_
android:id="@+id/activity_main"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
tools:context=".ui.MainActivity">_x000D_
<include layout="@layout/tabs"></include>_x000D_
<LinearLayout_x000D_
android:orientation="vertical"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:layout_marginBottom="@dimen/activity_vertical_margin"_x000D_
android:layout_marginLeft="@dimen/activity_horizontal_margin"_x000D_
android:layout_marginRight="@dimen/activity_horizontal_margin"_x000D_
android:layout_marginTop="80dp">_x000D_
<FrameLayout android:id="@+id/tabContent"_x000D_
android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">_x000D_
</FrameLayout>_x000D_
</LinearLayout>_x000D_
</RelativeLayout>
_x000D_
public class MainActivity extends AppCompatActivity{_x000D_
_x000D_
private Toolbar toolbar;_x000D_
private TabLayout tabLayout;_x000D_
private ViewPagerAdapter adapter;_x000D_
_x000D_
private final static int[] tabIcons = {_x000D_
R.drawable.ic_action_car,_x000D_
android.R.drawable.ic_menu_mapmode,_x000D_
android.R.drawable.ic_dialog_email,_x000D_
R.drawable.ic_action_settings_x000D_
};_x000D_
_x000D_
protected void onCreate(Bundle savedInstanceState) {_x000D_
super.onCreate(savedInstanceState);_x000D_
setContentView(R.layout.activity_main);_x000D_
_x000D_
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);_x000D_
setSupportActionBar(toolbar);_x000D_
_x000D_
ViewPager viewPager = (ViewPager) findViewById(R.id.container);_x000D_
setupViewPager(viewPager);_x000D_
_x000D_
_x000D_
tabLayout = (TabLayout) findViewById(R.id.tabs);_x000D_
tabLayout.setupWithViewPager(viewPager);_x000D_
setupTabIcons();_x000D_
_x000D_
_x000D_
}_x000D_
private void setupTabIcons() {_x000D_
tabLayout.getTabAt(0).setIcon(tabIcons[0]);_x000D_
tabLayout.getTabAt(1).setIcon(tabIcons[1]);_x000D_
tabLayout.getTabAt(2).setIcon(tabIcons[2]);_x000D_
tabLayout.getTabAt(3).setIcon(tabIcons[3]);_x000D_
}_x000D_
_x000D_
private void setupViewPager(ViewPager viewPager) {_x000D_
adapter = new ViewPagerAdapter(getSupportFragmentManager());_x000D_
adapter.addFrag(new CarFragment());_x000D_
adapter.addFrag(new LocationFragment());_x000D_
adapter.addFrag(new MessageFragment());_x000D_
adapter.addFrag(new SettingsFragment());_x000D_
viewPager.setAdapter(adapter);_x000D_
}_x000D_
_x000D_
class ViewPagerAdapter extends FragmentPagerAdapter {_x000D_
private final List<Fragment> mFragmentList = new ArrayList<>();_x000D_
ViewPagerAdapter(FragmentManager manager) {_x000D_
super(manager);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public Fragment getItem(int position) {_x000D_
return mFragmentList.get(position);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public int getCount() {_x000D_
return mFragmentList.size();_x000D_
}_x000D_
_x000D_
void addFrag(Fragment fragment) {_x000D_
mFragmentList.add(fragment);_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
I think you want to extract a column from an array such as an array below
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
Now if you want to get the third column in the format
D=array[[3],
[7],
[11]]
Then you need to first make the array a matrix
B=np.asmatrix(A)
C=B[:,2]
D=asarray(C)
And now you can do element wise calculations much like you would do in excel.
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
Make sure the required dlls are exported (or copied manually) to the bin folder when building your application.
The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.
public class LinkedList {
Node head;
public static class Node{
int data;
Node next;
Node(int item){
data = item;
next = null;
}
}
public static void main(String args[]){
LinkedList ll = new LinkedList();
ll.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3);
Node fourth = new Node(4);
ll.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;
ll.printList();
System.out.println("Add element 100 to the last");
ll.addLast(100);
ll.printList();
}
public void printList(){
Node t = head;
while(n != null){
System.out.println(t.data);
t = t.next;
}
}
public void addLast(int item){
Node new_item = new Node(item);
if(head == null){
head = new_item;
return;
}
new_item.next = null;
Node last = head;
Node temp = null;
while(last != null){
if(last != null)
temp = last;
last = last.next;
}
temp.next = new_item;
return;
}
}
https://docs.djangoproject.com/en/stable/topics/db/queries/#creating-objects
To create and save an object in a single step, use the
create()
method.
Mostly you don't see a difference, unless you are using set -u
:
/home/user1> var=""
/home/user1> echo $var
/home/user1> set -u
/home/user1> echo $var
/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable
So really, it depends on how you are going to test the variable.
I will add that my preferred way of testing if it is set is:
[[ -n $var ]] # True if the length of $var is non-zero
or
[[ -z $var ]] # True if zero length
it simple, select columns want to insert primary key and click on Key icon on header and save table
happy coding..,
In main.xml file
You can put the following attrubute to validate only alphabatics character can accept in edittext.
Do this :
android:entries="abcdefghijklmnopqrstuvwxyz"
I tried the below and it worked like a charm :)
rec_list = ['[email protected]', '[email protected]']
rec = ', '.join(rec_list)
msg['To'] = rec
send_out = smtplib.SMTP('localhost')
send_out.sendmail(me, rec_list, msg.as_string())
I have written the following Java program out of curiosity, simple and self-explanatory HTH. Thanks.
/**
*
* @author sanhn
*/
public class CheckPalindrome {
private static String max_string = "";
public static void checkSubString(String s){
System.out.println("Got string is "+s);
for(int i=1;i<=s.length();i++){
StringBuilder s1 = new StringBuilder(s.substring(0,i));
StringBuilder s2 = new StringBuilder(s.substring(0,i));
s2.reverse();
if(s1.toString().equals(s2.toString())){
if(max_string.length()<=s1.length()){
max_string = s1.toString();
System.out.println("tmp max is "+max_string);
}
}
}
}
public static void main(String[] args){
String s="HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE";
for(int i=0; i<s.length(); i++)
checkSubString(s.substring(i, s.length()));
System.out.println("Max string is "+max_string);
}
}
update mytable set title=trim(replace(REPLACE(title,CHAR(13),''),CHAR(10),''));
Above is working for fine.
when new props or states being received (like you call setState
here), React will invoked some functions, which are called componentWillUpdate
and componentDidUpdate
in your case, just simply add a componentDidUpdate
function to call this.drawGrid()
here is working code in JS Bin
as I mentioned, in the code, componentDidUpdate
will be invoked after this.setState(...)
then componentDidUpdate
inside is going to call this.drawGrid()
read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate
Nope, it is more complicated than just calling a method, if you want to transparently add it into the user's calendar.
You've got a couple of choices;
Calling the intent to add an event on the calendar
This will pop up the Calendar application and let the user add the event. You can pass some parameters to prepopulate fields:
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Or the more complicated one:
Get a reference to the calendar with this method
(It is highly recommended not to use this method, because it could break on newer Android versions):
private String getCalendarUriBase(Activity act) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = act.managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
and add an event and a reminder this way:
// get calendar
Calendar cal = Calendar.getInstance();
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
ContentResolver cr = getContentResolver();
// event insert
ContentValues values = new ContentValues();
values.put("calendar_id", 1);
values.put("title", "Reminder Title");
values.put("allDay", 0);
values.put("dtstart", cal.getTimeInMillis() + 11*60*1000); // event starts at 11 minutes from now
values.put("dtend", cal.getTimeInMillis()+60*60*1000); // ends 60 minutes from now
values.put("description", "Reminder description");
values.put("visibility", 0);
values.put("hasAlarm", 1);
Uri event = cr.insert(EVENTS_URI, values);
// reminder insert
Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
values = new ContentValues();
values.put( "event_id", Long.parseLong(event.getLastPathSegment()));
values.put( "method", 1 );
values.put( "minutes", 10 );
cr.insert( REMINDERS_URI, values );
You'll also need to add these permissions to your manifest for this method:
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />
Update: ICS Issues
The above examples use the undocumented Calendar APIs, new public Calendar APIs have been released for ICS, so for this reason, to target new android versions you should use CalendarContract.
More infos about this can be found at this blog post.
try this one, it might be helpful for you
String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
To complement the other answers: if you want to reset all background properties to their initial value (which includes background-color: transparent
and background-image: none
) without explicitly specifying any value such as transparent
or none
, you can do so by writing:
background: initial;
If you want to check the display value, https://stackoverflow.com/a/1189281/5622596 already posted the answer.
However if instead of checking whether an element has a style of style="display:none"
you want to know if that element is visible. Then use .is(":visible")
For example:
$('#idDetails').is(":visible");
This will be true
if it is visible & false
if it is not.
You probably want to look at something like URL Rewrite to rewrite URLs to more user friendly ones rather than using a simple httpRedirect
. You could then make a rule like this:
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite to Category">
<match url="^Category/([_0-9a-z-]+)/([_0-9a-z-]+)" />
<action type="Rewrite" url="category.aspx?cid={R:2}" />
</rule>
</rules>
</rewrite>
</system.webServer>
The concept of interval notation comes up in both Mathematics and Computer Science. The Mathematical notation [
, ]
, (
, )
denotes the domain (or range) of an interval.
The brackets [
and ]
means:
The parenthesis (
and )
means:
An interval with mixed states is called "half-open".
For example, the range of consecutive integers from 1 .. 10 (inclusive) would be notated as such:
Notice how the word inclusive
was used. If we want to exclude the end point but "cover" the same range we need to move the end-point:
For both left and right edges of the interval there are actually 4 permutations:
(1,10) = 2,3,4,5,6,7,8,9 Set has 8 elements
(1,10] = 2,3,4,5,6,7,8,9,10 Set has 9 elements
[1,10) = 1,2,3,4,5,6,7,8,9 Set has 9 elements
[1,10] = 1,2,3,4,5,6,7,8,9,10 Set has 10 elements
How does this relate to Mathematics and Computer Science?
Array indexes tend to use a different offset depending on which field are you in:
These differences can lead to subtle fence post errors, aka, off-by-one bugs when implementing Mathematical algorithms such as for-loops.
If we have a set or array, say of the first few primes [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
, Mathematicians would refer to the first element as the 1st
absolute element. i.e. Using subscript notation to denote the index:
Some programming languages, in contradistinction, would refer to the first element as the zero'th
relative element.
Since the array indexes are in the range [0,N-1] then for clarity purposes it would be "nice" to keep the same numerical value for the range 0 .. N instead of adding textual noise such as a -1
bias.
For example, in C or JavaScript, to iterate over an array of N elements a programmer would write the common idiom of i = 0, i < N
with the interval [0,N) instead of the slightly more verbose [0,N-1]:
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 0; i < 10; i++ ) // [0,10)_x000D_
output += "[" + i + "]: " + a[i] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById('output1').innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main();">_x000D_
<pre id="output1"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Mathematicians, since they start counting at 1, would instead use the i = 1, i <= N
nomenclature but now we need to correct the array offset in a zero-based language.
e.g.
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 1; i <= 10; i++ ) // [1,10]_x000D_
output += "[" + i + "]: " + a[i-1] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById( "output2" ).innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main()";>_x000D_
<pre id="output2"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Aside:
In programming languages that are 0-based you might need a kludge of a dummy zero'th element to use a Mathematical 1-based algorithm. e.g. Python Index Start
Interval notation is also important for floating-point numbers to avoid subtle bugs.
When dealing with floating-point numbers especially in Computer Graphics (color conversion, computational geometry, animation easing/blending, etc.) often times normalized numbers are used. That is, numbers between 0.0 and 1.0.
It is important to know the edge cases if the endpoints are inclusive or exclusive:
Where M is some machine epsilon. This is why you might sometimes see const float EPSILON = 1e-#
idiom in C code (such as 1e-6
) for a 32-bit floating point number. This SO question Does EPSILON guarantee anything? has some preliminary details. For a more comprehensive answer see FLT_EPSILON
and David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic
Some implementations of a random number generator, random()
may produce values in the range 0.0 .. 0.999... instead of the more convenient 0.0 .. 1.0. Proper comments in the code will document this as [0.0,1.0) or [0.0,1.0] so there is no ambiguity as to the usage.
Example:
random()
colors. You convert three floating-point values to unsigned 8-bit values to generate a 24-bit pixel with red, green, and blue channels respectively. Depending on the interval output by random()
you may end up with near-white
(254,254,254) or white
(255,255,255). +--------+-----+
|random()|Byte |
|--------|-----|
|0.999...| 254 | <-- error introduced
|1.0 | 255 |
+--------+-----+
For more details about floating-point precision and robustness with intervals see Christer Ericson's Real-Time Collision Detection, Chapter 11 Numerical Robustness, Section 11.3 Robust Floating-Point Usage.
Just an extra bit of help: the device needs to be directly connected to the computer, connecting it to an USB hub might prevent the device prompt from displaying.
git reset HEAD <file>
for removing a particular file from the index.
and
git reset HEAD
for removing all indexed files.
Just type
unlink [SOCKET NAME]
in the terminal, then the error should no longer exist.
Is it not just a case of applying an appropriate class to each div?
For example:
.firstRowDiv { margin:0px 10px 10px 0px; }
.secondRowDiv { margin:0px 10px 0px 0px; }
This depends on if you know in advance which div to apply which class to.
In addition to the other answers here, if you've forgotten to put:
cmd.CommandType = CommandType.StoredProcedure;
Then you will also get this error.
use
new Long(your_integer);
or
Long.valueOf(your_integer);
Similarities:
DTDs and Schemas both perform the same basic functions:
Differences:
DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.
Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.
Examples:
DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
<!ELEMENT Efirstname (#PCDATA)>
<!ELEMENT Elastname (#PCDATA)>
<!ELEMENT Etitle (#PCDATA)>
<!ELEMENT Ephone (#PCDATA)>
<!ELEMENT Eemail (#PCDATA)>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="generated" type="xsd:dateTime"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="employees">
<xsd:annotation>
<xsd:appinfo>
<od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
unique="yes" clustered="no"/>
<od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
clustered="no"/>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Elastname" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephone" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Eemail" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
var output = '/var/www/site/Brand new document.docx'.replace(/ /g, "");
or
var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");
Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.
If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.
for reference click here.
Python:
rotated = list(zip(*original[::-1]))
and counterclockwise:
rotated_ccw = list(zip(*original))[::-1]
How this works:
zip(*original)
will swap axes of 2d arrays by stacking corresponding items from lists into new lists. (The *
operator tells the function to distribute the contained lists into arguments)
>>> list(zip(*[[1,2,3],[4,5,6],[7,8,9]]))
[[1,4,7],[2,5,8],[3,6,9]]
The [::-1]
statement reverses array elements (please see Extended Slices or this question):
>>> [[1,2,3],[4,5,6],[7,8,9]][::-1]
[[7,8,9],[4,5,6],[1,2,3]]
Finally, combining the two will result in the rotation transformation.
The change in placement of [::-1]
will reverse lists in different levels of the matrix.
To set image on your imageView use below line of code,
self.imgObj.image=[UIImage imageNamed:@"yourImage.png"];
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
Try this
SELECT id from comission_fees ORDER BY id DESC LIMIT 1
The problem is that you aren't correctly escaping the input string, try:
echo "\"member\":\"time\"" | grep -e "member\""
Alternatively, you can use unescaped double quotes within single quotes:
echo '"member":"time"' | grep -e 'member"'
It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd'
).
You can configure your own merge tool to be used with "git mergetool
".
Example:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd p4merge '$BASE $LOCAL $REMOTE $MERGED'
git config --global mergetool.p4merge.trustExitCode false
And while you are at it, you can also set it up as your difftool for "git difftool
":
git config --global diff.tool p4merge
git config --global difftool.p4merge.cmd p4merge '$LOCAL $REMOTE'
Note that in Unix/Linux you don't want the $BASE
to get parsed as a variable by your shell - it should actually appear in your ~/.gitconfig file for this to work.
browsing sometime ago, found this site, have you tried this alternative?
li{
list-style-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAE0lEQVQIW2NkYGD4D8RwwEi6AACaVAQBULo4sgAAAABJRU5ErkJggg==");
}
sounds hard, but you can make your own png image/pattern here, then copy/paste your code and customize your bullets =) stills elegant?
EDIT:
following the idea of @lea-verou on the other answer and applying this philosophy of outside sources enhancement I've come to this other solution:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
i.e.: fa-angle-right []
and use the last part of f... followed by a number like this, with the font-family
too:
li:before {
content: "\f105";
font-family: FontAwesome;
color: red; /* or whatever color you prefer */
margin-right: 4px;
}
and that's it! now you have custom bullet tips too =)
1) see if the xml files in the Package Explorer tree have an error-icon if they do, fix errors and R-class will be generated.
example hint: FILL_PARENT was renamed MATCH_PARENT in API Level 8; so if you're targeting platform 2.1 (api 7), change all occurences back to "fill_parent"
2) if you added "import android.R;" trying to do a quick-fix, remove that line
Don't try to get them inside its constructor. Try Call them in onDraw()
method.
As a DBA, You must schedule the backup of MySQL Database in case of any issues so that you can recover your databases from the current backup.
Here, we are using mysqldump to take the backup of mysql databases and the same you can put into the script.
[orahow@oradbdb DB_Backup]$ cat .backup_script.sh
#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions
Continue Reading .... MySQL Backup
My use case was to save range to variable and then select it later on
Dim targetRange As Range
Set targetRange = Sheets("Sheet").Range("Name")
Application.Goto targetRange
Set targetRangeQ = Nothing ' reset
You simply need to do a SUBSTR on the string in col3....
Select col1, col2, REPLACE(substr(col3, instr(col3, 'Client Name'),
(instr(col3, '|', instr(col3, 'Client Name') -
instr(col3, 'Client Name'))
),
'Client Name = ',
'')
from Table01
And yes, that is a bad DB design for the reasons stated in the original issue
You can use pd.to_datetime
from the pandas library. Here are various options, depending on what you want returned.
import pandas as pd
pd.to_datetime('today') # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')
As a python datetime object,
pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)
As a formatted date string,
pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'
# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'
To get just the date from the timestamp, call Timestamp.date
.
pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)
Aside from to_datetime
, you can directly instantiate a Timestamp
object using,
pd.Timestamp('today') # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')
pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)
If you want to make your Timestamp timezone aware, pass a timezone to the tz
argument.
pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')
This one's good, I promise.
If you're working with pendulum, there are some interesting choices. You can get the current timestamp using now()
or today's date using today()
.
import pendulum
pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))
pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
Additionally, you can also get tomorrow()
or yesterday()
's date directly without having to do any additional timedelta arithmetic.
pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
There are various formatting options available.
pendulum.now().to_date_string()
# '2019-03-27'
pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'
pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'
A lot of pandas users stumble upon this question because they believe it is a python question more than a pandas one. This answer aims to be useful to folks who are already using these libraries and would be interested to know that there are ways to achieve these results within the scope of the library itself.
If you are not working with pandas or pendulum already, I definitely do not recommend installing them just for the sake of running this code! These libraries are heavy and come with a lot of plumbing under the hood. It is not worth the trouble when you can use the standard library instead.
Try this
\+?\(?([0-9]{3})\)?[-.]?\(?([0-9]{3})\)?[-.]?\(?([0-9]{4})\)?
It matches the following cases
For further explanation on the pattern CLICKME
#include <cstdlib>
...
exit( exit_code );
Add the following style to your h3
elements:
word-wrap: break-word;
This will cause the long URLs in them to wrap. The default setting for word-wrap is normal
, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
Its more likely that the path to file.js from the page is what is wrong. as long as when you view the page, and view-source you see the tag, its working, now its time to debug whether or not your path is too relative, maybe you need a / in front of it.
This will scroll to the very top:
$(window).animate({scrollTop: 0});
This will scroll to the very bottom:
$(window).animate({scrollTop: $(document).height() + $(window).height()});
.. change window to your desired container id or class if necessary (in quotes).
If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding ID}"/>
</StackPanel>
That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.
Install C++ SDK:
Help > Install New Software > Work with: path for your eclipse version
> search for C++ and install C++ sdk development tools.
Example for a path: Mars - http://download.eclipse.org/releases/mars
A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display.I just add some attributes .
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars = "vertical"
android:scrollbarStyle="insideInset"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<!-- Add here which you want -->
</TableLayout>
</ScrollView>
Just in case if it could help someone like me.
Based on the Official website and the Accepted answer, I made a code using C# that uses System.Data.SQLite NuGet package.
This code also preserves the Primary key and Foreign key.
CODE in C#:
void RemoveColumnFromSqlite (string tableName, string columnToRemove) {
try {
var mSqliteDbConnection = new SQLiteConnection ("Data Source=db_folder\\MySqliteBasedApp.db;Version=3;Page Size=1024;");
mSqliteDbConnection.Open ();
// Reads all columns definitions from table
List<string> columnDefinition = new List<string> ();
var mSql = $"SELECT type, sql FROM sqlite_master WHERE tbl_name='{tableName}'";
var mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
string sqlScript = "";
using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
while (mSqliteReader.Read ()) {
sqlScript = mSqliteReader["sql"].ToString ();
break;
}
}
if (!string.IsNullOrEmpty (sqlScript)) {
// Gets string within first '(' and last ')' characters
int firstIndex = sqlScript.IndexOf ("(");
int lastIndex = sqlScript.LastIndexOf (")");
if (firstIndex >= 0 && lastIndex <= sqlScript.Length - 1) {
sqlScript = sqlScript.Substring (firstIndex, lastIndex - firstIndex + 1);
}
string[] scriptParts = sqlScript.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in scriptParts) {
if (!s.Contains (columnToRemove)) {
columnDefinition.Add (s);
}
}
}
string columnDefinitionString = string.Join (",", columnDefinition);
// Reads all columns from table
List<string> columns = new List<string> ();
mSql = $"PRAGMA table_info({tableName})";
mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
using (mSqliteReader = mSqliteCommand.ExecuteReader ()) {
while (mSqliteReader.Read ()) columns.Add (mSqliteReader["name"].ToString ());
}
columns.Remove (columnToRemove);
string columnString = string.Join (",", columns);
mSql = "PRAGMA foreign_keys=OFF";
mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
int n = mSqliteCommand.ExecuteNonQuery ();
// Removes a column from the table
using (SQLiteTransaction tr = mSqliteDbConnection.BeginTransaction ()) {
using (SQLiteCommand cmd = mSqliteDbConnection.CreateCommand ()) {
cmd.Transaction = tr;
string query = $"CREATE TEMPORARY TABLE {tableName}_backup {columnDefinitionString}";
cmd.CommandText = query;
cmd.ExecuteNonQuery ();
cmd.CommandText = $"INSERT INTO {tableName}_backup SELECT {columnString} FROM {tableName}";
cmd.ExecuteNonQuery ();
cmd.CommandText = $"DROP TABLE {tableName}";
cmd.ExecuteNonQuery ();
cmd.CommandText = $"CREATE TABLE {tableName} {columnDefinitionString}";
cmd.ExecuteNonQuery ();
cmd.CommandText = $"INSERT INTO {tableName} SELECT {columnString} FROM {tableName}_backup;";
cmd.ExecuteNonQuery ();
cmd.CommandText = $"DROP TABLE {tableName}_backup";
cmd.ExecuteNonQuery ();
}
tr.Commit ();
}
mSql = "PRAGMA foreign_keys=ON";
mSqliteCommand = new SQLiteCommand (mSql, mSqliteDbConnection);
n = mSqliteCommand.ExecuteNonQuery ();
} catch (Exception ex) {
HandleExceptions (ex);
}
}
You could use an array and indexOf
:
if ([1,3,12].indexOf(foo) > -1)
Structured Query Language - SQL: is an ANSI-standard used by almost all SGBD's vendors around the world. Basically, SQL is a language used to define and manipulate data [DDL and DML].
PL/SQL is a language created by Oracle universe. PL/SQL combine programming procedural instructions and allows the creation of programs that operates directly on database scenario.
T-SQL is Microsoft product align SQL patterns, with some peculiarities. So, feel free to test your limits.
If you want to start with a file you can do this
[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName
Temp files should be stored in the Windows Temp Folder. Based on the answer from Rod you can use the following one liner to create a 5 GB temp file which returns the filename
[System.IO.Path]::GetTempFileName() | % { [System.IO.File]::Create($_).SetLength(5gb).Close;$_ } | ? { $_ }
Explanation:
[System.IO.Path]::GetTempFileName()
generates a random filename with random extension in the Windows Temp Folder[System.IO.File]::Create($_)
which creates the file.SetLength(5gb)
. I was a bit surprised to discover, that PowerShell supports Byte Conversion, which is really helpful..close
to allow other applications to access it;$_
the filename is returned and with | ? { $_ }
it is ensured that only the filename is returned and not the empty string returned by [System.IO.File]::Create($_)
The following is set to work with IAsyncEnumerable
but can be modified to use IEnumerable
by just changing the type and removing the "await" on the foreach
. It's far more appropriate for large sets of data than creating countless parallel tasks and then awaiting them all.
public static async Task ForEachAsyncConcurrent<T>(this IAsyncEnumerable<T> enumerable, Func<T, Task> action, int maxDegreeOfParallelism, int? boundedCapacity = null)
{
ActionBlock<T> block = new ActionBlock<T>(
action,
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
BoundedCapacity = boundedCapacity ?? maxDegreeOfParallelism * 3
});
await foreach (T item in enumerable)
{
await block.SendAsync(item).ConfigureAwait(false);
}
block.Complete();
await block.Completion;
}
Example.
This runs on cscript.exe, on windows.
// define the Car class
(function() {
// makeClass - By John Resig (MIT Licensed)
// Allows either new User() or User() to be employed for construction.
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, (args && args.callee) ? args : arguments );
} else
return new arguments.callee( arguments );
};
}
Car = makeClass();
Car.prototype.init = function(make, model, price, topSpeed, weight) {
this.make = make;
this.model = model;
this.price = price;
this.weight = weight;
this.topSpeed = topSpeed;
};
})();
// create a list of cars
var autos = [
new Car("Chevy", "Corvair", 1800, 88, 2900),
new Car("Buick", "LeSabre", 31000, 138, 3700),
new Car("Toyota", "Prius", 24000, 103, 3200),
new Car("Porsche", "911", 92000, 155, 3100),
new Car("Mercedes", "E500", 67000, 145, 3800),
new Car("VW", "Passat", 31000, 135, 3700)
];
// a list of sorting functions
var sorters = {
byWeight : function(a,b) {
return (a.weight - b.weight);
},
bySpeed : function(a,b) {
return (a.topSpeed - b.topSpeed);
},
byPrice : function(a,b) {
return (a.price - b.price);
},
byModelName : function(a,b) {
return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
},
byMake : function(a,b) {
return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
}
};
function say(s) {WScript.Echo(s);}
function show(title)
{
say ("sorted by: "+title);
for (var i=0; i < autos.length; i++) {
say(" " + autos[i].model);
}
say(" ");
}
autos.sort(sorters.byWeight);
show("Weight");
autos.sort(sorters.byModelName);
show("Name");
autos.sort(sorters.byPrice);
show("Price");
You can also make a general sorter.
var byProperty = function(prop) {
return function(a,b) {
if (typeof a[prop] == "number") {
return (a[prop] - b[prop]);
} else {
return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
}
};
};
autos.sort(byProperty("topSpeed"));
show("Top Speed");
Before asking questions of this kind, please check MSDN documentation.
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).
int a = 5;
int b = 3;
int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2
Codeproject has a complete solution for this:
http://www.codeproject.com/Articles/17241/Capturing-the-Enter-key-to-cause-a-button-click
and like the article says: "decide which solution best fits your needs"
=================== EDITED ANSWER ============================
The link mentioned above, talks about two ways of capturing the "Enter Key" event:
Javascript (bind the onKeyPress event to the object and create a javascript function to check which key was pressed and do your logic)
_Page_Load in code behind:_
//Add the javascript so we know where we want the enter key press to go
if (!IsPostBack)
{
txtboxFirstName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
txtboxLastName.Attributes.Add("onKeyPress",
"doClick('" + btnSearch.ClientID + "',event)");
}
Javascript code:
<SCRIPT type=text/javascript>
function doClick(buttonName,e)
{
//the purpose of this function is to allow the enter key to
//point to the correct button to click.
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if (key == 13)
{
//Get the button the user wants to have clicked
var btn = document.getElementById(buttonName);
if (btn != null)
{ //If we find the button click it
btn.click();
event.keyCode = 0
}
}
}
</SCRIPT>
Panel Control
<asp:Panel ID="panSearch" runat="server" DefaultButton="btnSearch2" Width="100%" >
<asp:TextBox ID="txtboxFirstName2" runat="server" ></asp:TextBox>
</asp:Panel>
Quoting:
Notice that the Panel tag has a property called DefaultButton. You set this property to the button ID of the button you want to be clicked on an Enter key press event. So any text box inside of the Panel will direct its Enter key press to the button set in the DefaultButton property of the Panel
You can use following function:
function extract_numbers($string)
{
preg_match_all('/([\d]+)/', $string, $match);
return $match[0];
}
2015-03-30: Edited - Missing information has been added
To retrieve the current directory you can use the dynamic %cd%
variable that holds the current active directory
set "curpath=%cd%"
This generates a value with a ending backslash for the root directory, and without a backslash for the rest of directories. You can force and ending backslash for any directory with
for %%a in ("%cd%\") do set "curpath=%%~fa"
Or you can use another dynamic variable: %__CD__%
that will return the current active directory with an ending backslash.
Also, remember the %cd%
variable can have a value directly assigned. In this case, the value returned will not be the current directory, but the assigned value. You can prevent this with a reference to the current directory
for %%a in (".\") do set "curpath=%%~fa"
Up to windows XP, the %__CD__%
variable has the same behaviour. It can be overwritten by the user, but at least from windows 7 (i can't test it on Vista), any change to the %__CD__%
is allowed but when the variable is read, the changed value is ignored and the correct current active directory is retrieved (note: the changed value is still visible using the set
command).
BUT all the previous codes will return the current active directory, not the directory where the batch file is stored.
set "curpath=%~dp0"
It will return the directory where the batch file is stored, with an ending backslash.
BUT this will fail if in the batch file the shift
command has been used
shift
echo %~dp0
As the arguments to the batch file has been shifted, the %0
reference to the current batch file is lost.
To prevent this, you can retrieve the reference to the batch file before any shifting, or change the syntax to shift /1
to ensure the shift operation will start at the first argument, not affecting the reference to the batch file. If you can not use any of this options, you can retrieve the reference to the current batch file in a call to a subroutine
@echo off
setlocal enableextensions
rem Destroy batch file reference
shift
echo batch folder is "%~dp0"
rem Call the subroutine to get the batch folder
call :getBatchFolder batchFolder
echo batch folder is "%batchFolder%"
exit /b
:getBatchFolder returnVar
set "%~1=%~dp0" & exit /b
This approach can also be necessary if when invoked the batch file name is quoted and a full reference is not used (read here).
Use !(window.ActiveXObject) && "ActiveXObject" in window
to detect IE11 explicitly.
To detect any IE (pre-Edge, "Trident") version, use "ActiveXObject" in window
instead.
A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.
To do this you use an outer join:
select tablea.code, tablea.name, tableb.location from tablea left outer join
tableb on tablea.code = tableb.code
Another option is the lubridate
package:
library(lubridate)
x <- 15103
as_date(x, origin = lubridate::origin)
"2011-05-09"
y <- 1442866615
as_datetime(y, origin = lubridate::origin)
"2015-09-21 20:16:55 UTC"
From the docs:
Origin is the date-time for 1970-01-01 UTC in POSIXct format. This date-time is the origin for the numbering system used by POSIXct, POSIXlt, chron, and Date classes.
or an ORACLE version:
delete
from table_name
where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy')
if you take this problem without any change on your project as like as me, you need change your web.config that placed in View Folder. just write new line by Enter or Remove an empty line . then save your web.config and rebuild. my problem solved with this solution
The main problem, of course, is that a DLL file is missing, or, even more likely, corrupt. If this is the case, then I have some pretty good ideas (especially if you've downloaded and installed a DLL manually!)...
TLDR: Delete every manually copy/pasted DLL you've done, uninstall old redistributable installs, and reinstall new redistributables for both 32-bit and 64-bit installs.
What To Do
This solution of copying/pasting missing DLL's into system32
, etc., used to work since I can remember in the 1990's, but it doesn't seem to work anymore (2020). So if you run into this problem recently, I suggest:
windows\system32
and windows\SysWOW64
, delete all files that match ms*.dll
, that the operating system will allow you delete as admin.How You Know It's Working
There's a lot of variation in coders experiencing this, so, the idea that there's one single, possible solution is often discarded, but let's be positive!
ms*.dll
files worked, then you will no longer get an error about error code 0xc000007b
. Instead, you'll get a message about a missing .dll
. This tells you that you're hitting the right code path!system32
and SysWO64
folders. For instance: MSVCR120.dll
, MSVCR140.dll
, MSVCR100.dll
, MSVCP100.dll
, MSVCP120.dll
, MSVCP140.dll
, and friends.Last, Possible Best Chances
Sometimes things don't work according to plan (as we all in the Windows world know). You can also try the following!
.NET Framework
installations. You'll see a small installation go by..NET Framework
, and click "okay". If this works, you'll see a "installing and updating .NET framework" message that takes maybe a minute or so to go by. Once this is done, I recommend a reboot again.Good luck!
The easiest way is start the simulator from the Xcode
, and then on the dock, Ctrl
+ Click
on the icon and select Keep in Dock
In Java its Webelement.getText() . Not sure about python.
DATEPART(yyyy, date_column) could be used to extract year. In general, DATEPART function is used to extract specific portions of a date value.
Using Swift 2.1+
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("settingsVC") as! SettingsViewController
self.presentViewController(vc, animated: true, completion: nil)
git pull --rebase origin master
git push origin master
git push -f origin master
Warning git push -f origin master
Loading an excel file without explicitly naming a sheet but instead giving the number of the sheet order (often one will simply load the first sheet) goes like:
import pandas as pd
myexcel = pd.ExcelFile("C:/filename.xlsx")
myexcel = myexcel.parse(myexcel.sheet_names[0])
Since .sheet_names
returns a list of sheet names, it is easy to load one or more sheets by simply calling the list element(s).
If I understand you correctly, you need to use -SearchBase:
Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *
Note that Get-ADUser defaults to using
-SearchScope Subtree
so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
Probably it's not be correct, and a little bit longer, but I solved this problem (Android Studio) by using this:
System.out.println("Some text here");
Like this:
try {
...code here...
} catch(Exception e) {
System.out.println("Error desc: " + e.getMessage());
}
You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:
var table = document.createElement('table');
for (var i = 1; i < 4; i++){
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var text1 = document.createTextNode('Text1');
var text2 = document.createTextNode('Text2');
td1.appendChild(text1);
td2.appendChild(text2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
}
document.body.appendChild(table);
You are probably seeking:
ActiveRecord::Base.connection.tables
and
ActiveRecord::Base.connection.columns('projects').map(&:name)
You should probably wrap them in shorter syntax inside your .irbrc
.
Building on Ravinders solution, this code stops the form being submitted. It might be wise to check the extension at the server-side too. So you don't get hackers uploading anything they want.
<script>
var valid = false;
function validate_fileupload(input_element)
{
var el = document.getElementById("feedback");
var fileName = input_element.value;
var allowed_extensions = new Array("jpg","png","gif");
var file_extension = fileName.split('.').pop();
for(var i = 0; i < allowed_extensions.length; i++)
{
if(allowed_extensions[i]==file_extension)
{
valid = true; // valid file extension
el.innerHTML = "";
return;
}
}
el.innerHTML="Invalid file";
valid = false;
}
function valid_form()
{
return valid;
}
</script>
<div id="feedback" style="color: red;"></div>
<form method="post" action="/image" enctype="multipart/form-data">
<input type="file" name="fileName" accept=".jpg,.png,.bmp" onchange="validate_fileupload(this);"/>
<input id="uploadsubmit" type="submit" value="UPLOAD IMAGE" onclick="return valid_form();"/>
</form>
Although, @Tomasz is absolutely right there is another way:
@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
try {
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
} catch (IOException ex) {
...
}
}
but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the cumulative distribution function (cdf
- probability that a random sample X will be less than or equal to x) for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796
Which can be simplified for the standard normal distribution (mu = 0
and sigma = 1
):
NormalDist().cdf(1.96)
# 0.9750021048517796
NormalDist().cdf(-1.96)
# 0.024997895148220428
My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.
This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.
If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.
@EdSpencer is correct. If you have a lot of elements and you use ng-if to only instantiate the relevant ones, you are saving resources. @CodeHater is also somewhat correct, if you are going to remove and show an element very often, hiding it instead of removing it could improve performance.
The main use case I find for ng-if is that it allows me to cleanly validate and eliminte an element if the contents is illegal. For instance I could reference to a null image name variable and that will throw an error but if I ng-if and check if it's null, it's all good. If I did an ng-show, the error would still fire.
In WAMP, right click on WAMP tray icon then change the port from 3308 to 3306 like this:
const format1 = "YYYY-MM-DD HH:mm:ss"
const format2 = "YYYY-MM-DD"
var date1 = new Date("2020-06-24 22:57:36");
var date2 = new Date();
dateTime1 = moment(date1).format(format1);
dateTime2 = moment(date2).format(format2);
document.getElementById("demo1").innerHTML = dateTime1;
document.getElementById("demo2").innerHTML = dateTime2;
_x000D_
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script src="https://momentjs.com/downloads/moment.js"></script>
</body>
</html>
_x000D_
Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)
Example:
position:absolute;
From ?read.table
: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.
So, perhaps your data file isn't clean. Being more specific will help the data import:
d = read.table("foobar.txt",
sep="\t",
col.names=c("id", "name"),
fill=FALSE,
strip.white=TRUE)
will specify exact columns and fill=FALSE
will force a two column data frame.
Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47
MySQLWorkbench 8.0.11 for macOS addresses this. I can establish connection with root password protected mysql instance running in docker.
might want to try something as simple as below in the command line:
sed -n '$=' filename
or
wc -l filename
It is simple to calculate by diagramming function calls. Simply add the function calls for each value of n and look at how the number grows.
The Big O is O(Z^n) where Z is the golden ratio or about 1.62.
Both the Leonardo numbers and the Fibonacci numbers approach this ratio as we increase n.
Unlike other Big O questions there is no variability in the input and both the algorithm and implementation of the algorithm are clearly defined.
There is no need for a bunch of complex math. Simply diagram out the function calls below and fit a function to the numbers.
Or if you are familiar with the golden ratio you will recognize it as such.
This answer is more correct than the accepted answer which claims that it will approach f(n) = 2^n. It never will. It will approach f(n) = golden_ratio^n.
2 (2 -> 1, 0)
4 (3 -> 2, 1) (2 -> 1, 0)
8 (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
14 (5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
22 (6 -> 5, 4)
(5 -> 4, 3) (4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
(3 -> 2, 1) (2 -> 1, 0)
(4 -> 3, 2) (3 -> 2, 1) (2 -> 1, 0)
(2 -> 1, 0)
There might be some edge case where you have a vector access inside an inline function inside an inline function, where you've gone beyond what the compiler will inline and it will force a function call. That would be so rare as to not be worth worrying about - in general I would agree with litb.
I'm surprised nobody has mentioned this yet - don't worry about performance until it has been proven to be a problem, then benchmark.
In Sql Server
You can do this using cross apply
Select
ColumnA,
ColumnB,
c.calccolumn1 As calccolumn1,
c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c
This did the job for me:
git gc --prune=now
select
@selectoneCount = case @Temp
when 1 then (@selectoneCount+1)
when 2 then (@selectoneCount+1)
end
select @selectoneCount
This is probably the longest process to make a singleton in typescript, but in larger applications is the one that has worked better for me.
First you need a Singleton class in, let's say, "./utils/Singleton.ts":
module utils {
export class Singleton {
private _initialized: boolean;
private _setSingleton(): void {
if (this._initialized) throw Error('Singleton is already initialized.');
this._initialized = true;
}
get setSingleton() { return this._setSingleton; }
}
}
Now imagine you need a Router singleton "./navigation/Router.ts":
/// <reference path="../utils/Singleton.ts" />
module navigation {
class RouterClass extends utils.Singleton {
// NOTICE RouterClass extends from utils.Singleton
// and that it isn't exportable.
private _init(): void {
// This method will be your "construtor" now,
// to avoid double initialization, don't forget
// the parent class setSingleton method!.
this.setSingleton();
// Initialization stuff.
}
// Expose _init method.
get init { return this.init; }
}
// THIS IS IT!! Export a new RouterClass, that no
// one can instantiate ever again!.
export var Router: RouterClass = new RouterClass();
}
Nice!, now initialize or import wherever you need:
/// <reference path="./navigation/Router.ts" />
import router = navigation.Router;
router.init();
router.init(); // Throws error!.
The nice thing about doing singletons this way is that you still use all the beauty of typescript classes, it gives you nice intellisense, the singleton logic keeps someway separated and it's easy to remove if needed.