If you install TortoiseSVN you can use SVN under windows. It also gives you the SVN binaries. You needn't do the checkout from the command-line though as it integrates into Windows Explorer for you.
One additional benefit to doing it in javascript is you can add / remove the hover effect at different points in time - e.g. hover over table rows changes color, click disables the hover effect and starts edit in place mode.
If you have just installed macports just run and it should work
source ~/.bash_profile
This is a cool solution that works perfectly
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];
var item = array.filter(item=>item.title.toLowerCase().includes('this'));
alert(JSON.stringify(item))
EDITED
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];_x000D_
_x000D_
_x000D_
// array.filter loops through your array and create a new array returned as Boolean value given out "true" from eachIndex(item) function _x000D_
_x000D_
var item = array.filter((item)=>eachIndex(item));_x000D_
_x000D_
//var item = array.filter();_x000D_
_x000D_
_x000D_
_x000D_
function eachIndex(e){_x000D_
console.log("Looping each index element ", e)_x000D_
return e.title.toLowerCase().includes("this".toLowerCase())_x000D_
}_x000D_
_x000D_
console.log("New created array that returns \"true\" value by eachIndex ", item)
_x000D_
cd ~/.m2
git init
git commit -am "some comments"
cd /path/to/your/project
mvn install
cd ~/.m2
git reset --hard
open cmd and type the following command
netstat -aon|findstr 5037
and press enter.
you will get a reply like this :
TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 3372
TCP 127.0.0.1:5037 127.0.0.1:50126 TIME_WAIT 0
TCP 127.0.0.1:5037 127.0.0.1:50127 TIME_WAIT 0
TCP 127.0.0.1:50127 127.0.0.1:5037 TIME_WAIT 0
this shows the pid which is occupying the adb. in this 3372 is the value. it will not be same for anyone. so you need to do this every time you face this problem.
now type this :
taskkill /pid 3372(the pid you get in the previous step) /f
Voila! now adb runs perfectly.
I am posting all at one place, all works for me to pad with 4 leading zero :)
declare @number int = 1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')
Sometimes things might be simpler. I came here with the exact issue and tried all the suggestions. But later found that the problem was just the local file path was different and I was on a different folder. :-)
eg -
~/myproject/mygitrepo/app/$ git diff app/TestFile.txt
should have been
~/myproject/mygitrepo/app/$ git diff TestFile.txt
I had a similar issue on 16.04 VPS Digital Ocean. If you are changing crontabs, make sure to run
sudo service cron restart
i used replace feature in Notepad++ and replaced "
(without quotes) with "
and result was valid json
A lightweight solution with Check constraint:
CREATE TABLE example (
discriminator INTEGER DEFAULT 0 NOT NULL CHECK (discriminator = 0)
);
You just change the App_Start/WebApiConfig.cs
like this:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//Below formatter is used for returning the Json result.
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
//Default route
config.Routes.MapHttpRoute(
name: "ApiControllerOnly",
routeTemplate: "api/{controller}"
);
}
I ran into this issue and resolved it by removing the width styling I had used on the SVG:
.svg-div img {
width: 200px; /* removed this */
height: auto;
}
I've implemented a different method to check for primes because:
Here is my implementation:
public static BigInteger IntegerSquareRoot(BigInteger value)
{
if (value > 0)
{
int bitLength = value.ToByteArray().Length * 8;
BigInteger root = BigInteger.One << (bitLength / 2);
while (!IsSquareRoot(value, root))
{
root += value / root;
root /= 2;
}
return root;
}
else return 0;
}
private static Boolean IsSquareRoot(BigInteger n, BigInteger root)
{
BigInteger lowerBound = root * root;
BigInteger upperBound = (root + 1) * (root + 1);
return (n >= lowerBound && n < upperBound);
}
static bool IsPrime(BigInteger value)
{
Console.WriteLine("Checking if {0} is a prime number.", value);
if (value < 3)
{
if (value == 2)
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
else
{
Console.WriteLine("{0} is not a prime number because it is below 2.", value);
return false;
}
}
else
{
if (value % 2 == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by 2.", value);
return false;
}
else if (value == 5)
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
else if (value % 5 == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by 5.", value);
return false;
}
else
{
// The only way this number is a prime number at this point is if it is divisible by numbers ending with 1, 3, 7, and 9.
AutoResetEvent success = new AutoResetEvent(false);
AutoResetEvent failure = new AutoResetEvent(false);
AutoResetEvent onesSucceeded = new AutoResetEvent(false);
AutoResetEvent threesSucceeded = new AutoResetEvent(false);
AutoResetEvent sevensSucceeded = new AutoResetEvent(false);
AutoResetEvent ninesSucceeded = new AutoResetEvent(false);
BigInteger squareRootedValue = IntegerSquareRoot(value);
Thread ones = new Thread(() =>
{
for (BigInteger i = 11; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
onesSucceeded.Set();
});
ones.Start();
Thread threes = new Thread(() =>
{
for (BigInteger i = 3; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
threesSucceeded.Set();
});
threes.Start();
Thread sevens = new Thread(() =>
{
for (BigInteger i = 7; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
sevensSucceeded.Set();
});
sevens.Start();
Thread nines = new Thread(() =>
{
for (BigInteger i = 9; i <= squareRootedValue; i += 10)
{
if (value % i == 0)
{
Console.WriteLine("{0} is not a prime number because it is divisible by {1}.", value, i);
failure.Set();
}
}
ninesSucceeded.Set();
});
nines.Start();
Thread successWaiter = new Thread(() =>
{
AutoResetEvent.WaitAll(new WaitHandle[] { onesSucceeded, threesSucceeded, sevensSucceeded, ninesSucceeded });
success.Set();
});
successWaiter.Start();
int result = AutoResetEvent.WaitAny(new WaitHandle[] { success, failure });
try
{
successWaiter.Abort();
}
catch { }
try
{
ones.Abort();
}
catch { }
try
{
threes.Abort();
}
catch { }
try
{
sevens.Abort();
}
catch { }
try
{
nines.Abort();
}
catch { }
if (result == 1)
{
return false;
}
else
{
Console.WriteLine("{0} is a prime number.", value);
return true;
}
}
}
}
Update: If you want to implement a solution with trial division more rapidly, you might consider having a cache of prime numbers. A number is only prime if it is not divisible by other prime numbers that are up to the value of its square root. Other than that, you might consider using the probabilistic version of the Miller-Rabin primality test to check for a number's primality if you are dealing with large enough values (taken from Rosetta Code in case the site ever goes down):
// Miller-Rabin primality test as an extension method on the BigInteger type.
// Based on the Ruby implementation on this page.
public static class BigIntegerExtensions
{
public static bool IsProbablePrime(this BigInteger source, int certainty)
{
if(source == 2 || source == 3)
return true;
if(source < 2 || source % 2 == 0)
return false;
BigInteger d = source - 1;
int s = 0;
while(d % 2 == 0)
{
d /= 2;
s += 1;
}
// There is no built-in method for generating random BigInteger values.
// Instead, random BigIntegers are constructed from randomly generated
// byte arrays of the same length as the source.
RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] bytes = new byte[source.ToByteArray().LongLength];
BigInteger a;
for(int i = 0; i < certainty; i++)
{
do
{
// This may raise an exception in Mono 2.10.8 and earlier.
// http://bugzilla.xamarin.com/show_bug.cgi?id=2761
rng.GetBytes(bytes);
a = new BigInteger(bytes);
}
while(a < 2 || a >= source - 2);
BigInteger x = BigInteger.ModPow(a, d, source);
if(x == 1 || x == source - 1)
continue;
for(int r = 1; r < s; r++)
{
x = BigInteger.ModPow(x, 2, source);
if(x == 1)
return false;
if(x == source - 1)
break;
}
if(x != source - 1)
return false;
}
return true;
}
}
Both the right answer. HTML5 follows strict rules and in HTML5 we can close all the tags. So, it depends on you to use HTML5 or HTML and follow an appropriate answer.
<img src='stackoverflow.png'>
<img src='stackoverflow.png' />
The second property is more appropriate.
yet another solution uses tr
:
echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'
the option -d
stands for delete
.
For local development you could serve the files with a simple web server.
With Python installed, go into the folder where your project is served, like cd my-project/
. And then use python -m SimpleHTTPServer
which would make index.html
and it's JavaScript files available at localhost:8000
.
After editting the "right" files (all php.ini's). i had still the issue. My solution was:
Adding a System variable: OPENSSL_CONF
the value of OPENSSL_CONF should be the openssl.cnf file of your current php version.
for me it was:
-> Restart WAMP -> should work now
Swift 4
button.titleLabel?.font = UIFont(name: "Font_Name_Here", size: Font_Size_Here)
Objective-c
[button.titleLabel setFont:[UIFont fontWithName:@“Font_Name_Here” size: Font_Size_Here]];
Example:
Font_Name = "Helvetica"
Font_Size = 16.0
Hope it helps.
I had the same problem for a while and despite doing mvn -U clean install
the problem was not getting solved!
I finally solved the problem by deleting the whole .m2
folder and then restarted my IDE and the problem was gone!
So sometimes the problem would rise because of some incompatibilities or problems in your local maven repository.
Try these:
#dialog_style1 .ui-dialog-titlebar { display:none; }
#dialog_style2 .ui-dialog-titlebar { color:#aaa; }
The best recommendation I can give for you is to load the page in Firefox, open the dialog and inspect it with Firebug, then try different selectors in the console, and see what works. You may need to use some of the other descendant selectors.
Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:
SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Hi this is odd way but try it once
XMLDocument.LoadXML(xmlstring)
I try with your code and same XML without adding any XML declaration it works for me
XmlDocument doc = new XmlDocument();
doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");
XmlNodeList nodes = doc.GetElementsByTagName("Product");
XmlNode node = null;
foreach (XmlNode n in nodes)
{
Console.WriteLine("HI");
}
I have gone through the same problem when I was using
myApp.controller('mainController', ['$scope', function($scope,) {
//$http was not working in this
}]);
I have changed the above code to given below. Remember to include $http(2 times) as given below.
myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
//$http is working in this
}]);
and It has worked well.
The top border of frame is of size 30.You can write code for printing the coordinate of any point on the frame using MouseInputAdapter.You will find when the cursor is just below the top border of the frame the y coordinate is not zero , its close to 30.Hence if you give size to frame 300 * 300 , the size available for putting the components on the frame is only 300 * 270.So if you need to have size 300 * 300 ,give 300 * 330 size of the frame.
you need object notation
<section [ngClass]="{'class1':condition1, 'class2': condition2, 'class3':condition3}" >
ref: NgClass
It's really a shame that both their names start with Hash. That's the least important part of them. The important parts come after the Hash - the Set and Map, as others have pointed out. What they are, respectively, are a Set - an unordered collection - and a Map - a collection with keyed access. They happen to be implemented with hashes - that's where the names come from - but their essence is hidden behind that part of their names.
Don't be confused by their names; they are deeply different things.
Just typecheck it before you cast it.
Object someObject = session.getAttribute("attributeKey");
if(someObject instanceof HashMap)
HashMap<String, String> theHash = (HashMap<String, String>)someObject;
And for anyone asking, it's quite common to receive objects where you aren't sure of the type. Plenty of legacy "SOA" implementations pass around various objects that you shouldn't always trust. (The horrors!)
EDIT Changed the example code once to match the poster's updates, and following some comments I see that instanceof doesn't play nicely with generics. However changing the check to validate the outer object seems to play well with the commandline compiler. Revised example now posted.
I wrote a drawable lib to custom round corner position, it looks like this:
You can get this lib at here:
Worked for me in 30 seconds, short and sweet:
I've been verifying calls in the same manner - I believe it is the right way to do it.
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
), Times.Once());
If your lambda expression becomes unwieldy, you could create a function that takes MyObject
as input and outputs true
/false
...
mockSomething.Verify(ms => ms.Method(
It.IsAny<int>(),
It.Is<MyObject>(mo => MyObjectFunc(mo))
), Times.Once());
private bool MyObjectFunc(MyObject myObject)
{
return myObject.Id == 5 && myObject.description == "test";
}
Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.
EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).
foreach (var item in myList)
mockRepository.Verify(mr => mr.Update(
It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
Times.Once());
Same approach for setup...
foreach (var item in myList) {
var stuff = ... // some result specific to the item
this.mockRepository
.Setup(mr => mr.GetStuff(item.itemId))
.Returns(stuff);
}
So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.
this.mockRepository
.Setup(mr => mr.GetStuff(It.IsAny<int>()))
.Returns((int id) => SomeFunctionThatReturnsStuff(id));
One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.
If you simply want to run the script uninterrupted until it completes you can use nohup
as already mentioned in the answers here. However, none of the answers provide a full command that also logs stdin
and stdout
.
nohup node index.js >> app.log 2>&1 &
>>
means append to app.log
.2>&1
makes sure that errors are also send to stdout
and added to the app.log
.&
makes sure your current terminal is disconnected from command so you can continue working. If you want to run a node server (or something that should start back up when the server restarts) you should use systemd / systemctl.
Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:
Controller:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
user.user_gender = collection["rdbtnGender"];
return RedirectToAction("Index");
}
catch(Exception e)
{
throw e;
}
}
public ActionResult Edit(int id)
{
CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
ViewBag.UserObj = user;
return View();
}
VIEW:
Create:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label for="rdbtnGender2">FEMALE</label>
Edit:
<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>
To build on the answer by @RQDQ using generics, you can combine this with Func<TResult>
(or some variation) and delegate responsibility to the caller:
public T GetAnything<T>(Func<T> createInstanceOfT)
{
//do whatever
return createInstanceOfT();
}
Then you can do something like:
Computer comp = GetAnything(() => new Computer());
Radio rad = GetAnything(() => new Radio());
If you are using AndroidX, use below code to check Location Service is enabled or not:
fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
Here's how to apply environment variables to template file (no backup need).
echo "Hello {{FOO}}" > foo.conf.tmpl
FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf
Working both macOS 10.12.4 and Ubuntu 14.04.5
They are signals that application developers use. The kernel shouldn't ever send these to a process. You can send them using kill(2)
or using the utility kill(1)
.
If you intend to use signals for synchronization you might want to check real-time signals (there's more of them, they are queued, their delivery order is guaranteed etc).
Intel HD Graphics is usually the on-CPU graphics chip in newer Core i3/i5/i7 processors.
As far as I know it doesn't support CUDA (which is a proprietary NVidia technology), but OpenCL is supported by NVidia, ATi and Intel.
You have several tools available:
Aapt (which is part of the Android SDK)
$ aapt dump badging MyApk.apk
$ aapt dump permissions MyApk.apk
$ aapt dump xmltree MyApk.apk
$ java -jar apktool.jar -q decode -f MyApk.apk -o myOutputDir
Apk Viewer
$ dex2jar/d2j-dex2jar.sh -f MyApk.apk -o myOutputDir/MyApk.jar
$ ninjadroid MyApk.apk
$ ninjadroid MyApk.apk --all --extract myOutputDir/
$ apkinfo MyApk.apk
Very common problem in android
It can be broken down into 3 Pieces
1 ) start Activity B (Happens in Activity A)
2 ) Set requested data (Happens in activity B)
3 ) Receive requested data (Happens in activity A)
1) startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
2) Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
Eg: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key","Your_value");
setResult(RES_CODE_A,resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B,new Intent());
finish();
}
user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code
3) Retrieve result
For that override onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// back button clicked
}
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error($connection));
}
You got the order of the arguments to mysqli_select_db()
backwards. And mysqli_error()
requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.
Note also that with mysqli you can specify the DB in mysqli_connect()
:
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
die("Database connection failed: " . mysqli_connect_error();
}
You must use mysqli_connect_error()
, not mysqli_error()
, to get the error from mysqli_connect()
, since the latter requires you to supply a valid connection.
This is a recursive solution with n!
which accepts duplicate elements in the string
import math
def getFactors(root,num):
sol = []
# return condition
if len(num) == 1:
return [root+num]
# looping in next iteration
for i in range(len(num)):
# Creating a substring with all remaining char but the taken in this iteration
if i > 0:
rem = num[:i]+num[i+1:]
else:
rem = num[i+1:]
# Concatenating existing solutions with the solution of this iteration
sol = sol + getFactors(root + num[i], rem)
return sol
I validated the solution taking into account two elements, the number of combinations is n!
and the result can not contain duplicates. So:
inpt = "1234"
results = getFactors("",inpt)
if len(results) == math.factorial(len(inpt)) | len(results) != len(set(results)):
print("Wrong approach")
else:
print("Correct Approach")
Use hashes when you don't want to be able to get back the original input, use encryption when you do.
Hashes take some input and turn it into some bits (usually thought of as a number, like a 32 bit integer, 64 bit integer, etc). The same input will always produce the same hash, but you PRINCIPALLY lose information in the process so you can't reliably reproduce the original input (there are a few caveats to that however).
Encryption principally preserves all of the information you put into the encryption function, just makes it hard (ideally impossible) for anyone to reverse back to the original input without possessing a specific key.
Simple Example of Hashing
Here's a trivial example to help you understand why hashing can't (in the general case) get back the original input. Say I'm creating a 1-bit hash. My hash function takes a bit string as input and sets the hash to 1 if there are an even number of bits set in the input string, else 0 if there were an odd number.
Example:
Input Hash
0010 0
0011 1
0110 1
1000 0
Note that there are many input values that result in a hash of 0, and many that result in a hash of 1. If you know the hash is 0, you can't know for sure what the original input was.
By the way, this 1-bit hash isn't exactly contrived... have a look at parity bit.
Simple Example of Encryption
You might encrypt text by using a simple letter substitution, say if the input is A, you write B. If the input is B, you write C. All the way to the end of the alphabet, where if the input is Z, you write A again.
Input Encrypted
CAT DBU
ZOO APP
Just like the simple hash example, this type of encryption has been used historically.
You can make use of the following code incase you want to check the types of primitive data types.
// Returns 0 if the object type is equal to double
strcmp([myNumber objCType], @encode(double))
This didn't work,
android:background="@android:color/transparent"
Setting the webview
background color as worked
webView.setBackgroundColor(0)
Additionally, I set window background drawable as transparent
If you have just added FCM to an existing app, onTokenRefresh()
will NOT be called. I got it to run by uninstalling the app and installing it again.
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
Others have pointed out that a get_FOO_display method is what you need. I'm using this:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
which iterates over all of the choices that a particular item has until it finds the one that matches the items type
You can use a character class:
/[^\s\\]/
matches anything that is not a whitespace character nor a \
. Here's another example:
[abc]
means "match a
, b
or c
"; [^abc]
means "match any character except a
, b
or c
".
Below is what worked for me -
QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"
//for update
(from x in dataBase.Customers
where x.Name == "Test"
select x).ToList().ForEach(xx => xx.Name="New Name");
//for delete
dataBase.Customers.RemoveAll(x=>x.Name=="Name");
Here is how I got this working
$.ajax({
url: '<URL_TO_FILE>',
success: function(data) {
var blob=new Blob([data]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";
link.click();
}
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
$.ajax({
url: '<URL_TO_FILE>',
success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>")
});
_x000D_
g++ file_name.cpp -o executable_file_name
(i) -o option is used to show error in the code (ii) if there is no error in the code_file, then it will generate an executable file.
./executable_file_name
Java anonymous class is very similar to Javascript closure, but Java implement that in different way. (check Andersen's answer)
So in order not to confuse the Java Developer with the strange behavior that might occur for those coming from Javascript background. I guess that's why they force us to use final
, this is not the JVM limitation.
Let's look at the Javascript example below:
var add = (function () {
var counter = 0;
var func = function () {
console.log("counter now = " + counter);
counter += 1;
};
counter = 100; // line 1, this one need to be final in Java
return func;
})();
add(); // this will print out 100 in Javascript but 0 in Java
In Javascript, the counter
value will be 100, because there is only one counter
variable from the beginning to end.
But in Java, if there is no final
, it will print out 0
, because while the inner object is being created, the 0
value is copied to the inner class object's hidden properties. (there are two integer variable here, one in the local method, another one in inner class hidden properties)
So any changes after the inner object creation (like line 1), it will not affect the inner object. So it will make confusion between two different outcome and behaviour (between Java and Javascript).
I believe that's why, Java decide to force it to be final, so the data is 'consistent' from the beginning to end.
You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.
<script type="text/javascript">
$(document).ready(function() {
$('.btn-danger').tooltip();
}); //END $(document).ready()
</script>
Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup"
.
The problem with String concatenation is that it leads to copying of the String object with all the associated cost. StringBuilder is not threadsafe and is therefore faster than StringBuffer, which used to be the preferred choice before Java 5. As a rule of thumb, you should not do String concatenation in a loop, which will be called often. I guess doing a few concatenations here and there will not hurt you as long as you are not talking about hundreds and this of course depends on your performance requirements. If you are doing real time stuff, you should be very careful.
You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:
<body oncopy="return false" oncut="return false" onpaste="return false">
How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers
A more advanced aproach:
How to detect Ctrl+V, Ctrl+C using JavaScript?
Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.
You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)
Below is one of the way by which you can achieve that, may not be an ideal way to do.
Have one method accepting both types of request, then check what type of request you received, is it of type "GET" or "POST", once you come to know that, do respective actions and the call one method which does common task for both request Methods ie GET and POST.
@RequestMapping(value = "/books")
public ModelAndView listBooks(HttpServletRequest request){
//handle both get and post request here
// first check request type and do respective actions needed for get and post.
if(GET REQUEST){
//WORK RELATED TO GET
}else if(POST REQUEST){
//WORK RELATED TO POST
}
commonMethod(param1, param2....);
}
or just use $.trim(str)
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
This way you can create a new object with a custom property name.
$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);
Now you can reach it like:
echo $a->foo; //returns bar
(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
I don't think there's a recommended order, as long as it compiles! What's annoying is when some headers require other headers to be included first... That's a problem with the headers themselves, not with the order of includes.
My personal preference is to go from local to global, each subsection in alphabetical order, i.e.:
My rationale for 1. is that it should prove that each header (for which there is a cpp) can be #include
d without prerequisites (terminus technicus: header is "self-contained"). And the rest just seems to flow logically from there.
Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.
If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.
If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.
It could be a solution:
Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*
Load the address again once you have replaced uc with open in the address.
This loads a new screen with controls at the top.
Click on the "add to my drive" icon at the top right.
Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.
You should see the locked file on your drive now.
Select it with a right-click, and then the "make a copy" option from the menu.
8.Select the copy of the file with a right-click, and there download to download the file to your local system.
Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.
Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.
Another option is: Any public folder in Drive can host files and provide direct links to the files.
How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)
This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.
My solution:
I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it
Traffic limits DROPBOX
Links and file requests are automatically banned if they generate unusually large amounts of traffic.
Dropbox Basic (free) accounts:
20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate
Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.
P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
Just use this code
QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);
Note that:"path_to_icon"
is the path of image icon in file .qrc
of your project You can find how to add .qrc
file here
Just to add description for another one case. I've got to install similar Vagrant Ubuntu 18.04 based configurations to multiple Ubuntu machines. Downloaded bionic64 box to one using vagrant up
with Vagrantfile
where this box was specified, then copied folder .vagrant.d/boxes/ubuntu-VAGRANTSLASH-bionic64
to others.
You don't need to install sqlite3
module. It is included in the standard library (since Python 2.5).
The results of the execution time directly contradict the results of the Query Cost, but I'm having difficulty determining what "Query Cost" actually means.
Query cost
is what optimizer thinks of how long your query will take (relative to total batch time).
The optimizer tries to choose the optimal query plan by looking at your query and statistics of your data, trying several execution plans and selecting the least costly of them.
Here you may read in more detail about how does it try to do this.
As you can see, this may differ significantly of what you actually get.
The only real query perfomance metric is, of course, how long does the query actually take.
If you use selenium and chromium, you do not need to manage cookies by you self, and you can generate pdf page from chromium's print as pdf. You can refer this project to realize it. https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter
modified base > https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter/blob/master/sample/html_to_pdf_converter.py
import sys
import json, base64
def send_devtools(driver, cmd, params={}):
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': cmd, 'params': params})
response = driver.command_executor._request('POST', url, body)
return response.get('value')
def get_pdf_from_html(driver, url, print_options={}, output_file_path="example.pdf"):
driver.get(url)
calculated_print_options = {
'landscape': False,
'displayHeaderFooter': False,
'printBackground': True,
'preferCSSPageSize': True,
}
calculated_print_options.update(print_options)
result = send_devtools(driver, "Page.printToPDF", calculated_print_options)
data = base64.b64decode(result['data'])
with open(output_file_path, "wb") as f:
f.write(data)
# example
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
url = "https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python#"
webdriver_options = Options()
webdriver_options.add_argument("--no-sandbox")
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chromedriver, options=webdriver_options)
get_pdf_from_html(driver, url)
driver.quit()
You could set the @Input
on the setter directly, as described below:
_allowDay: boolean;
get allowDay(): boolean {
return this._allowDay;
}
@Input() set allowDay(value: boolean) {
this._allowDay = value;
this.updatePeriodTypes();
}
See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.
Modifying the startup.bat with the CATALINA_OPTS AND JPDA_OPTS didn't work for me but adding them to catalina.bat did
CATALINA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
JPDA_OPTS="-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"
change call "%EXECUTABLE%" start %CMD_LINE_ARGS% to
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
Then configure remote java application in your debug configurations in Eclipse.
If you use it more than once or in a loop, you could define a constant
public static final Foo[] FOO = new Foo[]{};
and do the conversion it like
Foo[] foos = fooCollection.toArray(FOO);
The toArray
method will take the empty array to determine the correct type of the target array and create a new array for you.
Here's my proposal for the update:
Collection<Foo> foos = new ArrayList<Foo>();
Collection<Bar> temp = new ArrayList<Bar>();
for (Foo foo:foos)
temp.add(new Bar(foo));
Bar[] bars = temp.toArray(new Bar[]{});
No, enums are supposed to be a complete static enumeration.
At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.
In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface
for the interface and an enum
that implements that interface
for the standard values. Of course, you lose the ability to switch
when you only have a reference to the interface
.
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
Use the below code for converting XML to JSON.
var json = new JavaScriptSerializer().Serialize(obj);
nth-last-child
sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.
Right. So I've finally got to the bottom of the problem: it was a botched in-place OTA upgrade.
My suspicions intensified after my Garmin Fenix 2 wasn't able to connect via bluetooth and after googling "Marshmallow upgrade issues". Anyway, a "Factory reset" fixed the issue.
Surprisingly, the reset did not return the phone to the original Kitkat; instead, the wipe process picked up the OTA downloaded 6.0 upgrade package and ran with it, resulting (I guess) in a "cleaner" upgrade.
Of course, this meant that the phone lost all the apps that I'd installed. But, freshly installed apps, including mine, work without any changes (i.e. there is backward compatibility). Whew!
pandas version 0.23.4
df.rename(index=str,columns={'old_name':'new_name'},inplace=True)
For the record:
omitting index=str will give error replace has an unexpected argument 'columns'
I tried re-creating this, and .someclass.notip
was being generated for me but .someclass:not(.notip)
was not, for as long as I did not have the @mixin tip()
defined. Once I had that, it all worked.
http://sassmeister.com/gist/9775949
$dropdown-width: 100px;
$comp-tip: true;
@mixin tip($pos:right) {
}
@mixin dropdown-pos($pos:right) {
&:not(.notip) {
@if $comp-tip == true{
@if $pos == right {
top:$dropdown-width * -0.6;
background-color: #f00;
@include tip($pos:$pos);
}
}
}
&.notip {
@if $pos == right {
top: 0;
left:$dropdown-width * 0.8;
background-color: #00f;
}
}
}
.someclass { @include dropdown-pos(); }
EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'.
it what I get when I remove @mixin tip($pos:right) { }
This is the result of the 6 different combinations of the sample test shared by @Hank D
It's evident that predicate of form u -> exp1 && exp2
is highly performant in all the cases.
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=3372, min=31, average=33.720000, max=47}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9150, min=85, average=91.500000, max=118}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9046, min=81, average=90.460000, max=150}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8336, min=77, average=83.360000, max=189}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9094, min=84, average=90.940000, max=176}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10501, min=99, average=105.010000, max=136}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=11117, min=98, average=111.170000, max=238}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8346, min=77, average=83.460000, max=113}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9089, min=81, average=90.890000, max=137}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10434, min=98, average=104.340000, max=132}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9113, min=81, average=91.130000, max=179}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8258, min=77, average=82.580000, max=100}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=9131, min=81, average=91.310000, max=139}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10265, min=97, average=102.650000, max=131}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8442, min=77, average=84.420000, max=156}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8553, min=81, average=85.530000, max=125}
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=8219, min=77, average=82.190000, max=142}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10305, min=97, average=103.050000, max=132}
If you are linking to many files, create a whitelist, and then use sendFile():
app.get('/npm/:pkg/:file', (req, res) => {
const ok = ['jquery','bootstrap','interactjs'];
if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
});
For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.
As an aside, I would love to know if there was a way to whitelist using express.static
printStackTrace()
helps the programmer to understand where the actual problem occurred. printStacktrace()
is a method of the class Throwable
of java.lang
package. It prints several lines in the output console.
The first line consists of several strings. It contains the name of the Throwable sub-class & the package information.
From second line onwards, it describes the error position/line number beginning with at
.
The last line always describes the destination affected by the error/exception. The second last line informs us about the next line in the stack where the control goes after getting transfer from the line number described in the last line. The errors/exceptions represents the output in the form a stack, which were fed into the stack by fillInStackTrace()
method of Throwable
class, which itself fills in the program control transfer details into the execution stack. The lines starting with at
, are nothing but the values of the execution stack.
In this way the programmer can understand where in code the actual problem is.
Along with the printStackTrace()
method, it's a good idea to use e.getmessage()
.
Another good option for handling this kind of option is the pprint
module, which (among other things) pretty prints long lists with one element per line:
>>> import sys
>>> import pprint
>>> pprint.pprint(sys.path)
['',
'/usr/lib/python27.zip',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/lib/python2.7/site-packages',
'/usr/lib/python2.7/site-packages/PIL',
'/usr/lib/python2.7/site-packages/gst-0.10',
'/usr/lib/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
'/usr/lib/python2.7/site-packages/webkit-1.0']
>>>
How about
XmlSerializer xs = new XmlSerializer(typeof(user[]));
using (Stream ins = File.Open(@"c:\some.xml", FileMode.Open))
foreach (user o in (user[])xs.Deserialize(ins))
userList.Add(o);
Not particularly fancy but it should work.
This is a class which you might find very convenient for reading embedded resource files from the current Assembly
:
using System.IO;
using System.Linq;
using System.Text;
public static class EmbeddedResourceUtils
{
public static string ReadFromResourceFile(string endingFileName)
{
var assembly = Assembly.GetExecutingAssembly();
var manifestResourceNames = assembly.GetManifestResourceNames();
foreach (var resourceName in manifestResourceNames)
{
var fileNameFromResourceName = _GetFileNameFromResourceName(resourceName);
if (!fileNameFromResourceName.EndsWith(endingFileName))
{
continue;
}
using (var manifestResourceStream = assembly.GetManifestResourceStream(resourceName))
{
if (manifestResourceStream == null)
{
continue;
}
using (var streamReader = new StreamReader(manifestResourceStream))
{
return streamReader.ReadToEnd();
}
}
}
return null;
}
// https://stackoverflow.com/a/32176198/3764804
private static string _GetFileNameFromResourceName(string resourceName)
{
var stringBuilder = new StringBuilder();
var escapeDot = false;
var haveExtension = false;
for (var resourceNameIndex = resourceName.Length - 1;
resourceNameIndex >= 0;
resourceNameIndex--)
{
if (resourceName[resourceNameIndex] == '_')
{
escapeDot = true;
continue;
}
if (resourceName[resourceNameIndex] == '.')
{
if (!escapeDot)
{
if (haveExtension)
{
stringBuilder.Append('\\');
continue;
}
haveExtension = true;
}
}
else
{
escapeDot = false;
}
stringBuilder.Append(resourceName[resourceNameIndex]);
}
var fileName = Path.GetDirectoryName(stringBuilder.ToString());
return fileName == null ? null : new string(fileName.Reverse().ToArray());
}
}
If you're removing a commit and don't want to keep its changes @ferit has a good solution.
If you want to add that commit to the current branch, but doesn't make sense to be part of the current pr, you can do the following instead:
git rebase -i HEAD~n
git reset HEAD^ --soft
to uncommit the changes and get them back in a staged state.git push --force
to update the remote branch without your removed commit.Now you'll have removed the commit from your remote, but will still have the changes locally.
Gitk
sometime painful for me to read.
Motivate me to write GitVersionTree.
The manual page (or the online GNU manual) pretty much explains everything.
For each result, command {}
is executed. All occurences of {}
are replaced by the filename. ;
is prefixed with a slash to prevent the shell from interpreting it.
Each result is appended to command
and executed afterwards. Taking the command length limitations into account, I guess that this command may be executed more times, with the manual page supporting me:
the total number of invocations of the command will be much less than the number of matched files.
Note this quote from the manual page:
The command line is built in much the same way that xargs builds its command lines
That's why no characters are allowed between {}
and +
except for whitespace. +
makes find detect that the arguments should be appended to the command just like xargs
.
Luckily, the GNU implementation of mv
can accept the target directory as an argument, with either -t
or the longer parameter --target
. It's usage will be:
mv -t target file1 file2 ...
Your find
command becomes:
find . -type f -iname '*.cpp' -exec mv -t ./test/ {} \+
From the manual page:
-exec command ;
Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory.
There are multiple frameworks that solve this problem. Just to name a few:
Swift:
Objective-C:
You can use Floern's solution. You may also want to disable the input while you set the color to gray. http://www.w3schools.com/tags/att_input_disabled.asp
One way to convert to string is to use astype:
total_rows['ColumnID'] = total_rows['ColumnID'].astype(str)
However, perhaps you are looking for the to_json
function, which will convert keys to valid json (and therefore your keys to strings):
In [11]: df = pd.DataFrame([['A', 2], ['A', 4], ['B', 6]])
In [12]: df.to_json()
Out[12]: '{"0":{"0":"A","1":"A","2":"B"},"1":{"0":2,"1":4,"2":6}}'
In [13]: df[0].to_json()
Out[13]: '{"0":"A","1":"A","2":"B"}'
Note: you can pass in a buffer/file to save this to, along with some other options...
Use CSS cursor: pointer
if I remember correctly.
Either in your CSS file:
.link_cursor
{
cursor: pointer;
}
Then just add the following HTML to any elements you want to have the link cursor: class="link_cursor"
(the preferred method.)
Or use inline CSS:
<a style="cursor: pointer;">
I came out with another solution which would not promise fewer operations, neither less time consumption, but it should be tried to see if it can be a good-enough heuristic to provide less time consumption in huge series of sock pairing.
Preconditions: There is no guarantee that there are the same socks. If they are of the same color it doesn't mean they have the same size or pattern. Socks are randomly shuffled. There can be odd number of socks (some are missing, we don't know how many). Prepare to remember a variable "index" and set it to 0.
The result will have one or two piles: 1. "matched" and 2. "missing"
Heuristic:
Also, there could be added check for damaged socks also, as if the removal of those. It could be inserted between 2 and 3, and between 13 and 14.
I'm looking forward to hear about any experiences or corrections.
I used the following property which works fine for me:
$('#selector').dialog({
minHeight: 'auto'
});
Here's the example:
// Test
public void foo() {
C c = new C();
A s;
s = ((A.B)c).get();
System.out.println(s.getR());
}
// classes
class C {}
class A {
public class B extends C{
A get() {return A.this;}
}
public String getR() {
return "This is string";
}
}
You can't solve it. Simply answer1.sum()==0
, and you can't perform a division by zero.
This happens because answer1
is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
nan
is returned in this case because of the division by zero.
Now to solve your problem you could:
scipy/numpy
function that does exactly what you want! Check out @Warren Weckesser answer.Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:
exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
where above x=3* 1089
and y=3* 1093
. Now, the argument of this exponential is
-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06
For the denominator you could proceed similarly but obtain that log(1+exp(-z+k))
is already rounded to 0
, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000
. You then have that your result is
exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089
in the numerator and the first number 1000
at the denominator):
exp(3*(1089-1000))=exp(-267)
For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):
Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
The difference between this number and the exponent above is +1.7053025658242404e-13
, so the approximation we made at the denominator was fine.
The final result is
'exp(-266.99999385580668) = 1.1050349147204485e-116
From wolfram alpha is (link)
1.105034914720621496.. × 10^-116 # Wolfram alpha.
and again, it is safe to use numpy here too.
As pointed out by @Jayan in another post, the solution was to do the following
import jenkins.model.*
jenkins = Jenkins.instance
Then I was able to do the rest of my scripting the way it was.
The following syntax fixes it for you:
curl -v -F key1=value1 -F upload=@localfilename URL
I have put together a collection of categories for NSData and NSString which uses solutions found on Jeff LaMarche's blog and some hints by Quinn Taylor here on Stack Overflow.
It uses categories to extend NSData to provide AES256 encryption and also offers an extension of NSString to BASE64-encode encrypted data safely to strings.
Here's an example to show the usage for encrypting strings:
NSString *plainString = @"This string will be encrypted";
NSString *key = @"YourEncryptionKey"; // should be provided by a user
NSLog( @"Original String: %@", plainString );
NSString *encryptedString = [plainString AES256EncryptWithKey:key];
NSLog( @"Encrypted String: %@", encryptedString );
NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );
Get the full source code here:
Thanks for all the helpful hints!
-- Michael
you can try this also
from docx import Document
document = Document('demo.docx')
for para in document.paragraphs:
print(para.text)
The TimeOfDay
property returns a TimeSpan
value.
Try the following code:
TimeSpan time = DateTime.Now.TimeOfDay;
if (time > new TimeSpan(11, 59, 00) //Hours, Minutes, Seconds
&& time < new TimeSpan(13, 01, 00)) {
//match found
}
Also, new DateTime()
is the same as DateTime.MinValue
and will always be equal to 1/1/0001 12:00:00 AM
. (Value types cannot have non-empty default values) You want to use DateTime.Now
.
Things to ponder:
this
is your code refering togetElementById
usually document.getElementById
?The operators <-
and =
assign into the environment in which they are evaluated. The operator <-
can be used anywhere, whereas the operator =
is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.
I would rewrite your dequeue function as:
std::string FileQueue::dequeue(const std::chrono::milliseconds& timeout)
{
std::unique_lock<std::mutex> lock(qMutex);
while(q.empty()) {
if (populatedNotifier.wait_for(lock, timeout) == std::cv_status::timeout )
return std::string();
}
std::string ret = q.front();
q.pop();
return ret;
}
It is shorter and does not have duplicate code like your did. Only issue it may wait longer that timeout. To prevent that you would need to remember start time before loop, check for timeout and adjust wait time accordingly. Or specify absolute time on wait condition.
The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.
Examples:
auto a = 0.0f; // a is float
auto b = std::vector<int>(); // b is std::vector<int>()
MyType foo() { return MyType(); }
auto c = foo(); // c is MyType
You cannot return anonymous types from a class... (Well, you can, but you have to cast them to object first and then use reflection at the other side to get the data out again) so you have to create a small class for the data to be contained within.
class ProjectNameAndId
{
public string Name { get; set; }
public string Id { get; set; }
}
Then in your LINQ statement:
select new ProjectNameAndId { Name = pro.ProjectName, Id = pro.ProjectId };
This will work for any resolution,
button{
position:absolute;
bottom: 5%;
right:20%;
}
WARNING: Security researches have found several poisoned packages on PyPI, including a package named
urllib
, which will 'phone home' when installed. If you usedpip install urllib
some time after June 2017, remove that package as soon as possible.
You can't, and you don't need to.
urllib2
is the name of the library included in Python 2. You can use the urllib.request
library included with Python 3, instead. The urllib.request
library works the same way urllib2
works in Python 2. Because it is already included you don't need to install it.
If you are following a tutorial that tells you to use urllib2
then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2
comes with that version.
Alternatively, install the requests
library for a higher-level and easier to use API. It'll work on both Python 2 and 3.
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
This is a common way to do it:
long l = Long.parseLong(str);
There is also this method: Long.valueOf(str);
Difference is that parseLong
returns a primitive long
while valueOf
returns a new Long()
object.
I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
In my case I was getting this error when trying to run python manage.py runserver
when not connected to my project's virtual environment.
Just had this issue with an Outlook client going through a Exchange server to an external address on Windows XP. Clearing the temp files seemed to do the trick.
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
Use which.min
:
df <- data.frame(Name=c('A','B','C','D'), Amount=c(150,120,175,160))
df[which.min(df$Amount),]
> df[which.min(df$Amount),]
Name Amount
2 B 120
From the help docs:
Determines the location, i.e., index of the (first) minimum or maximum of a numeric (or logical) vector.
Out of experience, I think the correct maximum z-index
is 2147483638.
I've used includes
from Lodash
which is really similar to the native.
You are probably attempting to use Gmail's servers on port 25 to deliver mail to a third party over an unauthenticated connection. Gmail doesn't let you do this, because then anybody could use Gmail's servers to send mail to anybody else. This is called an open relay and was a common enabler of spam in the early days. Open relays are no longer acceptable on the Internet.
You will need to ask your SMTP client to connect to Gmail using an authenticated connection, probably on port 587.
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
i no expert, but this works for me..
$sql = "desc MyTable";
$result = @mysql_query($sql);
while($row = @mysql_fetch_array($result)){
echo $row[0]."<br>"; // returns the first column of array. in this case Field
// the below code will return a full array-> Field,Type,Null,Key,Default,Extra
// for ($c=0;$c<sizeof($row);$c++){echo @$row[$c]."<br>";}
}
Look at my version :)
- (void)keyboardWasShown:(NSNotification *)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect bkgndRect = cellSelected.superview.frame;
bkgndRect.size.height += kbSize.height;
[cellSelected.superview setFrame:bkgndRect];
[tableView setContentOffset:CGPointMake(0.0, cellSelected.frame.origin.y-kbSize.height) animated:YES];
}
- (void)keyboardWasHidden:(NSNotification *)aNotification
{
[tableView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
To view all the changes in an un-popped stash:
git stash show -p stash@{0}
To view the changes of one particular file in an un-popped stash:
git diff HEAD stash@{0} -- path/to/filename.php
None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:
/**
* Removes URL parameters
* @param removeParams - param array
*/
function removeURLParameters(removeParams) {
const deleteRegex = new RegExp(removeParams.join('=|') + '=')
const params = location.search.slice(1).split('&')
let search = []
for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])
window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
}
removeURLParameters(['param1', 'param2'])
Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.
csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv
Replacing 2 with the column number will effectively extract the column data you are looking for.
If you need to refer them somewhere in the Java Code, you'd rahter put your files into the "res" directory.
And all files in the res folder will be indexed in the R file, which makes it much faster (and much easier!) to load them.
This works for me:
CSS
.form-group.required.control-label:before{
content: "*";
color: red;
}
OR
.form-group.required.control-label:after{
content: "*";
color: red;
}
Basic HTML
<div class="form-group required control-label">
<input class="form-control" />
</div>
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
It really is an "it depends" kinda question. Some general points:
You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.
For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.
In this case you might want to use the functions np.hstack and np.vstack
arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]
arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]
You also can use the np.concatenate function.
Cheers
To activate the installRelease
task, you simply need a signingConfig
. That is all.
From http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Android-tasks:
Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing).
Install tasks
-------------
installDebug - Installs the Debug build
installDebugTest - Installs the Test build for the Debug build
installRelease - Installs the Release build
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build
uninstallDebugTest - Uninstalls the Test build for the Debug build
uninstallRelease - Uninstalls the Release build <--- release
installRelease
task:Example build.gradle
:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId 'demo'
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName '1.0'
}
signingConfigs {
release {
storeFile <file>
storePassword <password>
keyAlias <alias>
keyPassword <password>
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
String.Equals
does offer overloads to handle casing and culture-aware comparison. If your code doesn't make use of these, the devs may just be used to Java, where (as Matthew says), you must use the .Equals method to do content comparisons.
I think that parse_str is what you're looking for, something like this should do the trick for you:
parse_str($_SERVER['QUERY_STRING'], $vars);
Then the $vars
array will hold all the passed arguments.
For Swift IOS8 onwards based on OScarsWyck answer:
yourUILabel.layer.masksToBounds = true
yourUILabel.layer.cornerRadius = 8.0
For completeness: Instead of using def
you could give a name to a lambda
function:
first2 = lambda s: s[:2]
Use setInterval
instead of setTimeout
. Though in this case either will be fine but setTimeout
inherently triggers only once setInterval
continues indefinitely.
<script language="javascript">
setInterval(function(){
window.location.reload(1);
}, 30000);
</script>
After data.clear()
it will definitely start again from the zero index.
Whenever I use the moment.js
library I specify the desired format this way:
moment(<your Date goes here>).format("DD-MMM-YYYY")
or
moment(<your Date goes here>).format("DD/MMM/YYYY")
... etc I hope you get the idea
Inside the format function, you put the desired format. The example above will get rid of all unwanted elements from the date such as minutes and seconds
You put <=
and it will catch the given date too. You can replace it with <
only.
Here's a Linq
version:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
Example:
git tag -a v1.2 9fceb02 -m "Message here"
Where 9fceb02
is the beginning part of the commit id.
You can then push the tag using git push origin v1.2
.
You can do git log
to show all the commit id's in your current branch.
There is also a good chapter on tagging in the Pro Git book.
Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at another answer.
Try this:
String numberStr = "3.5";
Float number = null;
try {
number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
System.out.println("numberStr is not a number");
}
in Windows in the search option Go to administrative tools>component services>OracleServiceXE(start this service)
You can use fiddler web debugger to import the HAR and then it is very easy from their on... Ctrl+A (select all) then Ctrl+c (copy summary) then paste in excel and have fun
a) If you want 0 when value is null
SELECT isnull(PartNum,0) AS PartNumber, PartID
FROM Part
b) If you want 0 when value is null and otherwise 1
SELECT
(CASE
WHEN PartNum IS NULL THEN 0
ELSE 1
END) AS PartNumber,
PartID
FROM Part
Solved:
forgot my password
.Sample:
git clone https://<bitbucket_id>@bitbucket.org/<repo>
In the MVC architectural pattern, JSPs represent the view layer. Embedding Java code in JSPs is considered a bad practice.
You can use JSTL, freeMarker, and velocity with JSP as a "template engine".
The data provider to those tags depends on frameworks that you are dealing with. Struts 2 and WebWork as an implementation for the MVC pattern uses OGNL "very interesting technique to expose Beans properties to JSP".
I had to create a timer for teachers grading students' work. Here's one I used which is entirely based on elapsed time since the grading begun by storing the system time at the point that the page is loaded, and then comparing it every half second to the system time at that point:
var startTime = Math.floor(Date.now() / 1000); //Get the starting time (right now) in seconds
localStorage.setItem("startTime", startTime); // Store it if I want to restart the timer on the next page
function startTimeCounter() {
var now = Math.floor(Date.now() / 1000); // get the time now
var diff = now - startTime; // diff in seconds between now and start
var m = Math.floor(diff / 60); // get minutes value (quotient of diff)
var s = Math.floor(diff % 60); // get seconds value (remainder of diff)
m = checkTime(m); // add a leading zero if it's single digit
s = checkTime(s); // add a leading zero if it's single digit
document.getElementById("idName").innerHTML = m + ":" + s; // update the element where the timer will appear
var t = setTimeout(startTimeCounter, 500); // set a timeout to update the timer
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
startTimeCounter();
This way, it really doesn't matter if the 'setTimeout' is subject to execution delays, the elapsed time is always relative the system time when it first began, and the system time at the time of update.
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
Based on @Evil Trout's most voted answer I created a custom method in my ViewController class, like shown bellow:
- (void) modifyTextField:(UITextField *)textField
{
UIView *paddingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
textField.leftView = paddingView;
textField.leftViewMode = UITextFieldViewModeAlways;
textField.rightView = paddingView;
textField.rightViewMode = UITextFieldViewModeAlways;
[textField setBackgroundColor:[UIColor whiteColor]];
[textField setTextColor:[UIColor blackColor]];
}
Now I can call that method inside (viewDidLoad method) and send any of my TextFields to that method and add padding for both right and left, and give text and background colors by writing just one line of code, as follows:
[self modifyTextField:self.firstNameTxtFld];
This Worked perfectly on iOS 7! I know that adding too much Views might make this a bit heavier class to be loaded. But when concerned about the difficulty in other solutions, I found myself more biased to this method and more flexible with using this way. ;)
Thanks for the Hack "Evil Trout"! (bow)
I thought I should update this answer's code snippet with Swift:
Since Swift allow us to write extensions for the existing classes, let's write it in that way.
extension UITextField {
func addPaddingToTextField() {
let paddingView: UIView = UIView.init(frame: CGRectMake(0, 0, 8, 20))
self.leftView = paddingView;
self.leftViewMode = .Always;
self.rightView = paddingView;
self.rightViewMode = .Always;
self.backgroundColor = UIColor.whiteColor()
self.textColor = UIColor.blackColor()
}
}
Usage:
self.firstNameTxtFld.addPaddingToTextField()
Hope this would be helpful to somebody else out there!
Cheers!
You need to add it to an axes. A Circle
is a subclass of an Patch
, and an axes
has an add_patch
method. (You can also use add_artist
but it's not recommended.)
Here's an example of doing this:
import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)
fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles.png')
This results in the following figure:
The first circle is at the origin, but by default clip_on
is True
, so the circle is clipped when ever it extends beyond the axes
. The third (green) circle shows what happens when you don't clip the Artist
. It extends beyond the axes (but not beyond the figure, ie the figure size is not automatically adjusted to plot all of your artists).
The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (fig.gca()
returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.
Here's a continuation of the example, showing how units matter:
circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
ax = plt.gca()
ax.cla() # clear things for fresh plot
# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')
which results in:
You can see how I set the fill of the 2nd circle to False
, which is useful for encircling key results (like my yellow data point).
I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have
typedef enum{
a,
b,
c
}test_t
and in test.c we have
void foo()
{
test_t test;
...
}
during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.
Uninstall composer
To remove just composer package itself from Ubuntu 16.04 (Xenial Xerus) execute on terminal:
sudo apt-get remove composer
Uninstall composer and it's dependent packages
To remove the composer package and any other dependant package which are no longer needed from Ubuntu Xenial.
sudo apt-get remove --auto-remove composer
Purging composer
If you also want to delete configuration and/or data files of composer from Ubuntu Xenial then this will work:
sudo apt-get purge composer
To delete configuration and/or data files of composer and it's dependencies from Ubuntu Xenial then execute:
sudo apt-get purge --auto-remove composer
https://www.howtoinstall.co/en/ubuntu/xenial/composer?action=remove
They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.
Something like this:
typedef struct vec
{
unsigned char* _mem;
unsigned long _elems;
unsigned long _elemsize;
unsigned long _capelems;
unsigned long _reserve;
};
vec* vec_new(unsigned long elemsize)
{
vec* pvec = (vec*)malloc(sizeof(vec));
pvec->_reserve = 10;
pvec->_capelems = pvec->_reserve;
pvec->_elemsize = elemsize;
pvec->_elems = 0;
pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
return pvec;
}
void vec_delete(vec* pvec)
{
free(pvec->_mem);
free(pvec);
}
void vec_grow(vec* pvec)
{
unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
free(pvec->_mem);
pvec->_mem = mem;
pvec->_capelems += pvec->_reserve;
}
void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
assert(elemsize == pvec->_elemsize);
if (pvec->_elems == pvec->_capelems) {
vec_grow(pvec);
}
memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
pvec->_elems++;
}
unsigned long vec_length(vec* pvec)
{
return pvec->_elems;
}
void* vec_get(vec* pvec, unsigned long index)
{
assert(index < pvec->_elems);
return (void*)(pvec->_mem + (index * pvec->_elemsize));
}
void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}
void playwithvec()
{
vec* pvec = vec_new(sizeof(int));
for (int val = 0; val < 1000; val += 10) {
vec_push_back(pvec, &val, sizeof(val));
}
for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
int val;
vec_copy_item(pvec, &val, index);
printf("vec(%d) = %d\n", index, val);
}
vec_delete(pvec);
}
Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.
Here is working solution:
Output:
public class XmlTest {
private static final Logger log = LoggerFactory.getLogger(XmlTest.class);
@Test
public void createDefaultBook() throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(new Book(), writer);
log.debug("Book xml:\n {}", writer.toString());
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "book")
public static class Book {
@XmlElementRef(name = "price")
private Price price = new Price();
}
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "price")
public static class Price {
@XmlAttribute(name = "drawable")
private Boolean drawable = true; //you may want to set default value here
@XmlValue
private int priceValue = 1234;
public Boolean getDrawable() {
return drawable;
}
public void setDrawable(Boolean drawable) {
this.drawable = drawable;
}
public int getPriceValue() {
return priceValue;
}
public void setPriceValue(int priceValue) {
this.priceValue = priceValue;
}
}
}
Output:
22:00:18.471 [main] DEBUG com.grebski.stack.XmlTest - Book xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book>
<price drawable="true">1234</price>
</book>
Looks like /e
option is what you need, it'll skip same files/directories.
robocopy c:\data c:\backup /e
If you run the command twice, you'll see the second round is much faster since it skips a lot of things.
Create a new array with a thousand true
values:
var items = Enumerable.Repeat<bool>(true, 1000).ToArray(); // Or ToList(), etc.
Similarly, you can generate integer sequences:
var items = Enumerable.Range(0, 1000).ToArray(); // 0..999
Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.
I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle
'd bytestrings generated by pickle.dumps(...)
.
The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain
object.
$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma
from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)
brain['a'] = [1]*10000
brain['a']
# >>> [1,1,1,1,...]
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
The error is also caused by quirky handling of quotes and single qutoes. To include single quotes inside the query, use doubled single quotes.
This won't work
select dbms_xmlgen.getxml("Select ....") XML from dual;
or this either
select dbms_xmlgen.getxml('Select .. where something='red'..') XML from dual;
but this DOES work
select dbms_xmlgen.getxml('Select .. where something=''red''..') XML from dual;
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
Try the following (note that there should not be a space between the VAR
, =
, and GREG
).
SET VAR=GREG
ECHO %VAR%
PAUSE
Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type
class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.
Try this, noting that the grammar of HTML is too complex for regular expressions to be correct 100% of the time:
var regex = /(<([^>]+)>)/ig
, body = "<p>test</p>"
, result = body.replace(regex, "");
console.log(result);
If you're willing to use a library such as jQuery, you could simply do this:
console.log($('<p>test</p>').text());
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
@doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.
import pandas as pd
df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
fig = plt.figure(figsize=(14,8))
for i in df.columns:
ax=plt.subplot(2,1,i+1)
df[[i]].plot(ax=ax)
print(i)
plt.show()
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
There is no best IDE. You make it as good as you get used using it.
Be careful, when you register by
LocalBroadcastManager.getInstance(this).registerReceiver()
you can't unregister by
unregisterReceiver()
you must use
LocalBroadcastManager.getInstance(this).unregisterReceiver()
or app will crash, log as follow:
09-30 14:00:55.458 19064-19064/com.jialan.guangdian.view E/AndroidRuntime: FATAL EXCEPTION: main Process: com.jialan.guangdian.view, PID: 19064 java.lang.RuntimeException: Unable to stop service com.google.android.exoplayer.demo.player.PlayService@141ba331: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.ActivityThread.handleStopService(ActivityThread.java:2941) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.google.android.exoplayer.demo.player.PlayService$PlayStatusReceiver@19538584 at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:769) at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1794) at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:510) at com.google.android.exoplayer.demo.player.PlayService.onDestroy(PlayService.java:542) at android.app.ActivityThread.handleStopService(ActivityThread.java:2924) at android.app.ActivityThread.access$2200(ActivityThread.java:148) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1395) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5310) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
This will match yyyy-mm-dd
and also yyyy-m-d
:
^\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])$
If you're looking for an exact match for yyyy-mm-dd
then try this
^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$
or use this one if you need to find a date inside a string like The date is 2017-11-30
\d{4}\-(0?[1-9]|1[012])\-(0?[1-9]|[12][0-9]|3[01])*
using C++ 14:
#include <string>
#include <vector>
std::vector<std::string> listbox;
...
std::vector<std::string> strarr {"ram","mohan","sita"};
for (const auto &str : strarr)
{
listbox.push_back(str);
}
I can't comment on the top answer, but a swift implementation would be:
self.tableView.reloadSections([0], with: UITableViewRowAnimation.fade)
you could include as many sections as you want to update in the first argument for reloadSections.
Other animations available from the docs: https://developer.apple.com/reference/uikit/uitableviewrowanimation
fade The inserted or deleted row or rows fade into or out of the table view.
right The inserted row or rows slide in from the right; the deleted row or rows slide out to the right.
left The inserted row or rows slide in from the left; the deleted row or rows slide out to the left.
top The inserted row or rows slide in from the top; the deleted row or rows slide out toward the top.
bottom The inserted row or rows slide in from the bottom; the deleted row or rows slide out toward the bottom.
case none The inserted or deleted rows use the default animations.
middle The table view attempts to keep the old and new cells centered in the space they did or will occupy. Available in iPhone 3.2.
automatic The table view chooses an appropriate animation style for you. (Introduced in iOS 5.0.)
I ran into the exact same issue. After compiling without the -fexceptions
build flag, the file compiled with no issue
You can use IPython's %pdb
magic. Just call %pdb
in IPython and when an error occurs, you're automatically dropped to ipdb
. While you don't have the stepping immediately, you're in ipdb
afterwards.
This makes debugging individual functions easy, as you can just load a file with %load
and then run a function. You could force an error with an assert
at the right position.
%pdb
is a line magic. Call it as %pdb on
, %pdb 1
, %pdb off
or %pdb 0
. If called without argument it works as a toggle.
I second @erickson: The pure data-transfer speed penalty is negligible. Modern CPUs reach a crypto/AES throughput of several hundred MBit/s. So unless you are on resource constrained system (mobile phone) TLS/SSL is fast enough for slinging data around.
But keep in mind that encryption makes caching and load balancing much harder. This might result in a huge performance penalty.
But connection setup is really a show stopper for many application. On low bandwidth, high packet loss, high latency connections (mobile device in the countryside) the additional roundtrips required by TLS might render something slow into something unusable.
For example we had to drop the encryption requirement for access to some of our internal web apps - they where next to unusable if used from china.
The following should tell you. From the docs:
fs.lstatSync(path_string).isDirectory()
Objects returned from fs.stat() and fs.lstat() are of this type.
stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() (only valid with fs.lstat()) stats.isFIFO() stats.isSocket()
The above solution will throw
an Error
if; for ex, the file
or directory
doesn't exist.
If you want a true
or false
approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
as mentioned by Joseph in the comments below.
You can use NPOI to do it.
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");
sheet.addMergedRegion(new CellRangeAddress(
1, //first row (0-based)
1, //last row (0-based)
1, //first column (0-based)
2 //last column (0-based)
));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
$('#div-id').click(function(){
location.reload();
});
This is the correct syntax.
$('#div-id').html(newContent); //This doesnt work
You can define UTF-8 .properties files to store your translations and use ResourceBundle, to get values. To avoid problems you can change encoding:
String value = RESOURCE_BUNDLE.getString(key);
return new String(value.getBytes("ISO-8859-1"), "UTF-8");
Perl solution similar to Mat's awk solution:
perl -F'\|' -lane 'print $#F+1; exit' stores.dat
I've tested this on a file with 1000000 columns.
If the field separator is whitespace (one or more spaces or tabs) instead of a pipe:
perl -lane 'print $#F+1; exit' stores.dat
After getting some inspiration from Orr Sella's blog post I wrote a pre-commit hook (resides in ~/.git/templates/hooks
) which would set specific usernames and e-mail addresses based on the information inside a local repositorie's ./.git/config
:
You have to place the path to the template directory into your ~/.gitconfig
:
[init]
templatedir = ~/.git/templates
Then each git init
or git clone
will pick up that hook and will apply the user data during the next git commit
. If you want to apply the hook to already exisiting repos then just run a git init
inside the repo in order to reinitialize it.
Here is the hook I came up with (it still needs some polishing - suggestions are welcome). Save it either as
~/.git/templates/hooks/pre_commit
or
~/.git/templates/hooks/post-checkout
and make sure it is executable: chmod +x ./post-checkout || chmod +x ./pre_commit
#!/usr/bin/env bash
# -------- USER CONFIG
# Patterns to match a repo's "remote.origin.url" - beginning portion of the hostname
git_remotes[0]="Github"
git_remotes[1]="Gitlab"
# Adjust names and e-mail addresses
local_id_0[0]="my_name_0"
local_id_0[1]="my_email_0"
local_id_1[0]="my_name_1"
local_id_1[1]="my_email_1"
local_fallback_id[0]="${local_id_0[0]}"
local_fallback_id[1]="${local_id_0[1]}"
# -------- FUNCTIONS
setIdentity()
{
local current_id local_id
current_id[0]="$(git config --get --local user.name)"
current_id[1]="$(git config --get --local user.email)"
local_id=("$@")
if [[ "${current_id[0]}" == "${local_id[0]}" &&
"${current_id[1]}" == "${local_id[1]}" ]]; then
printf " Local identity is:\n"
printf "» User: %s\n» Mail: %s\n\n" "${current_id[@]}"
else
printf "» User: %s\n» Mail: %s\n\n" "${local_id[@]}"
git config --local user.name "${local_id[0]}"
git config --local user.email "${local_id[1]}"
fi
return 0
}
# -------- IMPLEMENTATION
current_remote_url="$(git config --get --local remote.origin.url)"
if [[ "$current_remote_url" ]]; then
for service in "${git_remotes[@]}"; do
# Disable case sensitivity for regex matching
shopt -s nocasematch
if [[ "$current_remote_url" =~ $service ]]; then
case "$service" in
"${git_remotes[0]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[0]}"
setIdentity "${local_id_0[@]}"
exit 0
;;
"${git_remotes[1]}" )
printf "\n»» An Intermission\n» %s repository found." "${git_remotes[1]}"
setIdentity "${local_id_1[@]}"
exit 0
;;
* )
printf "\n» pre-commit hook: unknown error\n» Quitting.\n"
exit 1
;;
esac
fi
done
else
printf "\n»» An Intermission\n» No remote repository set. Using local fallback identity:\n"
printf "» User: %s\n» Mail: %s\n\n" "${local_fallback_id[@]}"
# Get the user's attention for a second
sleep 1
git config --local user.name "${local_fallback_id[0]}"
git config --local user.email "${local_fallback_id[1]}"
fi
exit 0
EDIT:
So I rewrote the hook as a hook and command in Python. Additionally it's possible to call the script as a Git command (git passport
), too. Also it's possible to define an arbitrary number of IDs inside a configfile (~/.gitpassport
) which are selectable on a prompt. You can find the project at github.com: git-passport - A Git command and hook written in Python to manage multiple Git accounts / user identities.
two ways:
x = [0] * 10
x = [0 for i in xrange(10)]
Edit: replaced range
by xrange
to avoid creating another list.
Also: as many others have noted including Pi and Ben James, this creates a list
, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array
module, as explained in the other answers in this thread.
Something I'd like to add, since this is error 191 first question on google:
When redirecting to facebook instead of your own site for a signed request, you might experience this error if the user has secure browsing on and your app does redirect to facebook without SSL.
Scripting is inevitable.
This isn't provided because of the security risk. <input type='file' />
is closest, but not what you are looking for.
Checkout this example that uses Javascript to achieve what you want.
If the OS is windows, you can use VB scripts to access the core control files to browse for a folder.
Do you use the ob_start(ob_gzhandler)
function? If so and If you output any content above the ob_start(ob_gzhandler)
function, you'll get this error. You can don't use this function or don't output content above this function. The ob_gzhandler
callback function will determine what type of content encoding the browser will accept and will return its output accordingly. So if you output content above this function, the content's encoding maybe different from the output content of ob_gzhandler
and that cause this error.
For Kotlin Users
You just need to add ? with Intent in onActivityResult
as the data can be null
if user cancels the transaction or anything goes wrong. So we need to define data as nullable
in onActivityResult
Just replace onActivityResult
signature of SampleActivity with below:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
It sounds like you want a sparse array. A normal array would have 24 items in it, but a sparse array would have 3. In Perl we emulate sparse arrays with hashes:
#!/usr/bin/perl
use strict;
use warnings;
my %sparse;
@sparse{0, 5, 23} = (1 .. 3);
print "there are ", scalar keys %sparse, " items in the sparse array\n",
map { "\t$sparse{$_}\n" } sort { $a <=> $b } keys %sparse;
The keys
function in scalar context will return the number of items in the sparse array. The only downside to using a hash to emulate a sparse array is that you must sort the keys before iterating over them if their order is important.
You must also remember to use the delete
function to remove items from the sparse array (just setting their value to undef is not enough).
Password Strength Algorithm:
Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more
Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case
Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers
Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character
Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters
Password Text Range:
>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak
Settings Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"
Check password
function checkPassword(strPassword)
{
// Reset combination count
var nScore = 0;
// Password length
// -- Less than 4 characters
if (strPassword.length < 5)
{
nScore += 5;
}
// -- 5 to 7 characters
else if (strPassword.length > 4 && strPassword.length < 8)
{
nScore += 10;
}
// -- 8 or more
else if (strPassword.length > 7)
{
nScore += 25;
}
// Letters
var nUpperCount = countContain(strPassword, m_strUpperCase);
var nLowerCount = countContain(strPassword, m_strLowerCase);
var nLowerUpperCount = nUpperCount + nLowerCount;
// -- Letters are all lower case
if (nUpperCount == 0 && nLowerCount != 0)
{
nScore += 10;
}
// -- Letters are upper case and lower case
else if (nUpperCount != 0 && nLowerCount != 0)
{
nScore += 20;
}
// Numbers
var nNumberCount = countContain(strPassword, m_strNumber);
// -- 1 number
if (nNumberCount == 1)
{
nScore += 10;
}
// -- 3 or more numbers
if (nNumberCount >= 3)
{
nScore += 20;
}
// Characters
var nCharacterCount = countContain(strPassword, m_strCharacters);
// -- 1 character
if (nCharacterCount == 1)
{
nScore += 10;
}
// -- More than 1 character
if (nCharacterCount > 1)
{
nScore += 25;
}
// Bonus
// -- Letters and numbers
if (nNumberCount != 0 && nLowerUpperCount != 0)
{
nScore += 2;
}
// -- Letters, numbers, and characters
if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
{
nScore += 3;
}
// -- Mixed case letters, numbers, and characters
if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
{
nScore += 5;
}
return nScore;
}
// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
var nScore = checkPassword(strPassword);
// Get controls
var ctlBar = document.getElementById(strFieldID + "_bar");
var ctlText = document.getElementById(strFieldID + "_text");
if (!ctlBar || !ctlText)
return;
// Set new width
ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";
// Color and text
// -- Very Secure
/*if (nScore >= 90)
{
var strText = "Very Secure";
var strColor = "#0ca908";
}
// -- Secure
else if (nScore >= 80)
{
var strText = "Secure";
vstrColor = "#7ff67c";
}
// -- Very Strong
else
*/
if (nScore >= 80)
{
var strText = "Very Strong";
var strColor = "#008000";
}
// -- Strong
else if (nScore >= 60)
{
var strText = "Strong";
var strColor = "#006000";
}
// -- Average
else if (nScore >= 40)
{
var strText = "Average";
var strColor = "#e3cb00";
}
// -- Weak
else if (nScore >= 20)
{
var strText = "Weak";
var strColor = "#Fe3d1a";
}
// -- Very Weak
else
{
var strText = "Very Weak";
var strColor = "#e71a1a";
}
if(strPassword.length == 0)
{
ctlBar.style.backgroundColor = "";
ctlText.innerHTML = "";
}
else
{
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = strText;
}
}
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{
// Declare variables
var nCount = 0;
for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}
return nCount;
}
You can customize by yourself according to your requirement.
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
What about SYSDATE() ?
<?php
$db = mysql_connect('localhost','user','pass');
mysql_select_db('test_db');
$stmt = "INSERT INTO `test` (`first`,`last`,`whenadded`) VALUES ".
"('{$first}','{$last}','SYSDATE())";
$rslt = mysql_query($stmt);
?>
Look at Difference between NOW(), SYSDATE() & CURRENT_DATE() in MySQL for more info about NOW() and SYSDATE().
For those using PowerShell
PS C:\> Get-Content create.sql -Raw | sqlite3 auction.db
in your viewWillAppear set the corners as round
yourUITextField.borderStyle = UITextBorderStyleRoundedRect;
SELECT CASE WHEN field IS NULL THEN 'Empty' ELSE field END AS field_alias
Or more idiomatic:
SELECT coalesce(field, 'Empty') AS field_alias
Are you by any chance also using the app EasyTether while connected to your Mac? If you happen to use this app, you're in luck, because the solution is to call:
sudo kextunload -v /System/Library/Extensions/EasyTetherUSBEthernet.kext
from a terminal. I forget if you have to reboot or not.
This will disable tethering, but you can now see your device via adb.
To renable tethering once you're done debugging, use
sudo kextload -v /System/Library/Extensions/EasyTetherUSBEthernet.kext
Of course, if you're not using EasyTether, then hopefully someone else has an idea....