In Microsoft SQL Server Management Studio you can right-click on the database you wish to backup and click Tasks -> Generate Scripts.
This pops open a wizard where you can set the following in order to perform a decent backup of your database, even on a remote server:
Once it's done its thing, you'll have a backup script ready in front of you. Create a new local (or remote) database, and change the first 'USE' statement in the script to use your new database. Save the script in a safe place, and go ahead and run it against your new empty database. This should create you a (nearly) duplicate local database you can then backup as you like.
If you have full access to the remote database, you can choose to check 'script all objects' in the wizard's first window and then change the 'Script Database' option to True on the next window. Watch out though, you'll need to perform a full search & replace of the database name in the script to a new database which in this case you won't have to create before running the script. This should create a more accurate duplicate but is sometimes not available due to permissions restrictions.
In my case it was due to passing in \r\n characters inside TestCase's. Not sure why it's causing intermittent issues, as it works most of the time. But if I remove \r\n the test is never inconclusive:
[TestCase("test\r\n1,2\r\n3,4", 1, 2)]
public void My_Test(string message, double latitude, double longitude)
You can create a function with the pattern ShouldSerialize{PropertyName}
which tells the XmlSerializer if it should serialize the member or not.
For example, if your class property is called MyNullableInt
you could have
public bool ShouldSerializeMyNullableInt()
{
return MyNullableInt.HasValue;
}
Here is a full sample
public class Person
{
public string Name {get;set;}
public int? Age {get;set;}
public bool ShouldSerializeAge()
{
return Age.HasValue;
}
}
Serialized with the following code
Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);
Results in the followng XML - Notice there is no Age
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>Chris</Name>
</Person>
I had the same problem: the error was File not found
, while opening HTML
files in chrome, but I resolved it as follows:
BEFORE:
1) I saved a html file abc.html
in a folder name C#
.
2) When I was opening the abc.html
in Google Chrome, it was showing error as "file not found". But it was working fine on Firefox and Internet Explorer.
AFTER:
3) What I did then is, I simply changed the folder name C#
to csharp
without space and re opened it in Chrome. It worked.
4) The moral is: Make sure you don't give any space in a folder name as some browsers don't support it.
How does your .NET Webservice look like?
I had the same effect using ksoap 2.3 from code.google.com. I followed the tutorial on The Code Project (which is great BTW.)
And everytime I used
Integer result = (Integer)envelope.getResponse();
to get the result of a my webservice (regardless of the type, I tried Object, String, int) I ran into the org.ksoap2.serialization.SoapPrimitive
exception.
I found a solution (workaround). The first thing I had to do was to remove the "SoapRpcMethod() attribute from my webservice methods.
[SoapRpcMethod(), WebMethod]
public Object GetInteger1(int i)
{
// android device will throw exception
return 0;
}
[WebMethod]
public Object GetInteger2(int i)
{
// android device will get the value
return 0;
}
Then I changed my Android code to:
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
However, I get a SoapPrimitive object, which has a "value" filed that is private. Luckily the value is passed through the toString()
method, so I use Integer.parseInt(result.toString())
to get my value, which is enough for me, because I don't have any complex types that I need to get from my Web service.
Here is the full source:
private static final String SOAP_ACTION = "http://tempuri.org/GetInteger2";
private static final String METHOD_NAME = "GetInteger2";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://10.0.2.2:4711/Service1.asmx";
public int GetInteger2() throws IOException, XmlPullParserException {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("i");
pi.setValue(123);
request.addProperty(pi);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
return Integer.parseInt(result.toString());
}
he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float
(float)(a.y - b.y) / (a.x - b.x);
A direction quotation from the documentation on 5.3. Tuples and Sequences:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
If you call getcwd it should give you the path:
<?php
echo getcwd();
?>
You have used:
char s[] = "asd";
Here s actually points to the bytes "asd". The address of s, would also point to this location.
If you used:
char *s = "asd";
the value of s and &s would be different, as s would actually be a pointer to the bytes "asd".
You used:
char s[] = "asd";
char **p = &s;
Here s points to the bytes "asd". p is a pointer to a pointer to characters, and has been set to a the address of characters. In other words you have too many indirections in p. If you used char *s = "asd", you could use this additional indirection.
Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").
The following website has both right click and view source disabled.
They fooled you. Just scroll down in view-source.
Furthermore, employing such tactics marks you as unprofessional. Don’t do it.
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
By implementing the SpinnerAdapter for your adapter object i use interested.getItem(i).toString()
Check /var/lib/php/session and its permissions. This dir should be writable by user so the session can be stored
Callback functions are part of the C standard, an therefore also part of C++. But if you are working with C++, I would suggest you use the observer pattern instead: http://en.wikipedia.org/wiki/Observer_pattern
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:
def gen():
x = 0
while True:
yield x
x += 1
g1 = gen()
list(g1) # never ends
Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do
g1 = gen()
[g1.next() for i in range(10)]
Assuming an interactive shell, and you'd like to keep your current command history and also load /etc/profile (which loads environment data including /etc/bashrc and on Mac OS X loads paths defined in /etc/paths.d/ via path_helper), append your command history and do an exec of bash with the login ('-l') option:
history -a && exec bash -l
/appointments?users=1d1,1d2..
is fine. It's pretty much your only sensible option since you can't pass in a body with a GET.
Just set
webView.mediaPlaybackRequiresUserAction = NO;
The autoplay works for me on iOS.
The default behaviour of Newtonsoft.Json is going to find the public
constructors. If your default constructor is only used in containing class or the same assembly, you can reduce the access level to protected
or internal
so that Newtonsoft.Json will pick your desired public
constructor.
Admittedly, this solution is rather very limited to specific cases.
internal Result() { }
public Result(int? code, string format, Dictionary<string, string> details = null)
{
Code = code ?? ERROR_CODE;
Format = format;
if (details == null)
Details = new Dictionary<string, string>();
else
Details = details;
}
Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.
Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:
Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.
The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:
By selecting the correct collation, you get all this done for you, automatically :-)
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
I am having a similar problem. I can get the screen to stay on, but if I use a partial wake lock and the screen is turned off, my onFinish function isn't called until the screen is turned on.
You can check your wake lock using mWakeLock.isHeld(), first of all, to make sure you're getting it. Easiest way is to add that to the code, set a breakpoint on it in the debugger, and then check it.
In my case, I'm getting it, but the partial wake lock doesn't seem to be doing anything. Here's my working code for the screen dim lock.
protected void setScreenLock(boolean on){
if(mWakeLock == null){
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE, TAG);
}
if(on){
mWakeLock.acquire();
}else{
if(mWakeLock.isHeld()){
mWakeLock.release();
}
mWakeLock = null;
}
}
ADDENDUM:
Droid Eris and DROID users are reporting to me that this DOES NOT work on their devices, though it works fine on my G1. What device are you testing on? I think this may be an Android bug.
Hiberante supports the feature of lazy initialization for both entities and collections. Hibernate engine loads only those objects that we are querying for does not other entites or collections.
lazy="false" by default loading initialization mention for the only child is lazy.in case of true that is parent is loading does not support child
I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
You can do the following. Add your ggplot code after the first line of code and end with dev.off()
.
tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()
res=300
specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.
Change width
and height
in the code above depending on the desired output.
Note that this also works for other R
plots including plot
, image
, and pheatmap
.
Other file formats
In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.
Many devices with different screen sizes/ratios/resolutions have come out even in the last five years, including new types of iPhones and iPads. It would be very difficult to customize a website for each device.
Meanwhile, media queries for device-width
, device-height
, and device-aspect-ratio
have been deprecated, so they may not work in future browser versions. (Source: MDN)
TLDR: Design based on browser widths, not devices. Here's a good introduction to this topic.
There are a lot of answers here, but I'll add my approach since I found this post while working on the same problem.
Starting with what we know here are the number from 0 to 16.
Number encoded in bits minimum number of bits to encode
0 000000 1
1 000001 1
2 000010 2
3 000011 2
4 000100 3
5 000101 3
6 000110 3
7 000111 3
8 001000 4
9 001001 4
10 001010 4
11 001011 4
12 001100 4
13 001101 4
14 001110 4
15 001111 4
16 010000 5
looking at the breaks, it shows this table
number <= number of bits
1 0
3 2
7 3
15 4
So, now how do we compute the pattern?
Remember that log base 2 (n) = log base 10 (n) / log base 10 (2)
number logb10 (n) logb2 (n) ceil[logb2(n)]
1 0 0 0 (special case)
3 0.477 1.58 2
7 0.845 2.807 3
8 0.903 3 3 (special case)
15 1.176 3.91 4
16 1.204 4 4 (special case)
31 1.491 4.95 5
63 1.799 5.98 6
Now the desired result matching the first table. Notice how also some values are special cases. 0 and any number which is a powers of 2. These values dont change when you apply ceiling so you know you need to add 1 to get the minimum bit field length.
To account for the special cases add one to the input. The resulting code implemented in python is:
from math import log
from math import ceil
def min_num_bits_to_encode_number(a_number):
a_number=a_number+1 # adjust by 1 for special cases
# log of zero is undefined
if 0==a_number:
return 0
num_bits = int(ceil(log(a_number,2))) # logbase2 is available
return (num_bits)
Add Following Code
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_item:
Intent i = new Intent(this,SecondActivity.class);
this.startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
First of all check if your project is using androidx or android support library. Check gradle.properties file:
android.useAndroidX=true
android.enableJetifier=true
If it contains the above lines, it is using androidx with an old code from some old tutorial.
In build.gradle (module:app)
Use
implementation 'androidx.appcompat:appcompat:1.0.0'
Instead of
compile 'com.android.support:appcompat-v7:28.0.0'
Also in MainActivity.java : Use
import androidx.appcompat.app.AppCompatActivity;
instead of :
import android.support.v7.app.AppCompatActivity;
def isok(mypath):
try:
thepage = urllib.request.urlopen(mypath)
except HTTPError as e:
return 0
except URLError as e:
return 0
else:
return 1
You can using the socket module to simply check if a port is open or not.
It would look something like this.
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
print "Port is open"
else:
print "Port is not open"
sock.close()
int x = 0xFF; //your number - 11111111
How do I for example read a 3 bit integer value starting at the second bit
int y = x & ( 0x7 << 2 ) // 0x7 is 111
// and you shift it 2 to the left
you could submit all parameters with such naming:
params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]
then later you do something like this:
foreach ($_REQUEST['params'] as $item) {
echo $item['topdiameter'];
echo $item['bottomdiameter'];
}
dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
Here are some options for using AJAX to upload files:
AjaxFileUpload - Requires a form element on the page, but uploads the file without reloading the page. See the Demo.
Uploadify - A Flash-based method of uploading files.
Ten Examples of AJAX File Upload - This was posted this year.
UPDATE: Here is a JQuery plug-in for Multiple File Uploading.
Here is a general purpose method which lets you add/subtract any type of unit(Year/Month/Day/Hour/Second etc) in the specified date.
Using Swift 2.2
func addUnitToDate(unitType: NSCalendarUnit, number: Int, date:NSDate) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(
unitType,
value: number,
toDate: date,
options: NSCalendarOptions(rawValue: 0))!
}
print( addUnitToDate(.Day, number: 1, date: NSDate()) ) // Adds 1 Day To Current Date
print( addUnitToDate(.Hour, number: 1, date: NSDate()) ) // Adds 1 Hour To Current Date
print( addUnitToDate(.Minute, number: 1, date: NSDate()) ) // Adds 1 Minute To Current Date
// NOTE: You can use negative values to get backward values too
To delete all files and directories within the current directory:
find . -mtime +3 | xargs rm -Rf
Or alternatively, more in line with the OP's original command:
find . -mtime +3 -exec rm -Rf -- {} \;
Hj, all methods of yours are not working for me, in Fedora KDE 14. I have a dirty way to do bring a window to front, while we're waiting for Oracle to fix this issue.
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
public class FrameMain extends javax.swing.JFrame {
//...
private final javax.swing.JFrame mainFrame = this;
private void toggleVisible() {
setVisible(!isVisible());
if (isVisible()) {
toFront();
requestFocus();
setAlwaysOnTop(true);
try {
//remember the last location of mouse
final Point oldMouseLocation = MouseInfo.getPointerInfo().getLocation();
//simulate a mouse click on title bar of window
Robot robot = new Robot();
robot.mouseMove(mainFrame.getX() + 100, mainFrame.getY() + 5);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//move mouse to old location
robot.mouseMove((int) oldMouseLocation.getX(), (int) oldMouseLocation.getY());
} catch (Exception ex) {
//just ignore exception, or you can handle it as you want
} finally {
setAlwaysOnTop(false);
}
}
}
//...
}
And, this works perfectly in my Fedora KDE 14 :-)
minimumFontSize
has been deprecated with iOS 6. You can use minimumScaleFactor
.
yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;
This will take care of your font size according width of label and text.
A solution using awk
:
$ ms=10000001; awk -v ms=$ms 'BEGIN {x=ms/1000;
s=x%60; x/=60;
m=x%60; x/=60;
h=x%60;
printf("%02d:%02d:%02d.%03d\n", h, m, s, ms%1000)}'
02:46:40.001
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
If you want to get the strings separated by the ,
you can use
string b = a.Split(',')[0];
JoshAdel's solution uses np.newaxis to add a dimension. An alternative is to use reshape() to align the dimensions in preparation for broadcasting.
data = np.array([[1,1,1],[2,2,2],[3,3,3]])
vector = np.array([1,2,3])
data
# array([[1, 1, 1],
# [2, 2, 2],
# [3, 3, 3]])
vector
# array([1, 2, 3])
data.shape
# (3, 3)
vector.shape
# (3,)
data / vector.reshape((3,1))
# array([[1, 1, 1],
# [1, 1, 1],
# [1, 1, 1]])
Performing the reshape() allows the dimensions to line up for broadcasting:
data: 3 x 3
vector: 3
vector reshaped: 3 x 1
Note that data/vector
is ok, but it doesn't get you the answer that you want. It divides each column of array
(instead of each row) by each corresponding element of vector
. It's what you would get if you explicitly reshaped vector
to be 1x3
instead of 3x1
.
data / vector
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
data / vector.reshape((1,3))
# array([[1, 0, 0],
# [2, 1, 0],
# [3, 1, 1]])
getPath()
returns the path used to create the File
object. This return value is not changed based on the location it is run (results below are for windows, separators are obviously different elsewhere)
File f1 = new File("/some/path");
String path = f1.getPath(); // will return "\some\path"
File dir = new File("/basedir");
File f2 = new File(dir, "/some/path");
path = f2.getPath(); // will return "\basedir\some\path"
File f3 = new File("./some/path");
path = f3.getPath(); // will return ".\some\path"
getAbsolutePath()
will resolve the path based on the execution location or drive. So if run from c:\test
:
path = f1.getAbsolutePath(); // will return "c:\some\path"
path = f2.getAbsolutePath(); // will return "c:\basedir\some\path"
path = f3.getAbsolutePath(); // will return "c:\test\.\basedir\some\path"
getCanonicalPath()
is system dependent. It will resolve the unique location the path represents. So if you have any "."s in the path they will typically be removed.
As to when to use them. It depends on what you are trying to achieve. getPath()
is useful for portability. getAbsolutePath()
is useful to find the file system location, and getCanonicalPath()
is particularly useful to check if two files are the same.
If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
And just in case you need the sample in a hurry, here it is in all its plagiarized glory:
using System;
using System.IO;
using System.Security.Cryptography;
namespace RijndaelManaged_Example
{
class RijndaelExample
{
public static void Main()
{
try
{
string original = "Here is some data to encrypt!";
// Create a new instance of the RijndaelManaged
// class. This generates a new key and initialization
// vector (IV).
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.GenerateKey();
myRijndael.GenerateIV();
// Encrypt the string to an array of bytes.
byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);
// Decrypt the bytes to a string.
string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
//Display the original data and the decrypted data.
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Round Trip: {0}", roundtrip);
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
}
}
static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
byte[] encrypted;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
// Create an RijndaelManaged object
// with the specified key and IV.
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.IV = IV;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
}
A less orthodox approach might be
SELECT * FROM table_name
WHERE LEFT(table_name.date, 7) = LEFT(CURDATE(), 7)
AND table_name.date <= CURDATE();
as a date being between the first of a month and now is equivalent to a date being in this month, and before now. I do feel that this is a bit easier on the eyes than some other approaches, though.
This is one of the dumb mistakes I've done. I spent a lot of time trying to debug this problem and tried all the responses posted above, but in the end, it was one of my many dumb mistakes.
I was using org.apache.logging.log4j.Logger
(:fml:) whereas I should have used org.apache.log4j.Logger
. Using this correct logger saved my evening.
Its best to use auto on the dimension that should respect the aspect ratio. If you do not set the other property to auto, most browsers nowadays will assume that you want to respect the aspect ration, but not all of them (IE10 on windows phone 8 does not, for example)
width: 100%;
height: auto;
this code probable help you .
<iframe src="" onload="this.width=screen.width;this.height=screen.height;">
You can use the fact that Python concatenates string literals which appear adjacent to each other:
>>> def fun():
... print '{0} Here is a really long ' \
... 'sentence with {1}'.format(3, 5)
That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.
For example:
$ cat t.c
#include <stdio.h>
int main()
{
printf("hello\n");
return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0
0x400534
is the address of main
in my case. 0x400408
is also a valid function address in a.out
, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init
. You can see the layout of your executable with readelf -a your_exe
.)
Other times when addr2line
will fail is if you're including a library that has no debug information.
A base R option is the split()
-lapply()
-do.call()
idiom:
> do.call(rbind, lapply(split(test, test$id), head, 1))
id string
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
A more direct option is to lapply()
the [
function:
> do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
id string
1 1 A
2 2 B
3 3 C
4 4 D
5 5 E
The comma-space 1, )
at the end of the lapply()
call is essential as this is equivalent of calling [1, ]
to select first row and all columns.
Depending on how large and how well-written the original code was, it might be worth starting again in your favourite language (which might still be C++) and learning from any mistakes made in the last version. Didn't someone once say about writing one to throw away?
n.b. Clearly if this is a huge product, then it may not be worth the time.
You should be able to use forward slashes in Java to refer to file locations.
The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.
Toolkit's use of BufferedReader is probably what you need.
You are just supposed to provide the predict
method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace
[0.58,0.76]
With
[[0.58,0.76]]
And it should work.
EDIT: This answer became popular so I thought I'd add a little more explanation about ML. The short version: we can only use predict
on data that is of the same dimensionality as the training data (X
) was.
In the example in question, we give the computer a bunch of rows in X
(with 2 values each) and we show it the correct responses in y
. When we want to predict
using new values, our program expects the same - a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.
August 2018 I didn't find a working example on the iframe implementation. Other questions were related to Chrome only, which gave it away a little.
You'll have to mute sound mute=1
in order to autoplay on Chrome. FF and IE seem to be working just fine using autoplay=1
as parameter.
<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>
for /F "tokens=1" %a in ('dir ^| findstr "File(s)"') do echo %a
Result:
C:\MyDir> for /F "tokens=1" %a in ('dir ^| findstr "File(s)"') do @set FILE_COUNT=%a
C:\MyDir> echo %FILE_COUNT%
4 // <== There's your answer
✗
✗
✘
✘
✕
✕
✖
✖
As the other answers have already pointed out, https "URLs" are indeed encrypted. However, your DNS request/response when resolving the domain name is probably not, and of course, if you were using a browser, your URLs might be recorded too.
To convert the year from string to int, you can add the following option to the csv reader: "inferSchema" -> "true", see DataBricks documentation
I met the problem because of the primary key generation is wrong,when I insert a row like this:
public void addTerminal(String typeOfDevice,Map<Byte,Integer> map) {
// TODO Auto-generated method stub
try {
Set<Byte> keySet = map.keySet();
for (Byte byte1 : keySet) {
Device device=new Device();
device.setNumDevice(DeviceCount.map.get(byte1));
device.setTimestamp(System.currentTimeMillis());
device.setTypeDevice(byte1);
this.getHibernateTemplate().save(device);
}
System.out.println("hah");
}catch (Exception e) {
// TODO: handle exception
logger.warn("wrong");
logger.warn(e.getStackTrace()+e.getMessage());
}
}
I change the id generator class to identity
<id name="id" type="int">
<column name="id" />
<generator class="identity" />
</id>
tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.
If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.
Change
id.equals(list[pos].getItemNumber())
to
id == list[pos].getItemNumber()
For more details, you should learn the difference between the primitive types like int
, char
, and double
and reference types.
String str, str1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str = sc.nextLine();
str1 = str.replaceAll("[aeiouAEIOU]", "");
System.out.print(str1);
I found a nice solution in pure Markdown with a little CSS 3 hack :-)
![image alt >](/image-right.jpg)
![image alt <](/image-left.jpg)
![image alt ><](/center-image.jpg)
Follow the CSS 3 code float image on the left or right, when the image alt
ends with <
or >
.
img[alt$=">"] {
float: right;
}
img[alt$="<"] {
float: left;
}
img[alt$="><"] {
display: block;
max-width: 100%;
height: auto;
margin: auto;
float: none!important;
}
As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.
However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="WARN"/>
</filter>
Or to exclude a specific logging level by adding a "deny" node to the filter.
You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.
Reference Doc: log4net.Filter.LevelMatchFilter
If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.
I had this problem on debian. The issue was, I was using the dotdeb repository for more recent PHP packages. For some reason, it updated the php cli to 7.0, while the web php binary remained php 5.6. I used this answer to link the php command line binary to the 5.6 version, like so:
$ sudo ln -sfn /usr/bin/php5 /etc/alternatives/php
If you imported an existing maven project and Maven dependencies are not showing in the build path in eclipse then right click on project--> Maven--> 'update Project' will resolve the issue.
You could make a little Tkinter app:
import Tkinter as tk
def onKeyPress(event):
text.insert('end', 'You pressed %s\n' % (event.char, ))
root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()
To expand on rhughes answer,
The robocopy works beautifully, just incase you need to include sub directories you can use /e
to include subs and copy empty directories or /s
to include subs excluding empty directories.
Also robocopy will report back a few things like if new files were copied, this will cause VS to complain since anything above 0 is a failure and robocopy will return 1 if new files have been found. Its worth to mention that robocopy first compares the Source/Dest and only copies the updated/new files.
To get around this use:
(robocopy "$(SolutionDir)Solution Items\References\*.dll" "$(TargetDir)") ^& IF %ERRORLEVEL% LEQ 4 exit /B 0
I highly recommend using yarn upgrade-interactive to update React, or any Node project for that matter. It lists your packages, current version, the latest version, an indication of a Minor, Major, or Patch update compared to what you have, plus a link to the respective project.
You run it with yarn upgrade-interactive --latest
, check out release notes if you want, go down the list with your arrow keys, choose which packages you want to upgrade by selecting with the space bar, and hit Enter
to complete.
Npm-upgrade is ok but not as slick.
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}
In my case, and I had bad lag doing the simplest of things, it helped to update my pc drivers. The system drivers are the foundation for everything.
I was fortunate that I have Dell and they have awesome website support to do this. I googled
dell <my model name> update drivers
or go to the drivers home page
I let it update all the drivers it wanted to (Dell driver update is pretty much automatic).
Much of the lag seems to have gone away.
The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)
Here is how I have done:
body {
margin: 0;
padding: 0;
}
div maincontainer {
margin: 0 auto;
width: ___px;
text-align: center;
}
ul {
margin: 0;
padding: 0;
}
ul li {
margin-left: auto;
margin-right: auto;
}
and do not forget to set doctype html5
Modern solution:
let blob = await fetch(url).then(r => r.blob());
The url can be an object url or a normal url.
One simple method is to use place
to use an image as a background image. This is the type of thing that place
is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid
or pack
other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
Structs "really" pure aren't supported in Java. E.g., C# supports struct
definitions that represent values and can be allocated anytime.
In Java, the unique way to get an approximation of C++ structs
struct Token
{
TokenType type;
Stringp stringValue;
double mathValue;
}
// Instantiation
{
Token t = new Token;
}
without using a (static buffer or list) is doing something like
var type = /* TokenType */ ;
var stringValue = /* String */ ;
var mathValue = /* double */ ;
So, simply allocate variables or statically define them into a class.
From jacoco:prepare-agent that says:
One of the ways to do this in case of maven-surefire-plugin - is to use syntax for late property evaluation:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>@{argLine} -your -extra -arguments</argLine> </configuration> </plugin>
Note the @{argLine}
that's added to -your -extra -arguments
.
Thanks Slava Semushin for noticing the change and reporting in the comment.
Following jacoco:prepare-agent that says:
[org.jacoco:jacoco-maven-plugin:0.7.2-SNAPSHOT:prepare-agent] Prepares a property pointing to the JaCoCo runtime agent that can be passed as a VM argument to the application under test. Depending on the project packaging type by default a property with the following name is set:
- tycho.testArgLine for packaging type eclipse-test-plugin and
- argLine otherwise.
Note that these properties must not be overwritten by the test configuration, otherwise the JaCoCo agent cannot be attached. If you need custom parameters please append them. For example:
<argLine>${argLine} -your -extra -arguments</argLine>
Resulting coverage information is collected during execution and by default written to a file when the process terminates.
you should change the following line in maven-surefire-plugin
plugin configuration from (note the ${argLine}
inside <argLine>
):
<argLine>-Xmx2048m</argLine>
to
<argLine>${argLine} -Xmx2048m</argLine>
Make also the necessary changes to the other plugin maven-failsafe-plugin
and replace the following (again, notice the ${argLine}
):
<argLine>-Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
to
<argLine>${argLine} -Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
Update: If you are using CLion 2020.2, then it already supports Makefiles. If you are using an older version, read on.
Even though currently only CMake is supported, you can instruct CMake to call make
with your custom Makefile
. Edit your CMakeLists.txt
adding one of these two commands:
When you tell CLion
to run your program, it will try to find an executable with the same name of the target in the directory pointed by PROJECT_BINARY_DIR
. So as long as your make
generates the file where CLion
expects, there will be no problem.
Here is a working example:
CLion
to pass its $(PROJECT_BINARY_DIR) to make
This is the sample CMakeLists.txt
:
cmake_minimum_required(VERSION 2.8.4)
project(mytest)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_custom_target(mytest COMMAND make -C ${mytest_SOURCE_DIR}
CLION_EXE_DIR=${PROJECT_BINARY_DIR})
CLion's
directoryThis is the sample Makefile
:
all:
echo Compiling $(CLION_EXE_DIR)/$@ ...
g++ mytest.cpp -o $(CLION_EXE_DIR)/mytest
That is all, you may also want to change your program's working directory so it executes as it is when you run make from inside your directory. For this edit: Run -> Edit Configurations ... -> mytest -> Working directory
float b = (float)Math.ceil(a);
or
float b = (float)Math.round(a);
Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).
Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.
Install the GenerateSerialVersionUID plugin by Olivier Descout.
Go to: menu File ? Settings ? Plugins ? Browse repositories ? GenerateSerialVersionUID
Install the plugin and restart.
Now you can generate the id from menu Code ? Generate ? serialVersionUID` or the shortcut.
This is similar to user2533809's answer, but each file will be executed as a separate command.
#!/bin/bash
names="RA
RB
R C
RD"
while read -r line; do
echo line: "$line"
done <<< "$names"
This is an old question, but no one responded to the question regarding centering text in a terminal.
/**
* Centers a string of text in a terminal window
*
* @param string $text The text to center
* @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
*
* @return string The padded result, ready to echo
*/
function center($text, $pad_string = ' ') {
$window_size = (int) `tput cols`;
return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."\n";
}
echo center('foo');
echo center('bar baz', '=');
Whenever I type this command I always seem to hose it up, or forget a flag. I created a Gist on github based off of TaylanUB's answer that does a global find replace from the current directory. This is Mac OSX specific.
https://gist.github.com/nateflink/9056302
It's nice because now I just pop open a terminal then copy in:
curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"
You can get some weird byte sequence errors, so here is the full code:
#!/bin/bash
#By Nate Flink
#Invoke on the terminal like this
#curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"
if [ -z "$1" ] || [ -z "$2" ]; then
echo "Usage: ./$0 [find string] [replace string]"
exit 1
fi
FIND=$1
REPLACE=$2
#needed for byte sequence error in ascii to utf conversion on OSX
export LC_CTYPE=C;
export LANG=C;
#sed -i "" is needed by the osx version of sed (instead of sed -i)
find . -type f -exec sed -i "" "s|${FIND}|${REPLACE}|g" {} +
exit 0
One thing to also look at: Are you saving your .gitignore file with the correct line endings?
Windows:
If you're using it on Windows, are you saving it with Windows line endings? Not all programs will do this by default; Notepad++ and many PHP editors default to Linux line endings so the files will be server compatible. One easy way to check this, is open the file in Windows Notepad. If everything appears on one line, then the file was saved with Linux line endings.
Linux:
If you are having trouble with the file working in a Linux environment, open the file in an editor such as Emacs or nano. If you see any non-printable characters, then the file was saved with Windows line endings.
\d+
\d
represents any digit, +
for one or more. If you want to catch negative numbers as well you can use -?\d+
.
Note that as a string, it should be represented in C# as "\\d+"
, or @"\d+"
Based on this answer by apenwarr and this comment by Miral I came up with the following solution which saved me nearly 94% of disk space when cloning the linux git repository locally while only wanting one Documentation subdirectory:
$ cd linux
$ du -sh .git .
2.1G .git
894M .
$ du -sh
2.9G .
$ mkdir ../linux-sparse-test
$ cd ../linux-sparse-test
$ git init
Initialized empty Git repository in /…/linux-sparse-test/.git/
$ git config core.sparseCheckout true
$ git remote add origin ../linux
# Parameter "origin master" saves a tiny bit if there are other branches
$ git fetch --depth=1 origin master
remote: Enumerating objects: 65839, done.
remote: Counting objects: 100% (65839/65839), done.
remote: Compressing objects: 100% (61140/61140), done.
remote: Total 65839 (delta 6202), reused 22590 (delta 3703)
Receiving objects: 100% (65839/65839), 173.09 MiB | 10.05 MiB/s, done.
Resolving deltas: 100% (6202/6202), done.
From ../linux
* branch master -> FETCH_HEAD
* [new branch] master -> origin/master
$ echo "Documentation/hid/*" > .git/info/sparse-checkout
$ git checkout master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Already on 'master'
$ ls -l
total 4
drwxr-xr-x 3 abe abe 4096 May 3 14:12 Documentation/
$ du -sh .git .
181M .git
100K .
$ du -sh
182M .
So I got down from 2.9GB to 182MB which is already quiet nice.
I though didn't get this to work with git clone --depth 1 --no-checkout --filter=blob:none file:///…/linux linux-sparse-test
(hinted here) as then the missing files were all added as removed files to the index. So if anyone knows the equivalent of git clone --filter=blob:none
for git fetch
, we can probably save some more megabytes. (Reading the man page of git-rev-list
also hints that there is something like --filter=sparse:path=…
, but I didn't get that to work either.
(All tried with git 2.20.1 from Debian Buster.)
The simulator directory has been moved with Xcode 6 beta to...
~/Library/Developer/CoreSimulator
Browsing the directory to your app's Documents folder is a bit more arduous, e.g.,
~/Library/Developer/CoreSimulator/Devices/4D2D127A-7103-41B2-872B-2DB891B978A2/data/Containers/Data/Application/0323215C-2B91-47F7-BE81-EB24B4DA7339/Documents/MyApp.sqlite
Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.
You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.
The best option is using a server side script like the one posted by jellyfishtree.
A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.
int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;
// The * causes pA to DEREFERENCE... `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4..
If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.
I solved it this way:
Call the following just before calling your ssl webservice that cause that error:
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// solution for exception
/// System.Net.WebException:
/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
/// </summary>
public static void BypassCertificateError()
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(
Object sender1,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.
I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.
So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.
Delete all the shutdown simulators:
xcrun simctl list | grep -w "Shutdown" | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete uuid
If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.
Your condition is right (though you should drop the == true
). What is happening is that the scanner will keep going until it reaches the end of the input. Try Ctrl+D, or pipe the input from a file (java myclass < input.txt
).
From a background script you can listen to the chrome.tabs.onUpdated
event and check the property changeInfo.status
on the callback. It can be loading or complete. If it is complete, do the action.
Example:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete') {
// do your things
}
})
Because this will probably trigger on every tab completion, you can also check if the tab is active
on its homonymous attribute, like this:
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
if (changeInfo.status == 'complete' && tab.active) {
// do your things
}
})
SQL Server, nicely formatted table for all tables in KB/MB:
SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
t.Name
I never use NULL in my C or C++ code. 0
works just fine, as does if (ptrname)
. Any competent C or C++ programmer should know what those do.
To illustrate Nippysaurus's answer: If you are going to add the new items to the list and want to process the newly added items too during the same enumeration then you can just use for loop instead of foreach loop, problem solved :)
var list = new List<YourData>();
... populate the list ...
//foreach (var entryToProcess in list)
for (int i = 0; i < list.Count; i++)
{
var entryToProcess = list[i];
var resultOfProcessing = DoStuffToEntry(entryToProcess);
if (... condition ...)
list.Add(new YourData(...));
}
For runnable example:
void Main()
{
var list = new List<int>();
for (int i = 0; i < 10; i++)
list.Add(i);
//foreach (var entry in list)
for (int i = 0; i < list.Count; i++)
{
var entry = list[i];
if (entry % 2 == 0)
list.Add(entry + 1);
Console.Write(entry + ", ");
}
Console.Write(list);
}
Output of last example:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 5, 7, 9,
List (15 items)
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9
There are 3 main issues with multithreading:
1) Race Conditions
2) Caching / stale memory
3) Complier and CPU optimisations
volatile
can solve 2 & 3, but can't solve 1. synchronized
/explicit locks can solve 1, 2 & 3.
1) Consider this thread unsafe code:
x++;
While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x
originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.
Using synchronized
on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x
was 1, and 2 threads try to preform x++
we know in the end it will be equal to 3. So it solves the race condition problem.
synchronized (this) {
x++; // no problem now
}
Marking x
as volatile
does not make x++;
atomic, so it doesn't solve this problem.
2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.
Consider that on one thread, x = 10;
. And somewhat later, in another thread, x = 20;
. The change in value of x
might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20)
the answer will be false
.
Marking a variable as volatile
basically tells all threads to do read and write operations on main memory only. synchronized
tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.
Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.
3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.
Consider the following code:
boolean b = false;
int x = 10;
void threadA() {
x = 20;
b = true;
}
void threadB() {
if (b) {
System.out.println(x);
}
}
You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b
to true), as b
is set to true only after x
is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b
as volatile
ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile
only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.
Note that before Java 5 New Memory Model, volatile didn’t solve this issue.
First of all print
isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing ,
(comma). Now a space will be used instead of a newline.
Demo:
print 1,
print 2
output:
1 2
Or use Python 3's print()
function:
from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)
As you can clearly see print()
function is much more powerful as we can specify any string to be used as end
rather a fixed space.
I find it easier to push or append arrays and then flatten them in place, like so:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push anotherarray # => ["some", "thing", ["another", "thing"]]
#or
somearray << anotherarray # => ["some", "thing", ["another", "thing"]]
somearray.flatten! # => ["some", "thing", "another", "thing"]
somearray # => ["some", "thing", "another", "thing"]
The question is contradictory. It asks for a date without a time of day yet displays an example with a time of 00:00:00
.
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See my other Answer for java.time solution.
If instead you want the time-of-day set to the first moment of the day, use a DateTime
object on the Joda-Time library and call its withTimeAtStartOfDay
method. Be aware that the first moment may not be the time 00:00:00
because of Daylight Saving Time or perhaps other anomalies.
This simply means that the implementation project is out of date in my cases. The DLL containing the interface was rebuilt but the implementation dll was stale.
astype(str)
!Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:
# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')
From pandas 1.0 onwards, consider using "string"
type instead.
# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype
Here's why, as quoted by the docs:
You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.
object
dtype breaks dtype-specific operations likeDataFrame.select_dtypes()
. There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.When reading code, the contents of an
object
dtype array is less clear than'string'
.
See also the section on Behavioral Differences between "string"
and object
.
Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float
). But pandas can using Nullable Integer columns.
Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.
# pandas <= 0.25
pd.Series(['a', 'b', 1.23]) # whoops, this should have been "1.23"
0 a
1 b
2 1.23
dtype: object
pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23] # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")
0 a
1 b
2 1.23
dtype: string
pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23'] # it's a string and we just averted some potentially nasty bugs.
Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.
Consider,
# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
A B
0 a {}
1 b [1, 2, 3]
2 c 123
Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.
# pandas <= 0.25
df.dtypes
A object
B object
dtype: object
df.select_dtypes(object)
A B
0 a {}
1 b [1, 2, 3]
2 c 123
From pandas 1.0, this becomes a lot simpler:
# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes
A string
B object
dtype: object
df.select_dtypes("string")
A
0 a
1 b
2 c
Readability
This is self-explanatory ;-)
...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string"
columns as opposed to objects. With that said, however, it's never too early to form good habits!
I have found that at times even verifying the settings under Options --> Statement Completion (the answer above) doesn't work. In this case, saving and restarting Visual Studio will re-enable Intellisense.
Finally, this link has a list of other ways to troubleshoot Intellisense, broken down by language (for more specific errors).
http://msdn.microsoft.com/en-us/library/vstudio/ecfczya1(v=vs.100).aspx
Here is a different approach using mix-blend-mode: difference
, that will actually invert whatever the background is, not just a single colour:
div {_x000D_
background-image: linear-gradient(to right, red, yellow, green, cyan, blue, violet);_x000D_
}_x000D_
p {_x000D_
color: white;_x000D_
mix-blend-mode: difference;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscit elit, sed do</p>_x000D_
</div>
_x000D_
You can specify addresses as "R1C2" instead of "B2". Under File -> Options -> Formuals -> Workingg with Formulas there is a toggle R1C1 reference style. which can be set, as illustrated below.
I think style no. 111 (Japan) should work:
SELECT CONVERT(DATETIME, '2012-08-17', 111)
And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD
) which works for any language and date format setting in SQL Server:
SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)
I've had this issue a few times and to resolve I did the following:
I found this issue was caused everything we plugged the laptop into a projector and saved the file. Then everytime the issue came up I went just repeated steps 1. and 2. and my ActiveX objects were behaving again
As far as I know List<T>
implements IEnumerable<T>
. It means that you do not have to convert or cast anything.
I was getting this same error, but for me this was due to a method in a base class (in Project A) having the output type changed from a non-void type to void. A child class existed in Project B (which I didn't want used and had marked obsolete) that I missed when performing this update and hence started throwing this error.
1>CSC : error CS8104: An error occurred while writing the output file: System.NullReferenceException: Object reference not set to an instance of an object.
Original Code:
[Obsolete("Calling this method will throw an error")]
public override CompletionStatus Run()
{
throw new CustomException("Run process not supported.");
}
Revised Code:
[Obsolete("Calling this method will throw an error")]
public override void Run()
{
throw new CustomException("Run process not supported.");
}
if re.search(r'pattern', string):
Simple if-test:
if re.search(r'ing\b', "seeking a great perhaps"): # any words end with ing?
print("yes")
Pattern check, extract a substring, case insensitive:
match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
assert "to" == match_object.group(1) # what's between ought and be?
Notes:
Use re.search()
not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A
instead, re.search(r'^...', ...)
Use raw string syntax r'pattern'
for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)
In this example, \b
is a special sequence meaning word-boundary in regex. Not to be confused with backspace.
re.search()
returns None
if it doesn't find anything, which is always falsy.
re.search()
returns a Match object if it finds anything, which is always truthy.
a group is what matched inside parentheses
group numbering starts at 1
try this one :
$('html').keyup(function(e){if(e.keyCode == 8)alert('backspace trapped')})
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.
if [ -h $file ]
then
base=$(dirname $(readlink $file))
else
base=$(dirname $file)
fi
You can't get value when calling getJSON
, only after response.
var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
myjson = json;
});
I know it's not an exact answer to the OP, but as answers have already be given...
Do you really need to do this in PHP ?
What I mean is : if you need to convert a lot of images, doing it in PHP might not be the best way : you'll be confronted to memory_limit
, max_execution_time
, ...
I would also say GD might not get you the best quality/size ratio ; but not sure about that (if you do a comparison between GD and other solutions, I am very interested by the results ;-) )
Another approach, not using PHP, would be to use Image Magick via the command line (and not as a PHP extension like other people suggested)
You'd have to write a shell-script that goes through all .png
files, and gives them to either
convert
to create a new .jpg
file for each .png
filemogrify
to directly work on the original file and override it.
As a sidenote : if you are doing this directly on your production server, you could put some sleep time between bunches of conversions, to let it cool down a bit sometimes ^^
I've use the shell script + convert
/mogrify
a few times (having them run for something like 10 hours one time), and they do the job really well :-)
@boernard 's answer solves this from the Android Studio IDE, but if you want to understand what's happening under the covers, it's a simple gradle build file update:
You can edit the build.gradle file from within the IDE (left pane: Gradle Scripts -> build.gradle (Module: app)
) or use the raw path (<proj_dir>/app/build.gradle
)
and add/update the following dependency section:
dependencies {
//
// IDE setting pulls in the specific version of v4 support you have installed:
//
//compile 'com.android.support:support-v4:21.0.3'
//
// generic directive pulls in any available version of v4 support:
//
compile 'com.android.support:support-v4:+'
}
Using the above generic compile directive, allows you to ship your code to anyone, provided they have some level of the Android Support Libraries v4
installed.
read -n1
is not portable. A portable way to do the same might be:
( trap "stty $(stty -g;stty -icanon)" EXIT
LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
) </dev/tty
Besides using read
, for just a press ENTER
to continue prompt you could do:
sed -n q </dev/tty
Java 1.8 (as well as Groovy and Scala) has a thing called "Interface Defender Methods", which are interfaces with pre-defined default method bodies. By implementing multiple interfaces that use defender methods, you could effectively, in a way, extend the behavior of two interface objects.
Also, in Groovy, using the @Delegate annotation, you can extend behavior of two or more classes (with caveats when those classes contain methods of the same name). This code proves it:
class Photo {
int width
int height
}
class Selection {
@Delegate Photo photo
String title
String caption
}
def photo = new Photo(width: 640, height: 480)
def selection = new Selection(title: "Groovy", caption: "Groovy", photo: photo)
assert selection.title == "Groovy"
assert selection.caption == "Groovy"
assert selection.width == 640
assert selection.height == 480
When TypeScript thinks that property "x" does not exist on "y", then you can always cast "y" into "any", which will allow you to call anything (like "x") on "y".
Theory
(<any>y).x;
Real World Example
I was getting the error "TS2339: Property 'name' does not exist on type 'Function'" for this code:
let name: string = this.constructor.name;
So I fixed it with:
let name: string = (<any>this).constructor.name;
You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.
This is the simplest method. Only one step.
It has significant impact on speed. In my case, time taken for a training step almost halved.
I built on sabithpocker's idea and made a more generalized version that lets you control more than one selectbox from a given trigger.
I assigned the selectboxes I wanted to be controlled the classname "switchable," and cloned them all like this:
$j(this).data('options',$j('select.switchable option').clone());
and used a specific naming convention for the switchable selects, which could also translate into classes. In my case, "category" and "issuer" were the select names, and "category_2" and "issuer_1" the class names.
Then I ran an $.each on the select.switchable groups, after making a copy of $(this) for use inside the function:
var that = this;
$j("select.switchable").each(function() {
var thisname = $j(this).attr('name');
var theseoptions = $j(that).data('options').filter( '.' + thisname + '_' + id );
$j(this).html(theseoptions);
});
By using a classname on the ones you want to control, the function will safely ignore other selects elsewhere on the page (such as the last one in the example on Fiddle).
Here's a Fiddle with the complete code:
To retrieve data from form which send post request you can do it like this
def login_view(request):
if(request.POST):
login_data = request.POST.dict()
username = login_data.get("username")
password = login_data.get("password")
user_type = login_data.get("user_type")
print(user_type, username, password)
return HttpResponse("This is a post request")
else:
return render(request, "base.html")
I can see some people have asked, so on OSX you can still go to navigate->test or use cmd+shift+T
Remember you have to be focused in the class for this to work
The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:
public void someMethod() {
try {
...
if (condition)
return;
...
} catch (SomeException e) {
...
}
}
If the code involves lots of local variables, you may also consider using a break
from a labeled block, as suggested by Stephen C:
label: try {
...
if (condition)
break label;
...
} catch (SomeException e) {
...
}
ALTER TABLE test1 ADD COLUMN id SERIAL PRIMARY KEY;
This is all you need to:
id
columnCredit is given to @resnyanskiy who gave this answer in a comment.
I create the database myself using the command line. Then try to import again, it works.
kubectl exec -it POD_NAME -c CONTAINER_NAME bash - then kill 1
Assuming the container is run as root which is not recommended.
In my case when I changed the application config, I had to reboot the container which was used in a sidecar pattern, I would kill the PID for the spring boot application which is owned by the docker user.
with Showcase/Benchmark App and Source on Github. Also check out the Blur framework I'm currently working on: Dali.
After experimenting a lot I can now safely give you some solid recommendations that will make your life easier in Android when using the Android Framework.
Never use a the full size of a Bitmap. The bigger the image the more needs to be blurred and also the higher the blur radius needs to be and usually, the higher the blur radius the longer the algorithm takes.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap blurTemplate = BitmapFactory.decodeResource(getResources(), R.drawable.myImage, options);
This will load the bitmap with inSampleSize
8, so only 1/64 of the original image. Test what inSampleSize
suits your needs, but keep it 2^n (2,4,8,...) to avoid degrading quality due to scaling. See Google doc for more
Another really big advantage is that bitmap loading will be really fast. In my early blur testing I figured that the longest time during the whole blur process was the image loading. So to load a 1920x1080 image from disk my Nexus 5 needed 500ms while the blurring only took another 250 ms or so.
Renderscript provides ScriptIntrinsicBlur
which is a Gaussian blur filter. It has good visual quality and is just the fastest you realistically get on Android. Google claims to be "typically 2-3x faster than a multithreaded C implementation and often 10x+ faster than a Java implementation". Renderscript is really sophisticated (using the fastest processing device (GPU, ISP, etc.), etc.) and there is also the v8 support library for it making it compatible down to 2.2. Well at least in theory, through my own tests and reports from other devs it seems that it is not possible to use Renderscript blindly, since the hardware/driver fragmentation seems to cause problems with some devices, even with higher sdk lvl (e.g. I had troubles with the 4.1 Nexus S) so be careful and test on a lot of devices. Here's a simple example that will get you started:
//define this only once if blurring multiple times
RenderScript rs = RenderScript.create(context);
(...)
//this will blur the bitmapOriginal with a radius of 8 and save it in bitmapOriginal
final Allocation input = Allocation.createFromBitmap(rs, bitmapOriginal); //use this constructor for best performance, because it uses USAGE_SHARED mode which reuses memory
final Allocation output = Allocation.createTyped(rs, input.getType());
final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
script.setRadius(8f);
script.setInput(input);
script.forEach(output);
output.copyTo(bitmapOriginal);
When using the v8 support with Gradle, which is specifically recommended by Google "because they include the latest improvements", you only need to add 2 lines to your build script and use android.support.v8.renderscript
with current build tools (updated syntax for android Gradle plugin v14+)
android {
...
defaultConfig {
...
renderscriptTargetApi 19
renderscriptSupportModeEnabled true
}
}
Simple benchmark on a Nexus 5 - comparing RenderScript with different other java and Renderscript implementations:
The average runtime per blur on different pic sizes
Megapixels per sec that can be blurred
Each value is the avg of 250 rounds. RS_GAUSS_FAST
is ScriptIntrinsicBlur
(and nearly always the fastest), others that start with RS_
are mostly convolve implementations with simple kernels. The details of the algorithms can be found here. This is not purely blurring, since a good portion is garbage collection that is measured. This can be seen in this here (ScriptIntrinsicBlur
on a 100x100 image with about 500 rounds)
The spikes are gc.
You can check for yourself, the benchmark app is in the playstore: BlurBenchmark
If you need multiple blurs for a live blur or similar and your memory allows it do not load the bitmap from drawables multiple times, but keep it "cached" in a member variable. In this case always try to use the same variables, to keep garbage collecting to a minimum.
Also check out the new inBitmap
option when loading from a file or drawable which will reuse the bitmap memory and save garbage collection time.
The simple and naive method is just to use 2 ImageViews
, one blurred, and alpha fade them. But if you want a more sophisticated look that smoothly fades from sharp to blurry, then check out Roman Nurik's post about how to do it like in his Muzei app.
Basically he explains that he pre-blurs some frames with different blur extents and uses them as keyframes in an animation that looks really smooth.
You can effectively "empty" the Recycle Bin from the command line by permanently deleting the Recycle Bin directory on the drive that contains the system files. (In most cases, this will be the C:
drive, but you shouldn't hardcode that value because it won't always be true. Instead, use the %systemdrive%
environment variable.)
The reason that this tactic works is because each drive has a hidden, protected folder with the name $Recycle.bin
, which is where the Recycle Bin actually stores the deleted files and folders. When this directory is deleted, Windows automatically creates a new directory.
So, to remove the directory, use the rd
command (r?emove d?irectory) with the /s
parameter, which indicates that all of the files and directories within the specified directory should be removed as well:
rd /s %systemdrive%\$Recycle.bin
Do note that this action will permanently delete all files and folders currently in the Recycle Bin from all user accounts. Additionally, you will (obviously) have to run the command from an elevated command prompt in order to have sufficient privileges to perform this action.
You can also use function:
//Works with negative numbers now
static int MyRound(double d) {
if (d < 0) {
return (int)(d - 0.5);
}
return (int)(d + 0.5);
}
Depending on the architecture it is several times faster.
if (capital.touched && capital != undefined && capital.length < 1 ) {
//capital does exists
}
If you want a NULL
return value you need to use pointers instead of references.
References can't themselves be NULL
.
(Note to the future comment posters: Yes you can have the address of a reference be NULL if you really really try to).
See my answer here for a list of differences between references and pointers.
As @Lighthart as shown, yes it's possible, although it adds significant fat to the controller and isn't DRY.
You should really define your own query in the entity repository, it's simple and best practice.
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('username' => 'ASC'));
}
}
Then you must tell your entity to look for queries in the repository:
/**
* @ORM\Table(name="User")
* @ORM\Entity(repositoryClass="Acme\UserBundle\Entity\Repository\UserRepository")
*/
class User
{
...
}
Finally, in your controller:
$this->getDoctrine()->getRepository('AcmeBundle:User')->findAll();
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// run the code making use of getActivity() from here
}
Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.
I can't claim credit for this image, but it matches everything I know on this subject and offers a bit of humor at the same time.
It's definitely an issue with some of the projects being built for x86 compatibility instead of any CPU. If I had to guess I would say that some of the references between your projects are probably referencing the dll's in some of the bin\debug folders instead of being project references.
When a project is compiled for x86 instead of 'Any CPU' the dll's go into the bin\x86\debug folder instead of bin\debug (which is probably where your references are looking).
But in any case, you should be using project references between your projects.
Adding this configuration in application.properties file to fixed this issue easily.
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
As csgillespie said. stringsAsFactors is default on TRUE, which converts any text to a factor. So even after deleting the text, you still have a factor in your dataframe.
Now regarding the conversion, there's a more optimal way to do so. So I put it here as a reference :
> x <- factor(sample(4:8,10,replace=T))
> x
[1] 6 4 8 6 7 6 8 5 8 4
Levels: 4 5 6 7 8
> as.numeric(levels(x))[x]
[1] 6 4 8 6 7 6 8 5 8 4
To show it works.
The timings :
> x <- factor(sample(4:8,500000,replace=T))
> system.time(as.numeric(as.character(x)))
user system elapsed
0.11 0.00 0.11
> system.time(as.numeric(levels(x))[x])
user system elapsed
0 0 0
It's a big improvement, but not always a bottleneck. It gets important however if you have a big dataframe and a lot of columns to convert.
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
Absolutely. Try this:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
Don't forget also to create the constant PICK_IMAGE, so you can recognize when the user comes back from the image gallery Activity:
public static final int PICK_IMAGE = 1;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE) {
//TODO: action
}
}
That's how I call the image gallery. Put it in and see if it works for you.
EDIT:
This brings up the Documents app. To allow the user to also use any gallery apps they might have installed:
Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);
This can simply also mean you are missing or have too many parentheses. For example this has too many, and will result in unexpected EOF
:
print(9, not (a==7 and b==6)
Add this line to your change
event handler
$("#theSelect option:selected").attr('disabled','disabled')
.siblings().removeAttr('disabled');
This will disable the selected option, and enable any previously disabled options.
EDIT:
If you did not want to re-enable the previous ones, just remove this part of the line:
.siblings().removeAttr('disabled');
EDIT:
To re-enable when you click remove, add this to your click handler.
$("#theSelect option[value=" + value + "]").removeAttr('disabled');
You need to create both a URL
object and a URLConnection
object. The following code will test both the format of the URL and whether a connection can be established:
try {
URL url = new URL("http://www.yoursite.com/");
URLConnection conn = url.openConnection();
conn.connect();
} catch (MalformedURLException e) {
// the URL is not in a valid form
} catch (IOException e) {
// the connection couldn't be established
}
You can use std::set
instead of std::map
.
You can store both key and value in std::pair
and the type of container will look like this:
std::set< std::pair<int, std::string> > items;
std::set
will sort it's values both by original keys and values that were stored in std::map
.
Just use the cached
flag if you added, but haven't committed yet:
git diff --cached --color
this could be a solution?
declare @step2cmd nvarchar(200)
DECLARE @rcount NUMERIC(18,0)
set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
EXECUTE @rcount=sp_executesql @step2cmd
select @rcount
Here's a more elegant solution based on what came below. it accounts for event bubbling up from more than one level of children. It also accounts for cross-browser issues.
function onMouseOut(this, event) {
//this is the original element the event handler was assigned to
var e = event.toElement || event.relatedTarget;
//check for all children levels (checking from bottom up)
while(e && e.parentNode && e.parentNode != window) {
if (e.parentNode == this|| e == this) {
if(e.preventDefault) e.preventDefault();
return false;
}
e = e.parentNode;
}
//Do something u need here
}
document.getElementById('parent').addEventListener('mouseout',onMouseOut,true);
Hi please check the below link
https://www.postgresql.org/docs/current/xfunc-sql.html
EX:
CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;
if (!$("input[name='html_elements']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
This may happen due to the following reasons -
So by removing the implementation or adding them can remove this error. You can remove the "uses" code in the android manifest file.
Examples:
this wasted my 1 hour, cause I mistakenly added a class of wearable type, of course, I safe deleted that using refractor but it Didi not made changes to manifest file.
I used the firebase crashlytics code in my java project but I mistakenly deleted that in buld.gradle. Here below: implementation 'com.google.firebase:firebase-crashlytics:17.1.1'
The solution is in either BUILD>GRADLE or in AndroidManifest.xml, mostly.
Double click on the home button and then click and hold the icon like a normal phone and then click close I believe.
I created this a few months ago for a project.
".+?"|[^"]+?(?=,)|(?<=,)[^"]+
It works in C# and the Debuggex was happy when I selected Python and PCRE. Javascript doesn't recognize this form of Proceeded By ?<=....
For your values, it will create matches on
123
,2.99
,AMO024
,Title
"Description, more info"
,
,123987564
Note that anything in quotes doesn't have a leading comma, but attempting to match with a leading comma was required for the empty value use case. Once done, trim values as necessary.
I use RegexHero.Net to test my Regex.
Inspired by the comment of @MitMaro, I wrote a small benchmark to test the speed of solutions of @Gumbo, @Matt Bridges and @justin the proposal in the question:
function teststrtok($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = strtok($str,'?');
}
}
function testexplode($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$str = explode('?', $str);
}
}
function testregexp($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
preg_replace('/\\?.*/', '', $str);
}
}
function teststrpos($number_of_tests){
for($i = 0; $i < $number_of_tests; $i++){
$str = "http://www.example.com?test=test";
$qPos = strpos($str, "?");
$url_without_query_string = substr($str, 0, $qPos);
}
}
$number_of_runs = 10;
for($runs = 0; $runs < $number_of_runs; $runs++){
$number_of_tests = 40000;
$functions = array("strtok", "explode", "regexp", "strpos");
foreach($functions as $func){
$starttime = microtime(true);
call_user_func("test".$func, $number_of_tests);
echo $func.": ". sprintf("%0.2f",microtime(true) - $starttime).";";
}
echo "<br />";
}
strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18; strtok: 0.12;explode: 0.19;regexp: 0.31;strpos: 0.18;
Result: @justin's strtok is the fastest.
Note: tested on a local Debian Lenny system with Apache2 and PHP5.
-- First Truncate temporary table SQL> TRUNCATE TABLE test_temp1; -- Then Drop temporary table SQL> DROP TABLE test_temp1;
If you use "suffixIcon" to collapse the height of the TextField add: suffixIconConstraints
TextField(
style: TextStyle(fontSize: r * 1.8, color: Colors.black87),
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.symmetric(vertical: r * 1.6, horizontal: r * 1.6),
suffixIcon: Icon(Icons.search, color: Colors.black54),
suffixIconConstraints: BoxConstraints(minWidth: 32, minHeight: 32),
),
)
Try to add ReactiveFormsModule in your component as well.
import { FormGroup, FormArray, FormBuilder,
Validators,ReactiveFormsModule } from '@angular/forms';
this should solve your problem.
\cp -rf foo/* bar/
Are you looking for a 2 column CSS layout?
If so, have a look at the instructions, it's pretty straightforward for starting.
If this is what you mean, you can simply extend the class you would like to typedef, e.g.:
public class MyMap extends HashMap<String, String> {}
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... args) {
...
}
@Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
@Override
protected boolean doInBackground(String... args) {
...
}
@Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.
http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/
You can try this cool app available in play store called Html Page Source https://play.google.com/store/apps/details?id=com.scintillar.hps
Search up "Edit the system environment variables" on windows search
Click environmental variable on the bottom right corner
Find path under system variables and click edit on it
Click new to add a new path
add this path: C:\Users\yourUserName\AppData\Local\GitHubDesktop\bin\github.exe
To make sure everything is working fine, open cmd, and type github.exe
Please use the following command,
cat /etc/bash.bashrc > ~/.bashrc
This will generate a new bashrc file with the default values. Please use vi ~/.bashrc
to edit this file.
When inserting a row, regardless of the CopyOrigin, Excel will only put vertical borders on the inserted cells if the borders above and below the insert position are the same.
I'm running into a similar (but rotated) situation with inserting columns, but Copy/Paste is too slow for my workbook (tens of thousands of rows, many columns, and complex formatting).
I've found three workarounds that don't require copying the formatting from the source row:
Ensure the vertical borders are the same weight, color, and pattern above and below the insert position so Excel will replicate them in your new row. (This is the "It hurts when I do this," "Stop doing that!" answer.)
Use conditional formatting to establish the border (with a Formula of "=TRUE"). The conditional formatting will be copied to the new row, so you still end up with a border.Caveats:
Set the border on the inserted row in VBA after inserting the row. Setting a border on a range is much faster than copying and pasting all of the formatting just to get a border (assuming you know ahead of time what the border should be or can sample it from the row above without losing performance).
In my case, it seems ng is not registered into my environment path. I have been using npm run command to run the ng commands. Be aware in order to pass arguments you need an extra --
as per the npm run specification.
Example:
npm run ng g c components/scheduling **--** --module=app
Or:
npm run ng g c components/scheduling **--** --skip-import
If you want to go with the add-open option, here's a command to find which module provides which package ->
java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d
the name of the module will be shown with the @ while the name of the packages without it
NOTE: tested with JDK 11
IMPORTANT: obviously is better than the provider of the package does not do the illegal access
If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.
Starting with your example array:
import numpy as np
x = np.array([[1000, 10, 0.5],
[ 765, 5, 0.35],
[ 800, 7, 0.09]])
x_normed = x / x.max(axis=0)
print(x_normed)
# [[ 1. 1. 1. ]
# [ 0.765 0.5 0.7 ]
# [ 0.8 0.7 0.18 ]]
x.max(0)
takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,)
containing the maximum value in each column. You can then divide x
by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.
If x
contains negative values you would need to subtract the minimum first:
x_normed = (x - x.min(0)) / x.ptp(0)
Here, x.ptp(0)
returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.
I know this question is too old, but still, I think this approach would be cleaner:
cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);
In this case you wont need to go over the entire options with each()
.
Although by that time prop()
didn't exist so for older versions of jQuery use attr()
.
UPDATE
You have to be certain when using contains
because you can find multiple options, in case of the string inside cat
matches a substring of a different option than the one you intend to match.
Then you should use:
cat = $.URLDecode(cat);
$('#cbCategory option')
.filter(function(index) { return $(this).text() === cat; })
.prop('selected', true);
The first thing i would suggest is to use the correct configuration for predefined descriptors.
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
[...]
</project>
To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass>
parameter.
Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.
I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..
You can use var_dump() function to display structured information about variables/expressions including its type and value, or you can use print_r() to display information about a variable in a way that's readable by humans.
Example: Say we have got the following array and we want to display its contents.
$arr = array ('xyz', false, true, 99, array('50'));
Array
(
[0] => xyz
[1] =>
[2] => 1
[3] => 99
[4] => Array
(
[0] => 50
)
)
array(5) {
[0]=>
string(3) "xyz"
[1]=>
bool(false)
[2]=>
bool(true)
[3]=>
int(100)
[4]=>
array(1) {
[0]=>
string(2) "50"
}
}
The functions used in this answer can be found on the PHP.net website var_dump(), print_r()
For more details:
» https://stackhowto.com/how-to-display-php-variable-values-with-echo-print_r-and-var_dump/
In laravel 5.3
I want to show the get param in my view
Step 1 : my route
Route::get('my_route/{myvalue}', 'myController@myfunction');
Step 2 : Write a function inside your controller
public function myfunction($myvalue)
{
return view('get')->with('myvalue', $myvalue);
}
Now you're returning the parameter that you passed to the view
Step 3 : Showing it in my View
Inside my view you i can simply echo it by using
{{ $myvalue }}
So If you have this in your url
http://127.0.0.1/yourproject/refral/[email protected]
Then it will print [email protected] in you view file
hope this helps someone.
For anyone encountering a similar situation I was able to solve the issue above as follows:
Regenerate your pkcs12 file as follows:
openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts
, password: changeit
).
Set the following system properties:
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
Test ur url.
Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333
foreach (var v in structure)
{
var group = groups.Single(g => g.Key == v. ??? );
v.ListOfSmth = group.ToList();
}
First you need to select the desired group. Then you can use the ToList
method of on the group. The IGrouping
is a IEnumerable
of the values.
In case you have already installed the TortoiseSVN GUI and wondering how to upgrade to command line tools, here are the steps...
Refer to this image for further steps.
After completion of the command line client tools, open a command prompt and type svn help
to check the successful install.
extension Date {
func daysFromToday() -> Int {
return Calendar.current.dateComponents([.day], from: self, to: Date()).day!
}
}
Then use it like
func dayCount(dateString: String) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd,yyyy hh:mm a"
let fetchedDate = dateFormatter.date(from: dateString)
let day = fetchedDate?.daysFromToday()
if day! > -1{
return "\(day!) days passed."
}else{
return "\(day! * -1) days left."
}
}
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
I've had very good experience with copy-maven-plugin. It has a much more convenient and concise syntax in comparison to maven-resources-plugin.
//STEP01 EXEC SORT90MB
//SORTJNF1 DD DSN=INPUTFILE1,
// DISP=SHR
//SORTJNF2 DD DSN=INPUTFILE2,
// DISP=SHR
//SORTOUT DD DSN=MISMATCH_OUTPUT_FILE,
// DISP=(,CATLG,DELETE),
// UNIT=TAPE,
// DCB=(RECFM=FB,BLKSIZE=0),
// DSORG=PS
//SYSOUT DD SYSOUT=*
//SYSIN DD *
JOINKEYS FILE=F1,FIELDS=(1,79,A)
JOINKEYS FILE=F2,FIELDS=(1,79,A)
JOIN UNPAIRED,F1,ONLY
SORT FIELDS=COPY
/*
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";
// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
yield mb_substr($str, $i, 1);
}
})($str);
var_dump(
true === $gen instanceof Traversable,
// PHP 7.1
true === is_iterable($gen)
);
foreach ($gen as $char) {
echo $char, PHP_EOL;
}
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
redirected uri is the location where the user will be redirected after successfully login to your app. for example to get access token for your app in facebook you need to subimt redirected uri which is nothing only the app Domain that your provide when you create your facebook app.
ports:
expose:
When you open a file with the name address.csv
, you are telling the open()
function that your file is in the current working directory. This is called a relative path.
To give you an idea of what that means, add this to your code:
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
That will print the current working directory along with all the files in it.
Another way to tell the open()
function where your file is located is by using an absolute path, e.g.:
f = open("/Users/foo/address.csv")
if you are using ps, you can check the manual
man ps
there is a list of keywords allowing you to build what you need. for example to show, userid / processid / percent cpu / percent memory / work queue / command :
ps -e -o "uid pid pcpu pmem wq comm"
-e is similar to -A (all inclusive; your processes and others), and -o is to force a format.
if you are looking for a specific uid, you can chain it using awk or grep such as :
ps -e -o "uid pid pcpu pmem wq comm" | grep 501
this should (almost) show only for userid 501. try it.