I have the similar problem and fixed it by temporarily disabling my antivirus(Kaspersky Free 18.0.0.405). This AV has HTTPS interception module that automatically self-sign all certificates it finds in HTTPS responses.
Wget from Cygwin does not know anything about AV root certificate, so when it finds that website's certificate was signed with non trust certificate it prints that error.
To fix this permanently without disabling AV you should copy the AV root certificate from Windows certificate store to /etc/pki/ca-trust/source/anchors
as .pem file(base64 encoding) and run update-ca-trust
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Usually the process is the other way around. Do not go looking for situations where to use design patterns, look for code that can be optimized. When you have code that you think is not structured correctly. try to find a design pattern that will solve the problem.
Design patterns are meant to help you solve structural problems, do not go design your application just to be able to use design patterns.
If you're trying to run a program using a scripting language, you may need to include the full path of the scripting language and the file to execute. For example:
exec('/usr/local/bin/node /usr/local/lib/node_modules/uglifycss/uglifycss in.css > out.css');
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
You need to know your commit hash from the commit you want to revert to. You can get it from a GitHub URL like: https://github.com/your-organization/your-project/commits/master
Let's say the hash from the commit (where you want to go back to) is "99fb454" (long version "99fb45413eb9ca4b3063e07b40402b136a8cf264"), then all you have to do is:
git reset --hard 99fb45413eb9ca4b3063e07b40402b136a8cf264
git push --force
Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.
The for loop you specified is absolutely correct.
Although i will do all the loops for you once again.
int sum = 0;
// for loop
for (int i = 1; i<= 100; i++){
sum = sum + i;
}
System.out.println(sum);
// while loop
sum = 0;
int j = 1;
while(j<=100){
sum = sum + j;
j++;
}
System.out.println(sum);
// do while loop
sum = 0;
j = 1;
do{
sum = sum + j;
j++;
}
while(j<=100);
System.out.println(sum);
In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.
Much like setState in Class components created by extending React.Component
or React.PureComponent
, the state update using the updater provided by useState
hook is also asynchronous, and will not be reflected immediately.
Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.
Even if you add a setTimeout
the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout
will still use the value from its previous closure and not the updated one.
setMovies(result);
console.log(movies) // movies here will not be updated
If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate
in class components since the setter returned by useState doesn't have a callback pattern
useEffect(() => {
// action on update of movies
}, [movies]);
As far as the syntax to update state is concerned, setMovies(result)
will replace the previous movies
value in the state with those available from the async request.
However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like
setMovies(prevMovies => ([...prevMovies, ...result]));
var consolidatedChildren =
from c in children
group c by new
{
c.School,
c.Friend,
c.FavoriteColor,
} into gcs
select new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
};
var consolidatedChildren =
children
.GroupBy(c => new
{
c.School,
c.Friend,
c.FavoriteColor,
})
.Select(gcs => new ConsolidatedChild()
{
School = gcs.Key.School,
Friend = gcs.Key.Friend,
FavoriteColor = gcs.Key.FavoriteColor,
Children = gcs.ToList(),
});
Scenario 1 - you don't have a data-source for the items
You can just populate the ComboBox with static values as follows -
From XAML:
<ComboBox Height="23" Name="comboBox1" Width="120">
<ComboBoxItem Content="X"/>
<ComboBoxItem Content="Y"/>
<ComboBoxItem Content="Z"/>
</ComboBox>
Or, from CodeBehind:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("X");
comboBox1.Items.Add("Y");
comboBox1.Items.Add("Z");
}
Scenario 2.a - you have a data-source, and the items never get changed
You can use the data-source to populate the ComboBox. Any IEnumerable
type can be used as the data-source. You need to assign it to the ItemsSource
property of the ComboBox and that'll do just fine (it's up to you how you populate the IEnumerable
).
Scenario 2.b - you have a data-source, and the items might get changed
You should use an ObservableCollection<T>
as the data-source and assign it to the ItemsSource
property of the ComboBox (it's up to you how you populate the ObservableCollection<T>
). Using an ObservableCollection<T>
ensures that whenever an item is added to or removed from the data-source, the change will reflect immediately on the UI.
IETF Open Standards RFC 5321 2.4. General Syntax Principles and Transaction Model
SMTP implementations MUST take care to preserve the case of mailbox local-parts. In particular, for some hosts, the user "smith" is different from the user "Smith".
Mailbox domains follow normal DNS rules and are hence not case sensitive
First clear the temporary files in Windows system, then restart your system.
Run > %temp%
> delete all files
Open the developer setting and click console and type the following
JSON.parse(document.getElementById('jupyter-config-data').textContent).token
Then try saving the Notebook. The notebook that was not saving previously will save now.
The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.
You may wish to review a simple example at:
Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)
For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:
@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=
rem Go to the label with the parameter you selected
goto :config_%1
REM This next line is just to go to end of file
REM in case that the parameter %1 is not set
goto :end
REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end
:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end
:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end
:end
After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.
Example test.bat
@echo off
rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
call config.bat animals
echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%
rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%
call config.bat color
echo His lucky color is %first_color% even if %second_color% is also nice.
echo.
pause
Hope it helps the way others help me in here with their answers.
A short version of the above:
config.bat
@echo off
set config_all_selected=
goto :config_%1
goto :end
:config_all
set config_all_selected=1
:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end
:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end
:end
test.bat
@echo off
call config.bat size
echo My birthday present had a width of %width% and a height of %height%
call config.bat family
echo %father% and %mother% have a daughter named %daughter%
echo.
pause
Good day.
You can also use wget to »untar it inline«. Simply specify stdout as the output file (-O -
):
wget --no-check-certificate https://github.com/pinard/Pymacs/tarball/v0.24-beta2 -O - | tar xz
Here is a one liner (replace 3000 with a port or a config variable):
kill $(lsof -t -i:3000)
A
and B
reference the same object, so A.a
and B.a
reference the same property of the same object.
Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.
There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?
So have a look at the following, it's a slightly different approach to others.
/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
var o, prop, type;
if (typeof source != 'object' || source === null) {
// What do to with functions, throw an error?
o = source;
return o;
}
o = new source.constructor();
for (prop in source) {
if (source.hasOwnProperty(prop)) {
type = typeof source[prop];
if (deep && type == 'object' && source[prop] !== null) {
o[prop] = copy(source[prop]);
} else {
o[prop] = source[prop];
}
}
}
return o;
}
Worked a day for this project. It maybe useful for u. I compressed and combined both Network and GPS. Plug and play directly in MainActivity.java (There are some DIY function for display result)
///////////////////////////////////
////////// LOCATION PACK //////////
//
// locationManager: (LocationManager) for getting LOCATION_SERVICE
// osLocation: (Location) getting location data via standard method
// dataLocation: class type storage locztion data
// x,y: (Double) Longtitude, Latitude
// location: (dataLocation) variable contain absolute location info. Autoupdate after run locationStart();
// AutoLocation: class help getting provider info
// tmLocation: (Timer) for running update location over time
// LocationStart(int interval): start getting location data with setting interval time cycle in milisecond
// LocationStart(): LocationStart(500)
// LocationStop(): stop getting location data
//
// EX:
// LocationStart(); cycleF(new Runnable() {public void run(){bodyM.text("LOCATION \nLatitude: " + location.y+ "\nLongitude: " + location.x).show();}},500);
//
LocationManager locationManager;
Location osLocation;
public class dataLocation {double x,y;}
dataLocation location=new dataLocation();
public class AutoLocation extends Activity implements LocationListener {
@Override public void onLocationChanged(Location p1){}
@Override public void onStatusChanged(String p1, int p2, Bundle p3){}
@Override public void onProviderEnabled(String p1){}
@Override public void onProviderDisabled(String p1){}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,0,0,this);
if (locationManager != null) {
osLocation = locationManager.getLastKnownLocation(provider);
return osLocation;
}
}
return null;
}
}
Timer tmLocation=new Timer();
public void LocationStart(int interval){
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
final AutoLocation autoLocation = new AutoLocation();
tmLocation=cycleF(new Runnable() {public void run(){
Location nwLocation = autoLocation.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
location.y = nwLocation.getLatitude();
location.x = nwLocation.getLongitude();
} else {
//bodym.text("NETWORK_LOCATION is loading...").show();
}
Location gpsLocation = autoLocation.getLocation(LocationManager.GPS_PROVIDER);
if (gpsLocation != null) {
location.y = gpsLocation.getLatitude();
location.x = gpsLocation.getLongitude();
} else {
//bodym.text("GPS_LOCATION is loading...").show();
}
}}, interval);
}
public void LocationStart(){LocationStart(500);};
public void LocationStop(){stopCycleF(tmLocation);}
//////////
///END//// LOCATION PACK //////////
//////////
/////////////////////////////
////////// RUNTIME //////////
//
// Need library:
// import java.util.*;
//
// delayF(r,d): execute runnable r after d millisecond
// Halt by execute the return: final Runnable rn=delayF(...); (new Handler()).post(rn);
// cycleF(r,i): execute r repeatedly with i millisecond each cycle
// stopCycleF(t): halt execute cycleF via the Timer return of cycleF
//
// EX:
// delayF(new Runnable(){public void run(){ sig("Hi"); }},2000);
// final Runnable rn=delayF(new Runnable(){public void run(){ sig("Hi"); }},3000);
// delayF(new Runnable(){public void run(){ (new Handler()).post(rn);sig("Hello"); }},1000);
// final Timer tm=cycleF(new Runnable() {public void run(){ sig("Neverend"); }}, 1000);
// delayF(new Runnable(){public void run(){ stopCycleF(tm);sig("Ended"); }},7000);
//
public static Runnable delayF(final Runnable r, long delay) {
final Handler h = new Handler();
h.postDelayed(r, delay);
return new Runnable(){
@Override
public void run(){h.removeCallbacks(r);}
};
}
public static Timer cycleF(final Runnable r, long interval) {
final Timer t=new Timer();
final Handler h = new Handler();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {h.post(r);}
}, interval, interval);
return t;
}
public void stopCycleF(Timer t){t.cancel();t.purge();}
public boolean serviceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
//////////
///END//// RUNTIME //////////
//////////
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
With *nix, usually, you don't need a software to view an .img file. You can use the loop device to mount it and then every file manager to navigate it. Here you can find how. Sometime you need to install some package to manage strange filesystem like squashfs.
You need to use the CSS white-space
attribute.
In particular, white-space: nowrap
and white-space: pre
are the most commonly used values. The first one seems to be what you 're after.
Here's code that filters out invalid fields:
var ints = from field in s1.Split(';').Where((x) => { int dummy; return Int32.TryParse(x, out dummy); })
select Int32.Parse(field);
Inspired by Andrie's answer, you could use identical
and avoid any attribute problems by using the fact that it is the empty set of that class of object and combine it with an element of that class:
attr(a, "foo") <- "bar"
identical(1L, c(a, 1L))
#> [1] TRUE
Or more generally:
is.empty <- function(x, mode = NULL){
if (is.null(mode)) mode <- class(x)
identical(vector(mode, 1), c(x, vector(class(x), 1)))
}
b <- numeric(0)
is.empty(a)
#> [1] TRUE
is.empty(a,"numeric")
#> [1] FALSE
is.empty(b)
#> [1] TRUE
is.empty(b,"integer")
#> [1] FALSE
Table is the obvious choice, but it returns an object of class table
which takes a few annoying steps to transform back into a data.frame
So, if you're OK using dplyr, you use the command tally
:
library(dplyr)
df = data.frame(sex=sample(c("M", "F"), 100000, replace=T), occupation=sample(c('Analyst', 'Student'), 100000, replace=T)
df %>% group_by_all() %>% tally()
# A tibble: 4 x 3
# Groups: sex [2]
sex occupation `n()`
<fct> <fct> <int>
1 F Analyst 25105
2 F Student 24933
3 M Analyst 24769
4 M Student 25193
Make it lowercase first:
.m_title {text-transform: lowercase}
Then make it the first letter uppercase:
.m_title:first-letter {text-transform: uppercase}
"text-transform: capitalize" works for a word; but if you want to use for sentences this solution is perfect.
https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...
<?php
require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
$getID3 = new getID3();
$filename="/fire/My Documents/video/ferrari1.mpg";
$fileinfo = $getID3->analyze($filename);
$width=$fileinfo['video']['resolution_x'];
$height=$fileinfo['video']['resolution_y'];
echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
echo '<pre>';print_r($fileinfo);echo '</pre>';
?>
Here's how to determine a local user:
public bool IsLocalUser()
{
return windowsIdentity.AuthenticationType == "NTLM";
}
You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.
Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:
Why the NTLM Plug-in is Needed
NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.
Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.
By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.
How the Plug-in Works
The Verifier plug detects the following errors:
The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).
The target name in the call to InitializeSecurityContext is NULL.
The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.
The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).
The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.
NTLM Stops
5000 – Application Has Explicitly Selected NTLM Package
Severity – Error
The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.
How to Fix this Error
The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.
APIs(parameter) Used by Application Incorrect Value Correct Value ===================================== =============== ======================== AcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
User nrabinowitz' solution is working great, but I use the keypress
event instead of keyup
. That reduces the latency if the user types slowly.
What about this,
$.fn.extend({
hasClasses: function( selector ) {
var classNamesRegex = new RegExp("( " + selector.replace(/ +/g,"").replace(/,/g, " | ") + " )"),
rclass = /[\n\t\r]/g,
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && classNamesRegex.test((" " + this[i].className + " ").replace(rclass, " "))) {
return true;
}
}
return false;
}
});
Easy to use,
if ( $("selector").hasClasses("class1, class2, class3") ) {
//Yes It does
}
And It seems to be faster, http://jsperf.com/hasclasstest/7
As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.
There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.
Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:
The static
keyword modifies the lifecycle of a method or variable within a class. A static
method or variable is created at the time a class is loaded. A method or variable that is not declared as static
is created only when the class is instantiated as an object for example by using the new
operator.
The lifecycle of a class, in broad terms, is:
new
operator using the class to make an instance of the class as an actual object and then when done with the object In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main()
. Since the method must exist whether the class containing the main method has been instantiated or not, the main()
method must be declared with the static
modifier so that as soon as the class is loaded, the main()
method is available.
The result is that when you start your Java application by a command line such as java helloworld
a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld
class that is called main(String [] args)
. this method must be static
so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main()
method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static
modifier. Once your Java program has started with the main()
function you can then use any variables or methods that have the modifier of static
since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main()
method which do not have the static
modifier can not be used until an instance of the class has been created as an object within the main()
method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static
modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
If you need a simple working solution, try using DefaultTableModel.
If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.
For example, if you have used Vector, then it may be something like this:
public class SimpleTableModel extends AbstractTableModel {
private Vector<String> columnNames = new Vector<String>();
// Each value in the vector is a row; String[] - row data;
private Vector<String[]> data = new Vector<String[]>();
...
public String getValueAt(int row, int col) {
return data.get(row)[col];
}
...
public void removeRow(int row) {
data.removeElementAt(row);
}
}
If you have used List, then it would be very much alike:
// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();
public void removeRow(int row) {
data.remove(row);
}
HashMap:
//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();
public void removeRow(Integer row) {
data.remove(row);
}
And if you are using arrays like this one
String[][] data = { { "a", "b" }, { "c", "d" } };
then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.
For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
Manifest.MF contains information about the files contained in the JAR file.
Whenever a JAR file is created a default manifest.mf file is created inside META-INF folder and it contains the default entries like this:
Manifest-Version: 1.0
Created-By: 1.7.0_06 (Oracle Corporation)
These are entries as “header:value” pairs. The first one specifies the manifest version and second one specifies the JDK version with which the JAR file is created.
Main-Class header: When a JAR file is used to bundle an application in a package, we need to specify the class serving an entry point of the application. We provide this information using ‘Main-Class’ header of the manifest file,
Main-Class: {fully qualified classname}
The ‘Main-Class’ value here is the class having main method. After specifying this entry we can execute the JAR file to run the application.
Class-Path header: Most of the times we need to access the other JAR files from the classes packaged inside application’s JAR file. This can be done by providing their fully qualified paths in the manifest file using ‘Class-Path’ header,
Class-Path: {jar1-name jar2-name directory-name/jar3-name}
This header can be used to specify the external JAR files on the same local network and not inside the current JAR.
Package version related headers: When the JAR file is used for package versioning the following headers are used as specified by the Java language specification:
Headers in a manifest
Header | Definition
-------------------------------------------------------------------
Name | The name of the specification.
Specification-Title | The title of the specification.
Specification-Version | The version of the specification.
Specification-Vendor | The vendor of the specification.
Implementation-Title | The title of the implementation.
Implementation-Version | The build number of the implementation.
Implementation-Vendor | The vendor of the implementation.
Package sealing related headers:
We can also specify if any particular packages inside a JAR file should be sealed meaning all the classes defined in that package must be archived in the same JAR file. This can be specified with the help of ‘Sealed’ header,
Name: {package/some-package/} Sealed:true
Here, the package name must end with ‘/’.
Enhancing security with manifest files:
We can use manifest files entries to ensure the security of the web application or applet it packages with the different attributes as ‘Permissions’, ‘Codebae’, ‘Application-Name’, ‘Trusted-Only’ and many more.
META-INF folder:
This folder is where the manifest file resides. Also, it can contain more files containing meta data about the application. For example, in an EJB module JAR file, this folder contains the EJB deployment descriptor for the EJB module along with the manifest file for the JAR. Also, it contains the xml file containing mapping of an abstract EJB references to concrete container resources of the application server on which it will be run.
Reference:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
You can read Google Sheets spreadsheets data in JavaScript by using the RGraph sheets connector:
https://www.rgraph.net/canvas/docs/import-data-from-google-sheets.html
Initially (a few years ago) this relied on some RGraph functions to work its magic - but now it can work standalone (ie not requiring the RGraph common library).
Some example code (this example makes an RGraph chart):
<!-- Include the sheets library -->
<script src="RGraph.common.sheets.js"></script>
<!-- Include these two RGraph libraries to make the chart -->
<script src="RGraph.common.key.js"></script>
<script src="RGraph.bar.js"></script>
<script>
// Create a new RGraph Sheets object using the spreadsheet's key and
// the callback function that creates the chart. The RGraph.Sheets object is
// passed to the callback function as an argument so it doesn't need to be
// assigned to a variable when it's created
new RGraph.Sheets('1ncvARBgXaDjzuca9i7Jyep6JTv9kms-bbIzyAxbaT0E', function (sheet)
{
// Get the labels from the spreadsheet by retrieving part of the first row
var labels = sheet.get('A2:A7');
// Use the column headers (ie the names) as the key
var key = sheet.get('B1:E1');
// Get the data from the sheet as the data for the chart
var data = [
sheet.get('B2:E2'), // January
sheet.get('B3:E3'), // February
sheet.get('B4:E4'), // March
sheet.get('B5:E5'), // April
sheet.get('B6:E6'), // May
sheet.get('B7:E7') // June
];
// Create and configure the chart; using the information retrieved above
// from the spreadsheet
var bar = new RGraph.Bar({
id: 'cvs',
data: data,
options: {
backgroundGridVlines: false,
backgroundGridBorder: false,
xaxisLabels: labels,
xaxisLabelsOffsety: 5,
colors: ['#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5'],
shadow: false,
colorsStroke: 'rgba(0,0,0,0)',
yaxis: false,
marginLeft: 40,
marginBottom: 35,
marginRight: 40,
key: key,
keyBoxed: false,
keyPosition: 'margin',
keyTextSize: 12,
textSize: 12,
textAccessible: false,
axesColor: '#aaa'
}
}).wave();
});
</script>
Assuming that this
is .d
, you can write
$(this).closest('.a');
The closest
method returns the innermost parent of your element that matches the selector.
DECLARE @LastChangeDate as date
SET @LastChangeDate = GETDATE()
Normally, I just want to know if the object is nil or not.
So i use this function that just returns true
when the object entered is valid and false
when its not.
func isNotNil(someObject: Any?) -> Bool {
if someObject is String {
if (someObject as? String) != nil {
return true
}else {
return false
}
}else if someObject is Array<Any> {
if (someObject as? Array<Any>) != nil {
return true
}else {
return false
}
}else if someObject is Dictionary<AnyHashable, Any> {
if (someObject as? Dictionary<String, Any>) != nil {
return true
}else {
return false
}
}else if someObject is Data {
if (someObject as? Data) != nil {
return true
}else {
return false
}
}else if someObject is NSNumber {
if (someObject as? NSNumber) != nil{
return true
}else {
return false
}
}else if someObject is UIImage {
if (someObject as? UIImage) != nil {
return true
}else {
return false
}
}
return false
}
Are you running a real-time antivirus scanner by any chance ? If so, you could try (temporarily) disabling it to see if that is what is accessing the file you are trying to delete. (Chris' suggestion to use Sysinternals process explorer is a good one).
As far as I know, display: inline-block
is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.
You can use reorder
:
qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")
Edit:
To have the tallest bar at the left, you have to use a bit of a kludge:
qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
data=mtcars,geom="bar")
I would expect this to also have negative heights, but it doesn't, so it works!
AlexRobbins' answer worked for me, except that the first two lines need to be in the model (perhaps this was assumed?), and should reference self:
def book_author(self):
return self.book.author
Then the admin part works nicely.
You mean this:
jQuery("input.first").click(function(){
jQuery("input.second").trigger('click');
return false;
});
Here are some helper functions I use:
Array.contains = function (arr, key) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return true;
}
return false;
};
Array.add = function (arr, key, value) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return arr[key] = value;
}
this.push(key);
};
Array.remove = function (arr, key) {
for (var i = arr.length; i--;) {
if (arr[i] === key) return arr.splice(i, 1);
}
};
As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:
enum TShirtSize {
Small,
Medium,
Large
}
var mySize = TShirtSize.Large;
By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.
Listing 6.2 Enumerations with explicit members
enum TShirtSize {
Small = 3,
Medium = 5,
Large = 8
}
var mySize = TShirtSize.Large;
Both of these examples lifted directly out of TypeScript for JavaScript Programmers.
Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:
Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.
enum TShirtSize {
Small: 3,
Medium: 5,
Large: 8
}
var mySize = TShirtSize.Large;
For Angular 5+ Version we can use ngx-order-pipe package
Install package
$ npm install ngx-order-pipe --save
Import in apps module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { OrderModule } from 'ngx-order-pipe';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
OrderModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
use anywhere
<ul>
<li *ngFor="let item of (dummyData | orderBy:'name') ">
{{item.name}}
</li>
</ul>
If you will use Generics and define your map as
Map<String,String> map = new HashMap<String,String>();
then fetching value as
String s = map.get("keyStr");
you wont be required to typecast the map.get() or call toString method to get String value
That's the way the DataReader
works, it's designed to read the database rows one at a time.
while(reader.Read())
{
var value1 = reader.GetValue(0); // On first iteration will be hello
var value2 = reader.GetValue(1); // On first iteration will be hello2
var value3 = reader.GetValue(2); // On first iteration will be hello3
}
Interesting one. I love collecting quotes about quotes handling in cmd/command.
Your particular scripts gets fixed by using %1 instead of "%1" !!!
By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.
There is a performance issue related with the left join as well as full join with large data.
In my opinion this is the best solution:
select [First Name], count(1) e from (select * from [Temp Test Data] union all select * from [Temp Test Data 2]) a group by [First Name] having e = 1
If you're using Visual C#, all you need to do is add a class in Program.cs inheriting Form and change all the inherited class from Form to your class in every Form*.cs.
//Program.cs
public class Forms : Form
{
//Declare your global valuables here.
}
//Form1.cs
public partial class Form1 : Forms //Change from Form to Forms
{
//...
}
Of course, there might be a way to extending the class Form without modifying it. If that's the case, all you need to do is extending it! Since all the forms are inheriting it by default, so all the valuables declared in it will become global automatically! Good luck!!!
I don't know why you should make it so complicated as the others.
The following code is much simpler to understand and about 25% faster than the other solutions who uses the log function (called the function 20 Mio. times with different parameters)
function formatBytes($bytes, $precision = 2) {
$units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
$i = 0;
while($bytes > 1024) {
$bytes /= 1024;
$i++;
}
return round($bytes, $precision) . ' ' . $units[$i];
}
install mbstring and restart your apache:
sudo apt-get install php-mbstring
sudo service apache restart
then remove ; from your php.ini file:
;extension=php_mbstring.dll
to
extension=php_mbstring.dll
If it still doesn't work..remove your php setup, without removing the databases from your phpmyadmin. Reinstall it.
NB: * if you want to remove all, all mention the one you need to.
sudo apt-get remove php*
Then install the php and modules of the php version that you need. here, php 7.1:
sudo apt-get install php7.1 php7.1-cli php7.1-common libapache2-mod-php7.1 php7.1-mysql php7.1-fpm php7.1-curl php7.1-gd php7.1-bz2 php7.1-mcrypt php7.1-json php7.1-tidy php7.1-mbstring php-redis php-memcached
restart your apache and check the php version.
sudo service apache restart
php -v
when all this is done, execute the following command to enable mbstring forcefully and restart your apache.
sudo phpenmod mbstring
sudo service apache restart
Hope it helps. It did to me :)
Something else you could do using raytrace's answer. You could use the stdout of another shell call using backticks to then do some calculations. For instance I wanted to know the file size of the top 100 lines from a couple of files. The original size from wc -c
is in bytes, I want to know kilobytes. Here's what I did:
echo `cat * | head -n 100 | wc -c` / 1024 | bc -l
Use saveAs
on FileSaver.js github project.
FileSaver.js
implements the saveAs()
FileSaver interface in browsers that do not natively support it.
KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python
To get the titles for dates greater than a week ago today, use this:
SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7
Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.
for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }
in some case you can use annotation @Primary.
@Primary
class USA implements Country {}
This way it will be selected as the default autowire candididate, with no need to autowire-candidate on the other bean.
for mo deatils look at Autowiring two beans implementing same interface - how to set default bean to autowire?
RMI is based on Proxy.
Should be possible to cite one for most of the 23 patterns in GoF:
I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
Directly from the GitHub project homepage:
Dapper allow you to pass in IEnumerable and will automatically parameterize your query.
connection.Query<int>(
@"select *
from (select 1 as Id union all select 2 union all select 3) as X
where Id in @Ids",
new { Ids = new int[] { 1, 2, 3 });
Will be translated to:
select *
from (select 1 as Id union all select 2 union all select 3) as X
where Id in (@Ids1, @Ids2, @Ids3)
// @Ids1 = 1 , @Ids2 = 2 , @Ids2 = 3
Use Jquery instead. Add a decimal class to your textbox:
<input type="text" class="decimal" value="" />
Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});?
Check this fiddle: http://jsfiddle.net/2YW8g/
Hope it helps.
In your XML layout:
<Button
android:id="@+id/cancelskill"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_weight="1"
android:background="@drawable/button_border"
android:padding="10dp"
android:text="Cancel"
android:textAllCaps="false"
android:textColor="#ffffff"
android:textSize="20dp" />
In the drawable folder, create a file for the button's border style:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke
android:width="1dp"
android:color="#f43f10" />
</shape>
And in your Activity:
GradientDrawable gd1 = new GradientDrawable();
gd1.setColor(0xFFF43F10); // Changes this drawbale to use a single color instead of a gradient
gd1.setCornerRadius(5);
gd1.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd1);
cancelskill.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelskill.setBackgroundColor(Color.parseColor("#ffffff"));
cancelskill.setTextColor(Color.parseColor("#f43f10"));
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFFFFFFFF); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFFF43F10);
cancelskill.setBackgroundDrawable(gd);
finish();
}
});
I just use an array to achieved multiple requests, hope it helps someone. (Kotlin)
// got all permission
private fun requestPermission(){
var mIndex: Int = -1
var requestList: Array<String> = Array(10, { "" } )
// phone call Permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.CALL_PHONE
}
// SMS Permission
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.SEND_SMS
}
// Access photos Permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.READ_EXTERNAL_STORAGE
}
// Location Permission
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mIndex ++
requestList[mIndex] = Manifest.permission.ACCESS_FINE_LOCATION
}
if(mIndex != -1){
ActivityCompat.requestPermissions(this, requestList, PERMISSIONS_REQUEST_ALL)
}
}
// permission response
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSIONS_REQUEST_ALL -> {
// If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Phone Call permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SMS permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "SMS permission accept.")
}
// permission accept location
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Location permission accept.")
}
} else {
Toast.makeText(mContext, "Permission Failed!", Toast.LENGTH_LONG).show()
}
return
}
}
}
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
I'd like to add that for accessibility, I think you should add focus trigger :
i.e. $("#popover").popover({ trigger: "hover focus" });
CREATE TABLE t (d1 timestamp, d2 timestamp);
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 05:00:00');
INSERT INTO t VALUES ('2010-03-11 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-11 00:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-03-30 13:00:00');
INSERT INTO t VALUES ('2010-03-10 12:00:00', '2010-04-01 13:00:00');
SELECT d2, d1, DATEDIFF(d2, d1) AS diff FROM t;
+---------------------+---------------------+------+
| d2 | d1 | diff |
+---------------------+---------------------+------+
| 2010-03-30 05:00:00 | 2010-03-11 12:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-11 12:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-11 00:00:00 | 19 |
| 2010-03-30 13:00:00 | 2010-03-10 12:00:00 | 20 |
| 2010-04-01 13:00:00 | 2010-03-10 12:00:00 | 22 |
+---------------------+---------------------+------+
5 rows in set (0.00 sec)
yum update
helped me out. After I had
wget: symbol lookup error: wget: undefined symbol: psl_latest
Convert a String to ByteBuffer, then from ByteBuffer back to String using Java:
import java.nio.charset.Charset;
import java.nio.*;
String babel = "obufscate thdé alphebat and yolo!!";
System.out.println(babel);
//Convert string to ByteBuffer:
ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
try{
//Convert ByteBuffer to String
System.out.println(new String(babb.array(), "UTF-8"));
}
catch(Exception e){
e.printStackTrace();
}
Which prints the printed bare string first, and then the ByteBuffer casted to array():
obufscate thdé alphebat and yolo!!
obufscate thdé alphebat and yolo!!
Also this was helpful for me, reducing the string to primitive bytes can help inspect what's going on:
String text = "?????";
//convert utf8 text to a byte array
byte[] array = text.getBytes("UTF-8");
//convert the byte array back to a string as UTF-8
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s);
//forcing strings encoded as UTF-8 as an incorrect encoding like
//say ISO-8859-1 causes strange and undefined behavior
String sISO = new String(array, Charset.forName("ISO-8859-1"));
System.out.println(sISO);
Prints your string interpreted as UTF-8, and then again as ISO-8859-1:
?????
ããã«ã¡ã¯
Working from your jsFiddle example:
The jsFiddle was fine, but you were missing semi-colons at the end of the event.preventDefault() statements.
This works: Revised jsFiddle
jQuery(document).ready(function() {
jQuery(".rec1").click(function(event) {
event.preventDefault();
jQuery('#rec-box').html(jQuery(this).next().html());
});
jQuery(".rec2").click(function(event) {
event.preventDefault();
jQuery('#rec-box2').html(jQuery(this).next().html());
});
});
This is not an answer to the original question. But, as an original question is not a real-world problem it should not be a problem. I tried to explain to a friend what are promises in JavaScript and the difference between promise and callback.
Code below serves as an explanation:
//very basic callback example using setTimeout
//function a is asynchronous function
//function b used as a callback
function a (callback){
setTimeout (function(){
console.log ('using callback:');
let mockResponseData = '{"data": "something for callback"}';
if (callback){
callback (mockResponseData);
}
}, 2000);
}
function b (dataJson) {
let dataObject = JSON.parse (dataJson);
console.log (dataObject.data);
}
a (b);
//rewriting above code using Promise
//function c is asynchronous function
function c () {
return new Promise(function (resolve, reject) {
setTimeout (function(){
console.log ('using promise:');
let mockResponseData = '{"data": "something for promise"}';
resolve(mockResponseData);
}, 2000);
});
}
c().then (b);
Sometimes it happened to me that the method described in the accepted answer didn't work, especially if the separator is a carriage return.
In those cases I solved in this way:
string='first line
second line
third line'
oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"
for line in "${lines[@]}"
do
echo "--> $line"
done
If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.
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...);
You need to await the GetAsync
method. It will then throw a TaskCanceledException
if it has timed out. Additionally, GetStringAsync
and GetStreamAsync
internally handle timeout, so they will NEVER throw.
string baseAddress = "http://localhost:8080/";
var client = new HttpClient()
{
BaseAddress = new Uri(baseAddress),
Timeout = TimeSpan.FromMilliseconds(1)
};
try
{
var s = await client.GetAsync();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException.Message);
}
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android
select
{
-webkit-appearance: none;
}
If you need to you can also add an image that contains the arrow as part of the background.
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
Mid(strYourString, 4)
(i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.
This answer seems relevant since the OP makes reference to a need for a multi-OS solution. This Github help article details available approaches for handling lines endings cross-OS. There are global and per-repo approaches to managing cross-os line endings.
Global approach
Configure Git line endings handling on Linux or OS X:
git config --global core.autocrlf input
Configure Git line endings handling on Windows:
git config --global core.autocrlf true
Per-repo approach:
In the root of your repo, create a .gitattributes
file and define line ending settings for your project files, one line at a time in the following format: path_regex line-ending-settings
where line-ending-settings
is one of the following:
The text
value can be configured further to instruct Git on how to handle line endings for matching files:
text
- Changes line endings to OS native line endings.text eol=crlf
- Converts line endings to CRLF
on checkout.text eol=lf
- Converts line endings to LF
on checkout.text=auto
- Sensible default that leaves line handle up to Git's discretion.Here is the content of a sample .gitattributes file:
# Set the default behavior for all files.
* text=auto
# Normalized and converts to
# native line endings on checkout.
*.c text
*.h text
# Convert to CRLF line endings on checkout.
*.sln text eol=crlf
# Convert to LF line endings on checkout.
*.sh text eol=lf
# Binary files.
*.png binary
*.jpg binary
More on how to refresh your repo after changing line endings settings here. Tldr:
backup your files with Git, delete every file in your repository (except the .git directory), and then restore the files all at once. Save your current files in Git, so that none of your work is lost.
git add . -u
git commit -m "Saving files before refreshing line endings"
Remove the index and force Git to rescan the working directory.
rm .git/index
Rewrite the Git index to pick up all the new line endings.
git reset
Show the rewritten, normalized files.
In some cases, this is all that needs to be done. Others may need to complete the following additional steps:
git status
Add all your changed files back, and prepare them for a commit. This is your chance to inspect which files, if any, were unchanged.
git add -u
It is perfectly safe to see a lot of messages here that read[s] "warning: CRLF will be replaced by LF in file."
Rewrite the .gitattributes file.
git add .gitattributes
Commit the changes to your repository.
git commit -m "Normalize all the line endings"
It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.
There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit()
method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.
CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.
Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.
Note: when it says "B5" in the explanation below, it actually means "B{current_row}", so for C5 it's B5, for C6 it's B6 and so on. Unless you specify $B$5 - then you refer to one specific cell.
This is supported in Google Sheets as of 2015: https://support.google.com/drive/answer/78413#formulas
In your case, you will need to set conditional formatting on B5.
=B5>0.8*C5
.B5
.You can repeat this process to add more colors for the background or text or a color scale.
Even better, make a single rule apply to all rows by using ranges in "Range". Example assuming the first row is a header:
=B2>0.8*C2
.B2:B
.Will be like the previous example but works on all rows, not just row 5.
Ranges can also be used in the "Custom formula is" so you can color an entire row based on their column values.
This is the updated answer for WAMP v3.0.6 and up
> UPDATE mysql.user
> SET authentication_string=PASSWORD('MyNewPass')
> WHERE user='root';
> FLUSH PRIVILEGES;
In MySQL version 5.7.x there is no more password field in the mysql table. It was replaced with authentication_string. (This is for the terminal/CLI)
UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE user='root';
FLUSH PRIVILEGES;
(This if for PHPMyAdmin or any Mysql GUI)
Are you refering to the toggle outlining?
You can do: Control + M then Control + L to toggle all outlining
Check with starting mysql in terminal. Use below command
mysql-ctl start
In my case its worked
Reposting my post from How do I remove diacritics (accents) from a string in .NET?
This method works fine in java (purely for the purpose of removing diacritical marks aka accents).
It basically converts all accented characters into their deAccented counterparts followed by their combining diacritics. Now you can use a regex to strip off the diacritics.
import java.text.Normalizer;
import java.util.regex.Pattern;
public String deAccent(String str) {
String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(nfdNormalizedString).replaceAll("");
}
Simply:
frontend incoming_requsts
bind *:80
bind *:443 ssl crt *path_to_cert*.**pem**
**http-request redirect scheme https unless { ssl_fc }**
default_backend k8s_nodes
it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.
In v.2.x.x , we can use align
and justify
. We have below options for setup the horizontal and vertical alignment.
PROPS align
: 'start','center','end','baseline','stretch'
PRPS justify
: 'start','center','end','space-around','space-between'
<v-container fill-height fluid>
<v-row align="center"
justify="center">
<v-col></v-col>
</v-row>
</v-container>
For more details please refer this vuetify grid-system and you could check here with working codepen demo.
You could use align-center
for layout
and fill-height
for container.
Demo with v1.x.x
new Vue({
el: '#app'
})
_x000D_
.bg{
background: gray;
color: #fff;
font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-container bg fill-height grid-list-md text-xs-center>
<v-layout row wrap align-center>
<v-flex>
Hello I am center to vertically using "align-center".
</v-flex>
</v-layout>
</v-container>
</v-app>
</div>
_x000D_
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:
apt-get install python-dev libxml2 libxml2-dev libxslt-dev
It's just
$(this).val();
I think jQuery is clever enough to know what you need
From the jQuery API: with the setting of dataType
, If none is specified, jQuery will try to infer it with $.parseJSON()
based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType
to json
to convert it automatically.
i think the main things to remember about parsing csv is that it follows some simple rules:
a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns
have a read of this post to see what i am talking about
it's actually very easy to do once you have the hang of it and becomes very useful.
go to kafka/libs folder we can see multiple jars search for something similar kafka_2.11-0.10.1.1.jar.asc in this case the kafka version is 0.10.1.1
List result = new ArrayList();
while (i.hasNext()){
result.add(i.next());
}
This answer is not the answer for the above mentioned question but it is related to same topic and might be useful for people searching for same error.
I faced the same error when I executed below mentioned query.
select OR.* from ORDER_REL_STAT OR
problem with above query was OR is keyword so it was expecting other values when I replaced with some other alias it worked fine.
If you want the time out as well as the date you want Date.toLocaleString()
.
This was direct from my console:
> new Date().toLocaleString()
> "11/10/2016, 11:49:36 AM"
You can then input locale strings and format string to get the precise output you want.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
I have use Elasticsearch for 3 years and Solr for about a month, I feel elasticsearch cluster is quite easy to install as compared to Solr installation. Elasticsearch has a pool of help documents with great explanation. One of the use case I was stuck up with Histogram Aggregation which was available in ES however not found in Solr.
As the documentation clearly states, Character.getNumericValue()
returns the character's value as a digit.
It returns -1
if the character is not a digit.
If you want to get the numeric Unicode code point of a boxed Character
object, you'll need to unbox it first:
int value = (int)c.charValue();
Not an exact answer to your question, but a bit of information: if your device does use NTP for time (eg. if it is a tablet with no 3G or GPS capabilities), the server can be configured in /system/etc/gps.conf
- obviously this file can only be edited with root access, but is viewable on non-rooted devices.
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
On Debian, as well as adding the below lines to my .bash_profile as one of the above answers said. I also had to open up my terminal preferences (Edit -> Profile Preferences -> Command) and enable 'Run command as a login shell' to get it to work.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
Edit: For those on Mac be aware that macOS doesn't read .bashrc on Terminal start, so using .bash_profile is preferable. See Here.
In addition to other good answers here, this explanation made things crystal clear for me:
A buffer is a portion in memory that is used to store a stream of data (characters). These characters sometimes will only get sent to an output device (e.g. monitor) when the buffer is full or meets a certain number of characters. This can cause your system to lag if you just have a few characters to send to an output device. The flush() method will immediately flush the contents of the buffer to the output stream.
In general, it is desirable to avoid arbitrary string comparisons throughout your code. It is better to update the strings in one place and hide the magic string from your app. I provide a category on UIDevice
for that purpose.
For my specific needs I need to know which device I am using without the need to know specifics about networking capability that can be easily retrieved in other ways. So you will find a coarser grained enum
than the ever growing list of devices.
Updating is a matter of adding the device to the enum and the lookup table.
typedef NS_ENUM(NSUInteger, NTNUDeviceType) {
DeviceAppleUnknown,
DeviceAppleSimulator,
DeviceAppleiPhone,
DeviceAppleiPhone3G,
DeviceAppleiPhone3GS,
DeviceAppleiPhone4,
DeviceAppleiPhone4S,
DeviceAppleiPhone5,
DeviceAppleiPhone5C,
DeviceAppleiPhone5S,
DeviceAppleiPhone6,
DeviceAppleiPhone6_Plus,
DeviceAppleiPhone6S,
DeviceAppleiPhone6S_Plus,
DeviceAppleiPhoneSE,
DeviceAppleiPhone7,
DeviceAppleiPhone7_Plus,
DeviceAppleiPodTouch,
DeviceAppleiPodTouch2G,
DeviceAppleiPodTouch3G,
DeviceAppleiPodTouch4G,
DeviceAppleiPad,
DeviceAppleiPad2,
DeviceAppleiPad3G,
DeviceAppleiPad4G,
DeviceAppleiPad5G_Air,
DeviceAppleiPadMini,
DeviceAppleiPadMini2G,
DeviceAppleiPadPro12,
DeviceAppleiPadPro9
};
@interface UIDevice (NTNUExtensions)
- (NSString *)ntnu_deviceDescription;
- (NTNUDeviceType)ntnu_deviceType;
@end
#import <sys/utsname.h>
#import "UIDevice+NTNUExtensions.h"
@implementation UIDevice (NTNUExtensions)
- (NSString *)ntnu_deviceDescription
{
struct utsname systemInfo;
uname(&systemInfo);
return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}
- (NTNUDeviceType)ntnu_deviceType
{
NSNumber *deviceType = [[self ntnu_deviceTypeLookupTable] objectForKey:[self ntnu_deviceDescription]];
return [deviceType unsignedIntegerValue];
}
- (NSDictionary *)ntnu_deviceTypeLookupTable
{
return @{
@"i386": @(DeviceAppleSimulator),
@"x86_64": @(DeviceAppleSimulator),
@"iPod1,1": @(DeviceAppleiPodTouch),
@"iPod2,1": @(DeviceAppleiPodTouch2G),
@"iPod3,1": @(DeviceAppleiPodTouch3G),
@"iPod4,1": @(DeviceAppleiPodTouch4G),
@"iPhone1,1": @(DeviceAppleiPhone),
@"iPhone1,2": @(DeviceAppleiPhone3G),
@"iPhone2,1": @(DeviceAppleiPhone3GS),
@"iPhone3,1": @(DeviceAppleiPhone4),
@"iPhone3,3": @(DeviceAppleiPhone4),
@"iPhone4,1": @(DeviceAppleiPhone4S),
@"iPhone5,1": @(DeviceAppleiPhone5),
@"iPhone5,2": @(DeviceAppleiPhone5),
@"iPhone5,3": @(DeviceAppleiPhone5C),
@"iPhone5,4": @(DeviceAppleiPhone5C),
@"iPhone6,1": @(DeviceAppleiPhone5S),
@"iPhone6,2": @(DeviceAppleiPhone5S),
@"iPhone7,1": @(DeviceAppleiPhone6_Plus),
@"iPhone7,2": @(DeviceAppleiPhone6),
@"iPhone8,1" :@(DeviceAppleiPhone6S),
@"iPhone8,2" :@(DeviceAppleiPhone6S_Plus),
@"iPhone8,4" :@(DeviceAppleiPhoneSE),
@"iPhone9,1" :@(DeviceAppleiPhone7),
@"iPhone9,3" :@(DeviceAppleiPhone7),
@"iPhone9,2" :@(DeviceAppleiPhone7_Plus),
@"iPhone9,4" :@(DeviceAppleiPhone7_Plus),
@"iPad1,1": @(DeviceAppleiPad),
@"iPad2,1": @(DeviceAppleiPad2),
@"iPad3,1": @(DeviceAppleiPad3G),
@"iPad3,4": @(DeviceAppleiPad4G),
@"iPad2,5": @(DeviceAppleiPadMini),
@"iPad4,1": @(DeviceAppleiPad5G_Air),
@"iPad4,2": @(DeviceAppleiPad5G_Air),
@"iPad4,4": @(DeviceAppleiPadMini2G),
@"iPad4,5": @(DeviceAppleiPadMini2G),
@"iPad4,7":@(DeviceAppleiPadMini),
@"iPad6,7":@(DeviceAppleiPadPro12),
@"iPad6,8":@(DeviceAppleiPadPro12),
@"iPad6,3":@(DeviceAppleiPadPro9),
@"iPad6,4":@(DeviceAppleiPadPro9)
};
}
@end
In your code j is Already json data and j['places'] is list not dict.
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
for each in j['places']:
print each['latitude']
You can cast the numerator or the denominator to float...
int operations usually return int, so you have to change one of the operanding numbers.
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");
NB: the syntax is:
SELECT * FROM table WHERE column IN('value1','value2','value3')
I think this would be best explained by the following picture:
To initialize the above, one would type:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
I know this is a Java question, but if you're using Kotlin you can do this quite nicely:
val uri = request.run {
if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}
If you need to change a file just once. You should prefer making the change locally and build a new docker image with this file.
Say in a docker image, you need to change a file named myFile.xml under /path/to/docker/image/. So, you need to do.
FROM docker-repo:tag
ADD myFile.xml /path/to/docker/image/
Then build your own docker image with docker build -t docker-repo:v-x.x.x .
Then use your newly build docker image.
This one worked in my python script:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);
This should work. Your code works for me, like for Tamás and Manoj Govindan. It looks like you could try to update Matplotlib. If you can't update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with matplotlib.use()
could help.
The Diodeus's answer is awesome, but it prevent you to add a onClick function, it'll never run hold function if you put an onclick. And the Razzak's answer is almost perfect, but it run hold function only on mouseup, and generally, the function runs even if user keep holding.
So, I joined both, and made this:
$(element).on('click', function () {
if(longpress) { // if detect hold, stop onclick function
return false;
};
});
$(element).on('mousedown', function () {
longpress = false; //longpress is false initially
pressTimer = window.setTimeout(function(){
// your code here
longpress = true; //if run hold function, longpress is true
},1000)
});
$(element).on('mouseup', function () {
clearTimeout(pressTimer); //clear time on mouseup
});
Just to add a non-regex solution:
'(' + $myString.Split('()')[1] + ')'
This splits the string at the parentheses and takes the string from the array with the program name in it.
If you don't need the parentheses, just use:
$myString.Split('()')[1]
Open the created task scheduler
switch to the “Action” tab and select your created “Action”
In the Edit section, using the browser you could select powershell.exe in your system32\WindowsPowerShell\v1.0 folder.
Example -C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Next, in the ‘Add arguments’ -File parameter, paste your script file path in your system.
Example – c:\GetMFAStatus.ps1
This blog might help you to automate your Powershell scripts with windows task scheduler
Right now, the last version of Android Studio bundled (Windows IDE bundle with SDK (64-bit)) with Android SDK is version 2.3.3:
https://developer.android.com/studio/archive.html#android-studio-2-3-3
which size is about 2GB.
You can use it and then upgrade to the latest version of Android Studio.
If you're using Laravel, my problem was in the name of my Route. Instead:
Route::put('/reason/update', 'REASONController@update');
I wrote:
Route::put('/reason/update', 'RESONController@update');
and when I fixed the controller name, the code worked!
Try to set a longer max_execution_time
:
<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>
<IfModule mod_php7.c>
php_value max_execution_time 300
</IfModule>
'repr' means represention. First,we create an instance of class coordinate.
x = Coordinate(3, 4)
Then if we input x into console,th output is
<__main__.Coordinate at 0x7fcd40ab27b8>
If you use repr():
>>> repr(x)
Coordinate(3, 4)
the output is as same as 'Coordinate(3, 4)',except it is a string.You can use it to recreate a instance of coordinate.
In conclusion,repr() meathod is print out a string,which is the representation of the obeject.
Here is Bjarne Stroustrup's wordings,
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
I would like to add some additional aspect of this discussion. In windows OS I have observed that when a jar file containing schema is stored in a directory whose path contains a space character, for instance like in the following example
"c:\Program Files\myApp\spring-beans-4.0.2.RELEASE.jar"
then specifying schema location URL in the following way is not sufficient when you are developing some standalone application that should work also offline
<beans
xsi:schemaLocation="
http://www.springframework.org/schema/beans org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
/>
I have learned that result of such schema location URL resolution is a file which has a path like the following
"c:\Program%20Files\myApp\spring-beans-4.0.2.RELEASE.jar"
When I started my application from some other directory which didn't contain space character on its path then schema location resolution worked fine. Maybe somebody faced similar problems? Nevertheless I discoverd that classpath protocol works fine in my case
<beans
xsi:schemaLocation="
http://www.springframework.org/schema/beans classpath:org/springframework/beans/factory/xml/spring-beans-2.0.xsd"
/>
If you read the help for vector
(or numeric
or logical
or character
or integer
or double
, 'raw' or complex
etc ) then you will see that they all have a length
(or length.out
argument which defaults to 0
Therefore
numeric()
logical()
character()
integer()
double()
raw()
complex()
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')
All return 0 length vectors of the appropriate atomic modes.
# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')
driver Asus for Windows: http://www.asus.com/sa-en/support/Download/39/1/0/2/32/
Choose target device: USB device
I want share my experience. A few days ago I have to update 21 million records in table with 76 million records. My colleague suggested the next variant. For example, we have the next table 'Persons':
Id | FirstName | LastName | Email | JobTitle
1 | John | Doe | [email protected] | Software Developer
2 | John1 | Doe1 | [email protected] | Software Developer
3 | John2 | Doe2 | [email protected] | Web Designer
Task: Update persons to the new Job Title: 'Software Developer' -> 'Web Developer'.
1. Create Temporary Table 'Persons_SoftwareDeveloper_To_WebDeveloper (Id INT Primary Key)'
2. Select into temporary table persons which you want to update with the new Job Title:
INSERT INTO Persons_SoftwareDeveloper_To_WebDeveloper SELECT Id FROM
Persons WITH(NOLOCK) --avoid lock
WHERE JobTitle = 'Software Developer'
OPTION(MAXDOP 1) -- use only one core
Depends on rows count, this statement will take some time to fill your temporary table, but it would avoid locks. In my situation it took about 5 minutes (21 million rows).
3. The main idea is to generate micro sql statements to update database. So, let's print them:
DECLARE @i INT, @pagesize INT, @totalPersons INT
SET @i=0
SET @pagesize=2000
SELECT @totalPersons = MAX(Id) FROM Persons
while @i<= @totalPersons
begin
Print '
UPDATE persons
SET persons.JobTitle = ''ASP.NET Developer''
FROM Persons_SoftwareDeveloper_To_WebDeveloper tmp
JOIN Persons persons ON tmp.Id = persons.Id
where persons.Id between '+cast(@i as varchar(20)) +' and '+cast(@i+@pagesize as varchar(20)) +'
PRINT ''Page ' + cast((@i / @pageSize) as varchar(20)) + ' of ' + cast(@totalPersons/@pageSize as varchar(20))+'
GO
'
set @i=@i+@pagesize
end
After executing this script you will receive hundreds of batches which you can execute in one tab of MS SQL Management Studio.
4. Run printed sql statements and check for locks on table. You always can stop process and play with @pageSize to speed up or speed down updating(don't forget to change @i after you pause script).
5. Drop Persons_SoftwareDeveloper_To_AspNetDeveloper. Remove temporary table.
Minor Note: This migration could take a time and new rows with invalid data could be inserted during migration. So, firstly fix places where your rows adds. In my situation I fixed UI, 'Software Developer' -> 'Web Developer'.
I haven't tried this myself, but a quick dig through the library suggests you can do this:
$output = new Symfony\Component\Console\Output\ConsoleOutput();
$output->writeln("<info>my message</info>");
I couldn't find a shortcut for this, so you would probably want to create a facade to avoid duplication.
line=$(head -1 file)
Will work fine. (As previous answer). But
line=$(read -r FIRSTLINE < filename)
will be marginally faster as read
is a built-in bash command.
Last one is not working now, take this one, it worked for me.
in WebApiConfig.cs at App_Start
public static string _WebApiExecutionPath = "api";
public static void Register(HttpConfiguration config)
{
var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");
// Controller Only
// To handle routes like `/api/VTRouting`
config.Routes.MapHttpRoute(
name: "ControllerOnly",
routeTemplate: basicRouteTemplate//"{0}/{controller}"
);
// Controller with ID
// To handle routes like `/api/VTRouting/1`
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
Global.asax
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private static bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}
fournd here: http://forums.asp.net/t/1773026.aspx/1
You can replace "quote" characters with an empty string, like this:
>>> a = '"sajdkasjdsak" "asdasdasds"'
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'
In your case, you can do the same for out
variable.
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
A cleaner approach:
function Size($path)
{
$bytes = sprintf('%u', filesize($path));
if ($bytes > 0)
{
$unit = intval(log($bytes, 1024));
$units = array('B', 'KB', 'MB', 'GB');
if (array_key_exists($unit, $units) === true)
{
return sprintf('%d %s', $bytes / pow(1024, $unit), $units[$unit]);
}
}
return $bytes;
}
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
I would suggest using the members of string, but with an explicit encoding:
byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");
By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes()
etc:
EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.
Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.
EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset
instead. Using Guava I'd really use:
byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);
Inlining is a suggestion to the compiler which it is free to ignore. It's ideal for small bits of code.
If your function is inlined, it's basically inserted in the code where the function call is made to it, rather than actually calling a separate function. This can assist with speed as you don't have to do the actual call.
It also assists CPUs with pipelining as they don't have to reload the pipeline with new instructions caused by a call.
The only disadvantage is possible increased binary size but, as long as the functions are small, this won't matter too much.
I tend to leave these sorts of decisions to the compilers nowadays (well, the smart ones anyway). The people who wrote them tend to have far more detailed knowledge of the underlying architectures.
StringBuilder
is significantly more efficient but you will not see that performance unless you are doing a large amount of string modification.
Below is a quick chunk of code to give an example of the performance. As you can see you really only start to see a major performance increase when you get into large iterations.
As you can see the 200,000 iterations took 22 seconds while the 1 million iterations using the StringBuilder
was almost instant.
string s = string.Empty;
StringBuilder sb = new StringBuilder();
Console.WriteLine("Beginning String + at " + DateTime.Now.ToString());
for (int i = 0; i <= 50000; i++)
{
s = s + 'A';
}
Console.WriteLine("Finished String + at " + DateTime.Now.ToString());
Console.WriteLine();
Console.WriteLine("Beginning String + at " + DateTime.Now.ToString());
for (int i = 0; i <= 200000; i++)
{
s = s + 'A';
}
Console.WriteLine("Finished String + at " + DateTime.Now.ToString());
Console.WriteLine();
Console.WriteLine("Beginning Sb append at " + DateTime.Now.ToString());
for (int i = 0; i <= 1000000; i++)
{
sb.Append("A");
}
Console.WriteLine("Finished Sb append at " + DateTime.Now.ToString());
Console.ReadLine();
Result of the above code:
Beginning String + at 28/01/2013 16:55:40.
Finished String + at 28/01/2013 16:55:40.
Beginning String + at 28/01/2013 16:55:40.
Finished String + at 28/01/2013 16:56:02.
Beginning Sb append at 28/01/2013 16:56:02.
Finished Sb append at 28/01/2013 16:56:02.
The easiest way I have found to have the proper "directory" structure appear under the drawable folder for my icons is this:
Now the pseudo-directories have been created for you under the Drawable folder in the Android view. Open up the true directories on your file system "main/res/drawable-xxhdpi", "main/res/drawable-xhdpi" and replace the icons in each folder with your own of the proper density.
This is a very common problem faced by developers and that is mainly due to Safari's
property of not recreating elements defined as position : fixed
.
So either change the position property or some hack needs to be applied as mentioned in other answers.
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break
. That will do it.
HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/
From the Errata:
ModelState.AddRuleViolations(dinner.GetRuleViolations());
Should be:
ModelState.AddModelErrors(dinner.GetRuleViolations());
If you are on a linux machine running Python 2 you can run this commands:
1st make sure python 2 is installed:
python2 --version
2nd check to see if pip is installed:
pip --version
If you are running Python 3 you can run this command:
1st make sure python 3 is installed:
python3 --version
2nd check to see if pip3 is installed:
pip3 --version
If you do not have pip installed you can run these commands to install pip (it is recommended you install pip for Python 2 and Python 3):
Install pip for Python 2:
sudo apt install python-pip
Then verify if it is installed correctly:
pip --version
Install pip for Python 3:
sudo apt install python3-pip
Then verify if it is installed correctly:
pip3 --version
For more info see: https://itsfoss.com/install-pip-ubuntu/
UPDATE
I would like to mention a few things. When working with Django I learned that my Linux install requires me to use python 2.7, so switching my default python version for the python
and pip
command alias's to python 3 with alias python=python3
is not recommended. Therefore I use the python3
and pip3
commands when installing software like Django 3.0, which works better with Python 3. And I keep their alias's pointed towards whatever Python 3 version I want like so alias python3=python3.8
.
Keep In Mind
When you are going to use your package in the future you will want to use the pip
or pip3
command depending on which one you used to initially install the package. So for example if I wanted to change my change my Django package version I would use the pip3
command and not pip
like so, pip3 install Django==3.0.11
.
Notice
When running checking the packages version for python: $ python -m django --version
and python3: $ python3 -m django --version
, two different versions of django will show because I installed django v3.0.11 with pip3
and django v1.11.29 with pip
.
With the current version of Bootstrap (3.3.7), it is possible to color a single cell of a table like so:
<td class = 'text-center col-md-4 success'>
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
You can use PHP documentation more info check this link https://www.php.net/manual/en/splfixedarray.setsize.php
PYTHON 3
import urllib.request
wp = urllib.request.urlopen("http://example.com")
pw = wp.read()
print(pw)
PYTHON 2
import urllib
import sys
wp = urllib.urlopen("http://example.com")
for line in wp:
sys.stdout.write(line)
While I have tested both the Codes in respective versions.
I have an Android LG G4 and the only thing that worked for me was to install the Software Update and Repair tool from my device. Steps:
There's a nice article which may answer your question /only it prints the paths instead of collecting them/. Please note that you can experiment with the C++/Python samples in the online IDE.
http://www.geeksforgeeks.org/find-paths-given-source-destination/
You cannot test for string[]
in the general case but you can test for Array
quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330
If you specifically want for string
array you can do something like:
if (Array.isArray(value)) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString && value.length > 0){
console.log('string[]!');
}
}
import os
import os.path
import shutil
You find your current directory:
d = os.getcwd() #Gets the current working directory
Then you change one directory up:
os.chdir("..") #Go up one directory from working directory
Then you can get a tupple/list of all the directories, for one directory up:
o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple
Then you can search the tuple for the directory you want and open the file in that directory:
for item in o:
if os.path.exists(item + '\\testfile.txt'):
file = item + '\\testfile.txt'
Then you can do stuf with the full file path 'file'
Give your image an id. Then you can do this in your javascript.
document.getElementById("blaah").src="blaah";
You can use the ".___" method to change the value of any attribute of any element.
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
You can get and set environment variables via os.environ
:
import os
user_home = os.environ["HOME"]
os.environ["PYTHONPATH"] = "..."
But since your interpreter is already running, this will have no effect. You're better off using
import sys
sys.path.append("...")
which is the array that your PYTHONPATH
will be transformed into on interpreter startup.
This problem is caused by a mismatch between your pip installation and your requests installation.
As of requests version 2.4.0 requests.compat.IncompleteRead
has been removed. Older versions of pip, e.g. from July 2014, still relied on IncompleteRead
. In the current version of pip, the import of IncompleteRead
has been removed.
So the one to blame is either:
You can solve this issue, by either updating pip via Ubuntu (if there is a newer version) or by installing pip aside from Ubuntu.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
On my machine I tried check it. My result:
Calendar.getInstance().getTime() (*1000000 times) = 402ms new Date().getTime(); (*1000000 times) = 18ms System.currentTimeMillis() (*1000000 times) = 16ms
Don't forget about GC (if you use Calendar.getInstance()
or new Date()
)
Swift 5, Use extension:
extension UITextView {
func adjustUITextViewHeight() {
self.translatesAutoresizingMaskIntoConstraints = true
self.sizeToFit()
self.isScrollEnabled = false
}
}
Usecase:
textView.adjustUITextViewHeight()
And don't care about the height of texeView in the storyboard (just use a constant at first)
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
You need the ?Rscript
command to run an R script from the terminal.
Check out http://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rscript.html
Example
## example #! script for a Unix-alike
#! /path/to/Rscript --vanilla --default-packages=utils
args <- commandArgs(TRUE)
res <- try(install.packages(args))
if(inherits(res, "try-error")) q(status=1) else q()
To this case, I have a hexadecimal data format into an int array and I want to convert them on String.
int[] encodeHex = new int[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // Hello encode
for (int i = 0; i < encodeHex.length; i++) {
System.out.print((char) (encodeHex[i]));
}
I have the script all.p
set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file
Here the two last rows are literal, not heuristic. Then i run
$ gnuplot -p all.p
Change *.dat
to the file type you have, or add file types.
Next step: Add to ~/.bashrc this line
alias p='gnuplot -p ~/./all.p'
and put your file all.p
int your home directory and voila. You can plot all files in any directory by typing p and enter.
EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i)
.
workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
}
});
Here is a flexible approach, it can be used in all cases, in particular:
dataframe
has been obtained from applying previous operations (e.g. not immediately opening a file, or creating a new data frame).First, un-factorize a string using the as.character
function, and, then, re-factorize with the as.factor
(or simply factor
) function:
fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
# Un-factorize (as.numeric can be use for numeric values)
# (as.vector can be use for objects - not tested)
fixed$Type <- as.character(fixed$Type)
fixed[1, ] <- c("lunch", 100)
# Re-factorize with the as.factor function or simple factor(fixed$Type)
fixed$Type <- as.factor(fixed$Type)
If all you want is a simple excel worksheet try this:
header('Content-type: application/excel');
$filename = 'filename.xls';
header('Content-Disposition: attachment; filename='.$filename);
$data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet 1</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo/>
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
<body>
<table><tr><td>Cell 1</td><td>Cell 2</td></tr></table>
</body></html>';
echo $data;
The key here is the xml data. This will keep excel from complaining about the file.
Here's a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren't an issue either.
var now = new Date();
var daysOfYear = [];
for (var d = new Date(2012, 0, 1); d <= now; d.setDate(d.getDate() + 1)) {
daysOfYear.push(new Date(d));
}
Note that if you want to store the date, you'll need to make a new one (as above with new Date(d)
), or else you'll end up with every stored date being the final value of d
in the loop.
I used CRAN package "downloader" found at http://cran.r-project.org/web/packages/downloader/index.html . Much easier.
download(url, dest="dataset.zip", mode="wb")
unzip ("dataset.zip", exdir = "./")
If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:
=SUMIF(B:B,"No",A:A)
or
=SUMIFS(A:A,B:B,"No")
Here is an example that will display the amounts paid and outstanding for a small set of sample data.
A B C D
Amount Reimbursed? Total Paid: =SUMIF(B:B,"Yes",A:A)
$100 Yes Total Outstanding: =SUMIF(B:B,"No",A:A)
$200 No
$300 No
$400 Yes
$500 No
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.
Not tested but should work:
$("#MyDiv td input:checked").each(function()
{
alert($(this).attr("id"));
});
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
Turns query string like hello=1&another=2
into object {hello: 1, another: 2}
. From there, it's easy to extract the variable you need.
That said, it does not deal with array cases such as "hello=1&hello=2&hello=3"
. To work with this, you must check whether a property of the object you make exists before adding to it, and turn the value of it into an array, pushing any additional bits.
Plain vanilla JDBC does not support named parameters.
If you are using DB2 then using DB2 classes directly:
you can use ClearContents. ex,
Range("X").Cells.ClearContents
>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]
The above works. Are you doing something different?
Notice that your key function is just sum
; there's no need to write it explicitly.
Here is a generic way to convert array to ArrayList
<T> ArrayList<T> toArrayList(Object o, Class<T> type){
ArrayList<T> objects = new ArrayList<>();
for (int i = 0; i < Array.getLength(o); i++) {
//noinspection unchecked
objects.add((T) Array.get(o, i));
}
return objects;
}
Usage
ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
In PHP 5.5+, you can do
function limit($iterable, $limit) {
foreach ($iterable as $key => $value) {
if (!$limit--) break;
yield $key => $value;
}
}
foreach (limit($arr, 10) as $key => $value) {
// do stuff
}
Generators rock.
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
-eq
is a mathematical comparison operator. I've never used it for string comparison, relying on ==
and !=
for compares.
if [ 'XYZ' == 'ABC' ]; then # Double equal to will work in Linux but not on HPUX boxes it should be if [ 'XYZ' = 'ABC' ] which will work on both
echo "Match"
else
echo "No Match"
fi
tsc is not recognized as internal or external command
As mentioned in another answer this is because tsc is not present in path.
1. Install as global package
To make TypeScript compiler available to all directories for this user, run the below command:
npm install -g typescript
You will see something similar to
C:\Users\username\AppData\Roaming\npm\tsserver -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsserver C:\Users\username\AppData\Roaming\npm\tsc -> C:\Users\username\AppData\Roaming\npm\node_modules\typescript\bin\tsc + [email protected] added 1 package from 1 contributor in 4.769s
2. Set the environment variable
Add the npm installation folder to your "user variables" AND "environment variables".
In windows you can add environment variable PATH with value
C:\Users\username\AppData\Roaming\npm\
i.e. wherever the npm installation folder is present.
Note: If multiple Paths are present separate them with a ;(semicolon)
If the below command gives the version then you have successfully installed
tsc --version
If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file);
returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.
A simple one would be
\d{4}-\d{2}-\d{2}
but this does not restrict month to 1-12 and days from 1 to 31.
There are more complex checks like in the other answers, by the way pretty clever ones. Nevertheless you have to check for a valid date, because there are no checks for if a month has 28, 30, or 31 days.
You need the :not()
selector:
$('div[class^="first-"]:not(.first-bar)')
or, alternatively, the .not()
method:
$('div[class^="first-"]').not('.first-bar');
As in Oleg's answer, I believe the correct variable to set is CMAKE_RUNTIME_OUTPUT_DIRECTORY. We use the following in our root CMakeLists.txt:
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
You can also specify the output directories on a per-target basis:
set_target_properties( targets...
PROPERTIES
ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
)
In both cases you can append _[CONFIG]
to the variable/property name to make the output directory apply to a specific configuration (the standard values for configuration are DEBUG
, RELEASE
, MINSIZEREL
and RELWITHDEBINFO
).
Outer Div must set its position
to relative
or fixed
, and the Inner Div must set its position
to absolute
, top
and left
to 50%
and apply a transform: translate(-50%, -50%)
.
div.cn {_x000D_
position: relative;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
background: gray;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
div.inner {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
-webkit-transform: translate(-50%, -50%); _x000D_
transform: translate(-50%, -50%); _x000D_
background: red;_x000D_
_x000D_
}
_x000D_
<div class="cn">_x000D_
<div class="inner">_x000D_
test_x000D_
</div>_x000D_
</div>
_x000D_
Tested in:
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
A simpler way is
ggplot(data=df, aes(x=xvar, y=yvar)) +
geom_point()
ggsave(path = path, width = width, height = height, device='tiff', dpi=700)
SWIFT 5.1 of selected answer for newbies
class TestClass {
deinit {
// If you don't remove yourself as an observer, the Notification Center
// will continue to try and send notification objects to the deallocated
// object.
NotificationCenter.default.removeObserver(self)
}
init() {
super.init()
// Add this instance of TestClass as an observer of the TestNotification.
// We tell the notification center to inform us of "TestNotification"
// notifications using the receiveTestNotification: selector. By
// specifying object:nil, we tell the notification center that we are not
// interested in who posted the notification. If you provided an actual
// object rather than nil, the notification center will only notify you
// when the notification was posted by that particular object.
NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
}
@objc func receiveTest(_ notification: Notification?) {
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if notification?.name.isEqual(toString: "TestNotification") != nil {
print("Successfully received the test notification!")
}
}
}
... somewhere else in another class ...
func someMethod(){
// All instances of TestClass will be notified
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
}
You can get all N! permutations without much code
def permutations(string, step = 0):
# if we've gotten to the end, print the permutation
if step == len(string):
print "".join(string)
# everything to the right of step has not been swapped yet
for i in range(step, len(string)):
# copy the string (store as array)
string_copy = [character for character in string]
# swap the current index with the step
string_copy[step], string_copy[i] = string_copy[i], string_copy[step]
# recurse on the portion of the string that has not been swapped yet (now it's index will begin with step + 1)
permutations(string_copy, step + 1)
Alternative syntax using the -Not
operator and depending on your preference for readability:
if( -Not (Test-Path -Path $TARGETDIR ) )
{
New-Item -ItemType directory -Path $TARGETDIR
}
You have to use RegExp
:
str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));
When I'm concatenating strings, all slashes are gone.
If you have a backslash in your pattern to escape a special regex character, (like \(
), you have to use two backslashes in the string (because \
is the escape character in a string): new RegExp('\\(')
would be the same as /\(/
.
So your patterns have to become:
var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';
The way of changing the name for iOS and Android is clearly mentioned in the documentation as follows:
But, the case of iOS after you change the Display Name from Xcode, you are not able to run the application in the Flutter way, like flutter run
.
Because the Flutter run expects the app name as Runner. Even if you change the name in Xcode, it doesn't work.
So, I fixed this as follows:
Move to the location on your Flutter project, ios/Runner.xcodeproj/project.pbxproj, and find and replace all instances of your new name with Runner.
Then everything should work in the flutter run
way.
But don't forget to change the name display name on your next release time. Otherwise, the App Store rejects your name.
I also had this same problem.
I build .apk file of the project and installed it into mobile(android) and got it working