There is a more simpler way using the mongoose exists function
router.post("/groups/members", async (ctx) => {
const group_name = ctx.request.body.group_membership.group_name;
const member_name = ctx.request.body.group_membership.group_members;
const GroupMembership = GroupModels.GroupsMembers;
console.log("group_name : ", group_name, "member : ", member_name);
try {
if (
(await GroupMembership.exists({
"group_membership.group_name": group_name,
})) === false
) {
console.log("new function");
const newGroupMembership = await GroupMembership.insertMany({
group_membership: [
{ group_name: group_name, group_members: [member_name] },
],
});
await newGroupMembership.save();
} else {
const UpdateGroupMembership = await GroupMembership.updateOne(
{ "group_membership.group_name": group_name },
{ $push: { "group_membership.$.group_members": member_name } },
);
console.log("update function");
await UpdateGroupMembership.save();
}
ctx.response.status = 201;
ctx.response.message = "A member added to group successfully";
} catch (error) {
ctx.body = {
message: "Some validations failed for Group Member Creation",
error: error.message,
};
console.log(error);
ctx.throw(400, error);
}
});
To have a more in-depth knowledge of what's happening, I created the following example. Have a look at the activity_main.xml and content_profile.xml files.
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="@layout/content_profile" />
</LinearLayout>
content_profile.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</LinearLayout>
In here, the entire layout file when inflated looks like this.
<LinearLayout>
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
</LinearLayout>
See that there is a LinearLayout inside the parent LinearLayout which doesn't serve any purpose and is redundant. A look at the layout through Layout Inspector tool clearly explains this.
content_profile.xml after updating the code to use merge instead of a ViewGroup like LinearLayout.
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Howdy" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hi there" />
</merge>
Now our layout looks like this
<LinearLayout>
<TextView />
<TextView />
</LinearLayout>
Here we see that the redundant LinearLayout ViewGroup is removed. Now Layout Inspector tool gives the following layout hierarchy.
So always try to use merge when your parent layout can position your child layouts, or more precisely use merge when you understand that there is going to be a redundant view group in the hierarchy.
I resolved this issue with
sudo rm /usr/bin/java
And I downloaded and installed the last Java SE Runtime Environment: http://www.oracle.com/technetwork/java/javase/downloads/index.html
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/bin/java /usr/bin/java
did not work for me because I got Operation not permitted
. El Capitan now protects certain system directories in "rootless" mode (a.k.a. System Integrity Protection). It is applicable to macOS Sierra, and probably new macOS versions for the foreseeable future.
Broadly speaking, there are three groups of people out there.
Those who will not buy your software and resort to cracks, or if they don't find any, not use your software at all. Don't expect to make any money from this group. They rely either on their own skills or on crackers (who tend to prioritize their time depending on your useful and how big your audience is. The more useful, the sooner a crack will be available).
The group of legitimate users who will buy (pay for) your software, irrespective of what protection mechanism you use. Don't make life hard for your legitimate users by using an elaborate protection mechanism since they are going to pay for it in any case. A complex protection mechanism can easily spoil the user experience and you don't want this happening to this group. Personally, I'd vote against any hardware solution, which adds to the cost of your software.
A minority who will resort to "unethical" cracking and will only pay for your software because its features are protected by a licensing mechanism. You probably don't want to make it exceedingly easy for this group to circumvent your protection. However, all that effort you spend on protecting your software will pay back, depending on how big this group of people is. This entirely depends on the type of software you're building.
Given what you've said, if you think there is a large enough minority who can be pushed into buying your software, go ahead and implement some form of protection. Think about how much money you can make from this minority versus the time you spend working on the protection, or the amount you spend on a third party protection API/tool.
If you like to implement a solution of your own, using public-key cryptography is a good way (as opposed to symmetric algorithms) to prevent easy hacks. You could for instance digitally sign your license (serial no, or license file). The only way to get around this would then be to decompile, alter and recompile the code (which you could make harder using techniques such as those suggested in Simucal's answer).
That is a binary operator in hibernate you should use
is not null
Have a look at 14.10. Expressions
Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String filePath) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath = filePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream = fileStream;
}
private void loadFile() throws FileNotFoundException,
NullObjectFoundException {
if (resourceAsStream == null)
throw new FileNotFoundException("Unable to locate give file..");
else {
try {
workbook = new XSSFWorkbook(resourceAsStream);
} catch (IOException ex) {
}
}
}// end loadxlsFile
public String[] getSheetsName() {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex() {
int totalsheet = 0;
int i = 0;
int[] sheetIndex = null;
String[] sheetname = getSheetsName();
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetIndex = new int[totalsheet];
while (i < totalsheet) {
sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index) {
if (index < getSheetsIndex().length && index >= 0)
return true;
else
return false;
}
public int getNumberOfSheet() {
int totalsheet = 0;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
// logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
// logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex) {
int NO_OF_Column = 0;
@SuppressWarnings("unused")
XSSFCell cell = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = firstRow.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex) {
int NO_OF_ROW = 0;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex) {
int noOfColumns = 0;
XSSFCell cell = null;
int i = 0;
String columns[] = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = Row.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
// logger.error(ex);
}
return columns;
}// end of method
public String[][] getSheetData(int SheetIndex) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int noOfRows = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows = getNumberOfRows(SheetIndex) + 1;
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
data[i][j] = Boolean.toString(cell
.getBooleanCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
public String[][] getSheetData(int SheetIndex, int noOfRows) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (i < noOfRows) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
}
Created this little testcode:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
System.out.println(test.getSheetsName());
System.out.println(test.getNumberOfSheet());
}
}
All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.
Cheers, Wim
If calculating with dates summertime will cause often 1 uur more or one hour less than midnight (CEST). This causes 1 day difference when dates return. So the dates have to round to the nearest midnight. So the code will be (ths to jamisOn):
var d = new Date();
if(d.getHours() < 12) {
d.setHours(0,0,0,0); // previous midnight day
} else {
d.setHours(24,0,0,0); // next midnight day
}
Came here from google looking for same issue and wasted 4 hours to figure out what could be wrong. And now I feel really stupid while posting this answer. In my case SDK, JDK, JRE, Ant and everything else was installed and working a day before.
But just one particular project was giving me this issue. This one was under "C:\Users\Name\Documents" location
Soon I realized that I was running cmd as normal user, as soon as I choose "Run as Administrator" everything started working.
Tip: Always consider project location carefully!
If your app is in background, Firebase will not trigger onMessageReceived(). onMessageReceived() is called when app is in foreground . When app is in background,onMessageReceived() method will be called only if the body of https://fcm.googleapis.com/fcm/send contain only data payload.Here ,i just created a method to build custom notification with intent having ur your required activity . and called this method in onMessageRecevied() .
In PostMan:
uri: https://fcm.googleapis.com/fcm/send
header:Authorization:key=ur key
body --->>
{ "data" : {
"Nick" : "Mario",
"Room" : "PoSDenmark",
},
"to" : "xxxxxxxxx"
}
in your application.
class MyFirebaseMessagingService extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
sendNotification("ur message body") ;
}
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, Main2Activity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
when the data payload comes to the mobile,then onMessageReceived() method will be called.. inside that method ,i just made a custom notification. this will work even if ur app is background or foreground.
This happens because in r6 it shows an error when you try to extend private styles.
Refer to this link
JScript is Microsoft's implementation of the ECMAScript specification. JavaScript is the Mozilla implementation of the specification.
Remove javascript:
from onclick="..
, onsubmit="..
declarations
javascript:
prefix is used only in href=""
or similar attributes (not events related)
For ones who got permission denied
for saving operation, here is the command that worked for me:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png
My navigation bar was not showing, so I have used the following method in Swift 2 iOS 9
let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("Dashboard") as! Dashboard
// Creating a navigation controller with viewController at the root of the navigation stack.
let navController = UINavigationController(rootViewController: viewController)
self.presentViewController(navController, animated:true, completion: nil)
After Stop xampp, go to configure and change the port 3306 to 3308 of mysql and save. Now start the sql......Enjoy
i used this simply
Linkify.addLinks(TextView, Linkify.ALL);
makes the links clickable given here
Best description is on: http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en
For simple use permissions you can use this lib: http://hotchemi.github.io/PermissionsDispatcher/
I have been using this as an alternative of mysql_real_escape_string()
:
function htmlsan($htmlsanitize){
return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
}
$data = "Whatever the value's is";
$data = stripslashes(htmlsan($data));
One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:
npm cache clean
And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.
This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.
JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.
JavaScript will not be able to determine your Windows user name.
Do not mix 12 and 15, use this
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-auth:16.0.1'
implementation 'com.google.firebase:firebase-messaging:17.0.0'
There is an infinity in the NumPy library: from numpy import inf
. To get negative infinity one can simply write -inf
.
$("#mydropdownlist").val("thevalue");
just make sure the value in the options tags matches the value in the val method.
ResultSet
to your main program or do your stuff in the same method.0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
How to install Python / Pip on Windows Steps
Run the installer. Be sure to check the option to add Python to your PATH while installing.
Open PowerShell as admin by right clicking on the PowerShell icon and selecting ‘Run as Admin’
To solve permission issues, run the following command:
Set-ExecutionPolicy Unrestricted
Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this: C:\Python35-32;C:\Python35-32\Lib\site-packages\;C:\Python35-32\Scripts\
download the bootstrap scripts for easy_install and pip from https://bootstrap.pypa.io/ ez_setup.py get-pip.py
Save both the files in Python Installed folder Go to Python folder and run following: Python ez_setup.py Python get-pip.py
To create a Virtual Environment, use the following commands:
cd c:\python pip install virtualenv virtualenv test .\test\Scripts\activate.ps1 pip install IPython ipython3 Now You can install any Python package with pip
That’s it !! happy coding Visit This link for Easy steps of Installation python and pip in windows http://rajendralora.com/?p=183
Here is a way to get a string variable without having to worry about the coding.
If you have Mozilla Thunderbird, you can use it to fetch the html image code for you.
I wrote a little tutorial here, complete with a screenshot (it's for powershell, but that doesn't matter for this):
powershell email with html picture showing red x
And again:
Uri.IsFile doesn't work with http urls. It only works for "file://". From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile." So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
The XmlConvert
class provides these kinds of facilities.
About DateTimes, in particular, be careful about obsolete methods.
See also: https://stackoverflow.com/a/7457718/1288109
I have a lengthy form (250+ fields) that posts to a db. It is an online employment application. When an admin goes to look at an application that has been filed, the form is populated with data from the db. Input texts and textareas are replaced with the text they submitted but the radios and checkboxes are useful to keep as form elements. Disabling them makes them harder to read. Setting the .checked property to false onclick won't work because they may have been checked by the user filling out the app. Anyhow...
onclick="return false;"
works like a charm for 'disabling' radios and checkboxes ipso facto.
Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.
Example: http://jsfiddle.net/SHLu4/2/
It'll be something like:
<div class="container drop-shadow">
<div class="container">
<div class="row">
<div class="col-md-8">Main Area</div>
<div class="col-md-4">Side Area</div>
</div>
</div>
</div>
And your CSS:
<style>
.drop-shadow {
-webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
}
.container.drop-shadow {
padding-left:0;
padding-right:0;
}
</style>
If the second observable is hot, there is another way to do pause/resume:
var pauser = new Rx.Subject();
var source1 = Rx.Observable.interval(1000).take(1);
/* create source and pause */
var source2 = Rx.Observable.interval(1000).pausable(pauser);
source1.doOnCompleted(function () {
/* resume paused source2 */
pauser.onNext(true);
}).subscribe(function(){
// do something
});
source2.subscribe(function(){
// start to recieve data
});
Also you can use buffered version pausableBuffered to keep data during pause is on.
Be aware that Total Server Memory is NOT how much memory SQL Server is currently using.
refer to this Microsoft article: http://msdn.microsoft.com/en-us/library/ms190924.aspx
You can do it using xml.
Create an xml layout and name it like my_edit_text_border.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
<item>
<shape android:shape="rectangle">
<solid android:color="#ffffff"/>
<corners android:radius="5dp" />
<stroke
android:width="2dp"
android:color="#949494"
/>
</shape>
</item>
</selector>
Add background to your Edittext
<EditText
android:id="@+id/editText1"
..
android:background="@layout/my_edit_text_border">
I'm not sure if this helps, but I needed to create a macro to hold a snippet, so I simply recorded myself inserting the items and set a shortcut to it. Granted, I'm not using version 5.9 so there might be some slight version differences. To access the macro recorder go to Macro > Start Recording. Then you will perform your action and then go to Macro > Stop Recording. I'd recommend playing it back to ensure it's correct and then save and set your shortcut key.
Hope the helps.
In my experience, working with Firebase is a huge advantage if you are trying to do user management, database, messaging sort of app since all of these features are already well integrated.
Like others have said, if you're just focused on the database/querying aspect, stick to mongo.
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
UPDATE: I had some time on my hands, so ... I went ahead and fleshed out this idea. See below for the code.
Here's a bit of a crazy answer:
You could do what you're looking for -- essentially treat a two-dimensional array as a table with rows -- by writing a static method (perhaps an extension method) that takes a T[,]
and returns an IEnumerable<T[]>
. This would require copying each "row" of the underlying table into a new array, though.
A perhaps better (though more involved) approach would be to actually write a class that implements IList<T>
as a wrapper around a single "row" of a two-dimensional array (you would probably set IsReadOnly
to true and just implement the getter for the this[int]
property and probably Count
and GetEnumerator
; everything else could throw a NotSupportedException
). Then your static/extension method could return an IEnumerable<IList<T>>
and provide deferred execution.
That way you could write code pretty much like what you have:
foreach (IList<string> row in table.GetRows()) // or something
{
Console.WriteLine(row[0] + " " + row[1]);
}
Just a thought.
Implementation suggestion:
public static class ArrayTableHelper {
public static IEnumerable<IList<T>> GetRows<T>(this T[,] table) {
for (int i = 0; i < table.GetLength(0); ++i)
yield return new ArrayTableRow<T>(table, i);
}
private class ArrayTableRow<T> : IList<T> {
private readonly T[,] _table;
private readonly int _count;
private readonly int _rowIndex;
public ArrayTableRow(T[,] table, int rowIndex) {
if (table == null)
throw new ArgumentNullException("table");
if (rowIndex < 0 || rowIndex >= table.GetLength(0))
throw new ArgumentOutOfRangeException("rowIndex");
_table = table;
_count = _table.GetLength(1);
_rowIndex = rowIndex;
}
// I didn't implement the setter below,
// but you easily COULD (and then set IsReadOnly to false?)
public T this[int index] {
get { return _table[_rowIndex, index]; }
set { throw new NotImplementedException(); }
}
public int Count {
get { return _count; }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i < _count; ++i)
yield return this[i];
}
// omitted remaining IList<T> members for brevity;
// you actually could implement IndexOf, Contains, etc.
// quite easily, though
}
}
...now I think I should give StackOverflow a break for the rest of the day ;)
For me it worked best to export all data with this command:
mysqldump -u USERNAME -p --all-databases --complete-insert --extended-insert=FALSE --compatible=mssql > backup.sql
--extended-insert=FALSE is needed to avoid mssql 1000 rows import limit.
I created my tables with my migration tool, so I'm not sure if the CREATE from the backup.sql file will work.
In MSSQL's SSMS I had to imported the data table by table with the IDENTITY_INSERT ON to write the ID fields:
SET IDENTITY_INSERT dbo.app_warehouse ON;
GO
INSERT INTO "app_warehouse" ("id", "Name", "Standort", "Laenge", "Breite", "Notiz") VALUES (1,'01','Bremen',250,120,'');
SET IDENTITY_INSERT dbo.app_warehouse OFF;
GO
If you have relationships you have to import the child first and than the table with the foreign key.
In addition of export EDITOR="code --wait"
, note that, with VSCode v1.47 (June 2020), those diff editors will survice a VSCode reload/restart.
See issue 99290:
with commit 1428d44, diff editors now have a chance to survive reloads and this works OK unless the diff editor on a git resource is opened as the active one:
(and commit 24f1b69 fixes that)
When you create a virtual device from Android Studio pay attention to the Play Store Column in the device table. The images with the play store icon have google play pre-installed.
?? In system images that come with google play root is not available.
After you've created the AVD you'll also be able to see from the Android Studio AVD Manager which of your images have google play installed:
For turning off line numbers, any of these commands will work:
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
The rownumber functionality can't be mimicked. You might get the results you expect, but you'll most likely get disappointed at some stage. Here's what mysql documentation says:
For other statements, such as SELECT, you might get the results you expect, but this is not guaranteed. In the following statement, you might think that MySQL will evaluate @a first and then do an assignment second: SELECT @a, @a:=@a+1, ...; However, the order of evaluation for expressions involving user variables is undefined.
Regards, Georgi.
I just came across this. The correct answer is:
awk 'BEGIN{FS=OFS=","} {gsub(/^[[:space:]]+|[[:space:]]+$/,"",$2)} 1'
Compatible with all SDK versions (android.permission.ACCESS_FINE_LOCATION
became dangerous
permission in Android M and requires user to manually grant it).
In Android versions below Android M ContextCompat.checkSelfPermission(...)
always returns true
if you add these permission(s) in AndroidManifest.xml
)
public void onSomeButtonClick() {
...
if (!permissionsGranted()) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else doLocationAccessRelatedJob();
...
}
private Boolean permissionsGranted() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED);
}
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
doLocationAccessRelatedJob();
} else {
// User refused to grant permission. You can add AlertDialog here
Toast.makeText(this, "You didn't give permission to access device location", Toast.LENGTH_LONG).show();
startInstalledAppDetailsActivity();
}
}
}
private void startInstalledAppDetailsActivity() {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:" + getPackageName()));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
SecurityManager
has a protected method getClassContext
By creating a utility class which extends SecurityManager, you can access this.
public class CallingClass extends SecurityManager {
public static final CallingClass INSTANCE = new CallingClass();
public Class[] getCallingClasses() {
return getClassContext();
}
}
Use CallingClass.INSTANCE.getCallingClasses()
to retrieve the calling classes.
There is also a small library (disclaimer: mine) WhoCalled which exposes this information. It uses Reflection.getCallerClass when available, else falls back to SecurityManager.
To help newbies navigate through the manual fog, it might be helpful to see the [[ ... ]]
notation as a collapsing function - in other words, it is when you just want to 'get the data' from a named vector, list or data frame. It is good to do this if you want to use data from these objects for calculations. These simple examples will illustrate.
(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]
So from the third example:
> 2 * x[1]
x
1 2
> 2 * x[[1]]
[1] 2
It has been a while since this question was posted, but the following code works across all browsers (note although MattPII
's answer works in FFox and Chrome, it throws script errors in IE).
$('#foo').dialog({
autoOpen: true,
buttons: [
{
text: 'OK',
open: function() { $(this).addClass('b') }, //will append a class called 'b' to the created 'OK' button.
click: function() { alert('OK Clicked')}
},
{
text: "Cancel",
click: function() { alert('Cancel Clicked')}
}
]
});
I think why you want to zoom-in and zoom-out the image view is because your image view is small and zooming in the image there will not let the image come out of the image view. Instead, image starts disappearing from the boundaries while zooming in. So letting the image come out of the image while we zoom in is what you want I guess.
So there are two tricks (according to me) to achieve this-
Trick no.1 does not work when the image View is nested very much inside other views (like in nested recycler view)
Trick no.2 works always :-)
Here is the implementation of trick no.2 -
public class ZoomOnTouchListener extends AppCompatActivity implements View.OnTouchListener {
private Matrix matrix = new Matrix();
private boolean isfullImgViewActive = false;
// above boolean gets true when when we firstly move 2 fingers on the smallImgView and in this case smallImgView gets invisible and fullImgView gets visible
// and false if smallImgView is visible and fullImgView is gone
private float[] matrixArray = new float[9];
private float orgScale;
private PointF start = new PointF();
private PointF prevP1 = new PointF();
private PointF prevP2 = new PointF();
private PointF mid = new PointF();
private float oldDist = 1f;
private ImageView mfullImgView;
private ImageView smallImgView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfullImgView = (ImageView)findViewById(R.id.imgView2);
mfullImgView.setVisibility(View.GONE);
smallImgView = (ImageView)findViewById(R.id.imgView);
smallImgView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
//Log.i("0", "OnTouch()");
if(v instanceof ImageView) {
ImageView imgView = (ImageView) v;
boolean isImgViewSmall = (imgView == smallImgView);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
//Log.i("T", "Motion Event: ACTION_DOWN");
if(isImgViewSmall)
start.set(event.getX(), event.getY());
prevP1.set(event.getX(), event.getY());
return true;
case MotionEvent.ACTION_POINTER_DOWN: //second finger and other fingers down
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
oldDist = spacing(event);
midPoint(mid, event);
break;
case MotionEvent.ACTION_MOVE: //it doesn't mean fingers are moved. In this case, all pointers which are active are batched together
// this case occurs after action_down or action_pointer_down
//Log.i("Tag", event.getX()+","+event.getY());
if(event.getPointerCount() == 2) {
PointF newMid = new PointF();
midPoint(newMid,event);
float newDist = spacing(event);
float scale = newDist/oldDist;
if( !isfullImgViewActive){ // is smallImgView is visible and mfullImgView is gone
Log.i("tag", "true");
isfullImgViewActive = true;
matrix.set(imgView.getImageMatrix()); //note:- do not write matrix = imgView.getImageMatrix() because it gives the smallImgView's matrix reference to the matrix variable and changes on matrix will reflect on smallImgView
matrix.getValues(matrixArray);
orgScale = matrixArray[0];
smallImgView.setVisibility(View.INVISIBLE);
mfullImgView.setImageDrawable(smallImgView.getDrawable());
mfullImgView.setScaleType(ImageView.ScaleType.MATRIX);
mfullImgView.setVisibility(View.VISIBLE);
//To map the image of mFullImgView to that of smallImgView we have to
// translate the mFullImgView's image
matrix.postTranslate(tx, ty);
/////////////NOTE///////////////
//here (tx,ty) are coordinates of top-left corner of smallimgView and
// they MUST be relative to the origin of Outermost view or view group
// where fullImgView is placed. So find tx,ty in your case by yourself
mfullImgView.setImageMatrix(matrix);
}
if(isImgViewSmall) {
matrix.postScale(scale, scale, mid.x + tx, mid.y + ty);
}
else{
matrix.postScale(scale, scale, mid.x, mid.y);
}
oldDist = newDist;
matrix.postTranslate(newMid.x - mid.x, newMid.y - mid.y);
matrix.getValues(matrixArray);
mid.set(newMid);
prevP1.set(event.getX(0), event.getY(0));
prevP2.set(event.getX(1), event.getY(1));
}
else if(event.getPointerCount() == 1 ){
if(isfullImgViewActive) {
matrix.postTranslate(event.getX() - prevP1.x, event.getY() - prevP1.y);
matrix.getValues(matrixArray);
}
prevP1.set(event.getX(0), event.getY(0));
}
break;
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
//Now if pointer of index 0 is lifted then pointer of index 1 will get index 0;
if(event.getActionIndex() == 0 && isfullImgViewActive){
Log.i("TAg", event.getActionIndex()+"");
prevP1.set(prevP2);
}
break;
case MotionEvent.ACTION_UP: // first finger lifted or all fingers are lifted
if(isImgViewSmall && !isfullImgViewActive) {
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
int xDiff = (int) Math.abs(event.getX() - start.x);
int yDiff = (int) Math.abs(event.getY() - start.y);
if (xDiff == 0 && yDiff == 0) {
imgView.performClick();
return true;
}
}
if(isfullImgViewActive){
if(matrixArray[0] <= orgScale){ //matrixArray[0] is Scale.X value
mfullImgView.setOnTouchListener(null);
mfullImgView.setImageDrawable(null);
mfullImgView.setVisibility(View.GONE);
smallImgView.setOnTouchListener(this);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.VISIBLE);
isfullImgViewActive = false;
}
else if(matrixArray[0] > orgScale && isImgViewSmall){ //if the imgView was smallImgView
smallImgView.setOnTouchListener(null);
smallImgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
smallImgView.setVisibility(View.GONE); // or View.INVISIBLE
mfullImgView.setOnTouchListener(this);
}
}
return true;
}
//end of Switch statement
if(isfullImgViewActive) { //active means visible
mfullImgView.setImageMatrix(matrix); // display the transformation on screen
}
return true; // indicate event was handled
}
else
return false;
}
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event)
{
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
}
NOTE:- Don't set OnClickListener to mfullImgView before setting onTouchListener to it. Setting that will let the fullImageView(if it is visible) steal the touch event of putting second finger down after lifting it for the first time because we want to let the smallImgView take all the touch events until all the fingers are lifted up for the first time.
This hasn't solved my problem too, so I changed the parameters slightly.
This code worked for me:
var dataValue = "{ name: 'person', isGoing: 'true', returnAddress: 'returnEmail' }";
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result.d);
}
});
Spring Boot already has support for profile based properties.
Simply add an application-[profile].properties
file and specify the profiles to use using the spring.profiles.active
property.
-Dspring.profiles.active=local
This will load the application.properties
and the application-local.properties
with the latter overriding properties from the first.
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
How to implement 'in' and 'not in' for a pandas DataFrame?
Pandas offers two methods: Series.isin
and DataFrame.isin
for Series and DataFrames, respectively.
The most common scenario is applying an isin
condition on a specific column to filter rows in a DataFrame.
df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
countries
0 US
1 UK
2 Germany
3 China
c1 = ['UK', 'China'] # list
c2 = {'Germany'} # set
c3 = pd.Series(['China', 'US']) # Series
c4 = np.array(['US', 'UK']) # array
Series.isin
accepts various types as inputs. The following are all valid ways of getting what you want:
df['countries'].isin(c1)
0 False
1 True
2 False
3 False
4 True
Name: countries, dtype: bool
# `in` operation
df[df['countries'].isin(c1)]
countries
1 UK
4 China
# `not in` operation
df[~df['countries'].isin(c1)]
countries
0 US
2 Germany
3 NaN
# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]
countries
2 Germany
# Filter with another Series
df[df['countries'].isin(c3)]
countries
0 US
4 China
# Filter with array
df[df['countries'].isin(c4)]
countries
0 US
1 UK
Sometimes, you will want to apply an 'in' membership check with some search terms over multiple columns,
df2 = pd.DataFrame({
'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})
df2
A B C
0 x w 0
1 y a 1
2 z NaN 2
3 q x 3
c1 = ['x', 'w', 'p']
To apply the isin
condition to both columns "A" and "B", use DataFrame.isin
:
df2[['A', 'B']].isin(c1)
A B
0 True True
1 False False
2 False False
3 False True
From this, to retain rows where at least one column is True
, we can use any
along the first axis:
df2[['A', 'B']].isin(c1).any(axis=1)
0 True
1 False
2 False
3 True
dtype: bool
df2[df2[['A', 'B']].isin(c1).any(axis=1)]
A B C
0 x w 0
3 q x 3
Note that if you want to search every column, you'd just omit the column selection step and do
df2.isin(c1).any(axis=1)
Similarly, to retain rows where ALL columns are True
, use all
in the same manner as before.
df2[df2[['A', 'B']].isin(c1).all(axis=1)]
A B C
0 x w 0
numpy.isin
, query
, list comprehensions (string data)In addition to the methods described above, you can also use the numpy equivalent: numpy.isin
.
# `in` operation
df[np.isin(df['countries'], c1)]
countries
1 UK
4 China
# `not in` operation
df[np.isin(df['countries'], c1, invert=True)]
countries
0 US
2 Germany
3 NaN
Why is it worth considering? NumPy functions are usually a bit faster than their pandas equivalents because of lower overhead. Since this is an elementwise operation that does not depend on index alignment, there are very few situations where this method is not an appropriate replacement for pandas' isin
.
Pandas routines are usually iterative when working with strings, because string operations are hard to vectorise. There is a lot of evidence to suggest that list comprehensions will be faster here..
We resort to an in
check now.
c1_set = set(c1) # Using `in` with `sets` is a constant time operation...
# This doesn't matter for pandas because the implementation differs.
# `in` operation
df[[x in c1_set for x in df['countries']]]
countries
1 UK
4 China
# `not in` operation
df[[x not in c1_set for x in df['countries']]]
countries
0 US
2 Germany
3 NaN
It is a lot more unwieldy to specify, however, so don't use it unless you know what you're doing.
Lastly, there's also DataFrame.query
which has been covered in this answer. numexpr FTW!
On centos 7:
$ yum install curl-devel
$ yum reinstall git
That work´s for me.
Try a case statement
WHERE
CASE WHEN @zipCode IS NULL THEN 1
ELSE @zipCode
END
Two UE Boom Bluetooth speakers can form a stereo, which means the phone can stream simultaneously to two Bluetooth devices. The reason is Bluetooth 4.0 can support up to two synchronous connection oriented (SCO) links on the same piconet, and A2DP is based on SCO link.
Your demand "bluetooth chat" is based on SPP profile, and SPP is based on RFCOMM protocol. Luckily even Bluetooth 2.1 can support multiple RFCOMM channels, so yes, you can have multiple bluetooth connection to chat with each other.
You could do it as follows - with validation just to ensure that the datepicker is bound to the element.
var dt;
if ($("div#someID").is('.hasDatepicker')) {
dt = $("div#someID").datepicker('getDate');
}
This is what I have so far:
var actionName = filterContext.ActionDescriptor.ActionName;
var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
In my case, It was returning one output parameter and was not Returning any value.
So changed it to
param.Direction = ParameterDirection.Output;
command.ExecuteScalar();
and then it was throwing size error. so had to set the size as well
SqlParameter param = new SqlParameter("@Name",SqlDbType.NVarChar);
param.Size = 10;
This is an addendum to the accepted answer by AndreyT, with Nyan's comment on mismatched array sizes. I disagree with their automatic setting of the fifth element to zero. It should likely be 5 --the number after 1,2,3,4. So I would suggest a wrapper to memcpy() to produce a compile-time error when we try to copy arrays of different sizes:
#define Memcpy(a,b) do { /* copy arrays */ \
ASSERT(sizeof(a) == sizeof(b) && /* a static assert */ \
sizeof(a) != sizeof((a) + 0)); /* no pointers */ \
memcpy((a), (b), sizeof (b)); /* & unnecesary */ \
} while (0) /* no return value */
This macro will generate a compile-time error if your array is of length 1. Which is perhaps a feature.
Because we are using a macro, the C99 compound literal seems to need an extra pair of parentheses:
Memcpy(myarray, ((int[]) { 1, 2, 3, 4 }));
Here ASSERT() is a 'static assert'. If you don't already have your own, I use the following on a number of platforms:
#define CONCAT_TOKENS(a, b) a ## b
#define EXPAND_THEN_CONCAT(a,b) CONCAT_TOKENS(a, b)
#define ASSERT(e) enum {EXPAND_THEN_CONCAT(ASSERT_line_,__LINE__) = 1/!!(e)}
#define ASSERTM(e,m) /* version of ASSERT() with message */ \
enum{EXPAND_THEN_CONCAT(m##_ASSERT_line_,__LINE__)=1/!!(e)}
First add a global variable
Context mContext;
Then change your constructor to this
public FeedAdapter(Context context, List<Post> myDataset) {
mContext = context;
mDataset = myDataset;
}
The pass your context when creating the adapter.
FeedAdapter myAdapter = new FeedAdapter(this,myDataset);
Simply go to the directory where the troubling file is, type touch *
without quotes in the console, and you should be good.
Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:
func yourHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("header_name", "header_value")
}
Since there's no answer stating just this, summarized succinctly:
Carriage Return (MAC pre-OSX)
Line Feed (Linux, MAC OSX)
Carriage Return and Line Feed (Windows)
If you see ASCII code in a strange format, they are merely the number 13 and 10 in a different radix/base, usually base 8 (octal) or base 16 (hexadecimal).
Native browser smooth scrolling in JavaScript is like this:
// scroll to specific values,
// same as window.scroll() method.
// for scrolling a particular distance, use window.scrollBy().
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// scroll certain amounts from current position
window.scrollBy({
top: 100, // negative value acceptable
left: 0,
behavior: 'smooth'
});
// scroll to a certain element
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.
mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());
// now you are connected
With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools
.
In order to fix that, one should:
Programs and Features
find Visual Studios related version
there, click on it,Change
.
Then the setup window will appear, Web Developer Tools
there and continue to setup.It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools
now.
I had to do this in that order:
Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD
This is how I applied the code snippet below and it's working fine. Hope, this would help somebody.
<EditText
android:id="@+id/EditText02"
android:gravity="top|left"
android:inputType="textMultiLine"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:lines="5"
android:scrollHorizontally="false"
/>
Cheers! ...Thanks.
The best way is checking out the changes.
Changing the file pom.xml in a project named project-name you can do it:
git status
# modified: project-name/pom.xml
git checkout project-name/pom.xml
git checkout master
# Checking out files: 100% (491/491), done.
# Branch master set up to track remote branch master from origin.
# Switched to a new branch 'master'
In my opinion, the simplest way to get the amount of selected rows is the following:
The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)
Example:
print len(cursor.fetchall)
There might be another way, but this should work:
SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET]
WHERE day(Submission_date)=day(now) and
month(Submission_date)=month(now)
and year(Submission_date)=year(now)
Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.
I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.
The dict[key] = value
represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.
If your table is separated by others than tabs, you should specify it like...
LOAD DATA LOCAL
INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport
COLUMNS TERMINATED BY '\t' ## This should be your delimiter
OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here
Here's a working example in golang. I searched around and found this page and converted this over to what I needed. Hope someone else can find it useful.
// https://classroom.synonym.com/calculate-trendline-2709.html
package main
import (
"fmt"
"math"
)
func main() {
graph := [][]float64{
{1, 3},
{2, 5},
{3, 6.5},
}
n := len(graph)
// get the slope
var a float64
var b float64
var bx float64
var by float64
var c float64
var d float64
var slope float64
for _, point := range graph {
a += point[0] * point[1]
bx += point[0]
by += point[1]
c += math.Pow(point[0], 2)
d += point[0]
}
a *= float64(n) // 97.5
b = bx * by // 87
c *= float64(n) // 42
d = math.Pow(d, 2) // 36
slope = (a - b) / (c - d) // 1.75
// calculating the y-intercept (b) of the Trendline
var e float64
var f float64
e = by // 14.5
f = slope * bx // 10.5
intercept := (e - f) / float64(n) // (14.5 - 10.5) / 3 = 1.3
// output
fmt.Println(slope)
fmt.Println(intercept)
}
The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.
I added some fixes to @jessegavin's fix.
This will return right away if there is an ID on the element. I also added a name attribute check and a nth-child selector in case a element has no id, class, or name.
The name might need scoping in case there a multiple forms on the page and have similar inputs, but I didn't handle that yet.
function getSelector(el){
var $el = $(el);
var id = $el.attr("id");
if (id) { //"should" only be one of these if theres an ID
return "#"+ id;
}
var selector = $el.parents()
.map(function() { return this.tagName; })
.get().reverse().join(" ");
if (selector) {
selector += " "+ $el[0].nodeName;
}
var classNames = $el.attr("class");
if (classNames) {
selector += "." + $.trim(classNames).replace(/\s/gi, ".");
}
var name = $el.attr('name');
if (name) {
selector += "[name='" + name + "']";
}
if (!name){
var index = $el.index();
if (index) {
index = index + 1;
selector += ":nth-child(" + index + ")";
}
}
return selector;
}
To convert character digit to corresponding integer. Do as shown below:
char c = '8';
int i = c - '0';
Logic behind the calculation above is to play with ASCII values. ASCII value of character 8 is 56, ASCII value of character 0 is 48. ASCII value of integer 8 is 8.
If we subtract two characters, subtraction will happen between ASCII of characters.
int i = 56 - 48;
i = 8;
Modifying dates based on this post
strtotime() is really powerful and allows you to modify/transform dates easily with it’s relative expressions too:
Procedural
$dateString = '2011-05-01 09:22:34';
$t = strtotime($dateString);
$t2 = strtotime('-3 days', $t);
echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
DateTime
$dateString = '2011-05-01 09:22:34';
$dt = new DateTime($dateString);
$dt->modify('-3 days');
echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100
The stuff you can throw at strtotime() is quite surprising and very human readable. Have a look at this example looking for Tuesday next week.
Procedural
$t = strtotime("Tuesday next week");
echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
DateTime
$dt = new DateTime("Tuesday next week");
echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100
Note that these examples above are being returned relative to the time now. The full list of time formats that strtotime() and the DateTime constructor takes are listed on the PHP Supported Date and Time Formats page.
Another example, suitable for your case could be: based on this post
<?php
//How to get the day 3 days from now:
$today = date("j");
$thisMonth = date("n");
$thisYear = date("Y");
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear));
//1 week from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));
//4 months from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear));
//3 years, 2 months and 35 days from now:
list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
?>
More correct variant:
{
struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};
while (nanosleep(&delta, &delta));
}
(It's been a while since I did this stuff. Please don't blindly assume that all the details below are correct. But I hope I'm not too embarrassingly wrong. :))
As the previous answer stated, the Minecraft client (as of 1.3.1) supports SRV record lookup using the service name _minecraft
and the protocol name _tcp
, which means that if your zone file looks like this...
arboristal.com. 86400 IN A <your IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25566 arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25567 arboristal.com.
...then Minecraft clients who perform SRV record lookup as hinted in the changelog will use ports 25566 and 25567 with preference (40% of the time each) over port 25565 (20% of the time). We can assume that Minecraft clients who do not find and respect these SRV records will use port 25565 as usual.
However, I would argue that it would actually be more "clean and professional" to do it using a load balancer such as Nginx. (I pick Nginx just because I've used it before. I'm not claiming it's uniquely suited to this task. It might even be a bad choice for some reason.) Then you don't have to mess with your DNS, and you can use the same approach to load-balance any service, not just ones like Minecraft which happen to have done the hard client-side work to look up and respect SRV records. To do it the Nginx way, you'd run Nginx on the arboristal.com
machine with something like the following in /etc/nginx/sites-enabled/arboristal.com
:
upstream minecraft_servers {
ip_hash;
server 127.0.0.1:25566 weight=1;
server 127.0.0.1:25567 weight=1;
server 127.0.0.1:25568 weight=1;
}
server {
listen 25565;
proxy_pass minecraft_servers;
}
Here we are controlling the load-balancing ourselves on the server side (via Nginx), so we no longer need to worry that badly behaved clients might prefer port 25565 to the other two ports. In fact, now all clients will talk to arboristal.com:25565
! But the listener on that port is no longer a Minecraft server; it's Nginx, secretly proxying all the traffic onto three other ports on the same machine.
We load-balance based on a hash of the client's IP address (ip_hash
), so that if a client disconnects and then reconnects later, there's a good chance that it'll get reconnected to the same Minecraft server it had before. (I don't know how much this matters to Minecraft, or how SRV-enabled clients are programmed to deal with this aspect.)
Notice that we used to run a Minecraft server on port 25565; I've moved it to port 25568 so that we can use port 25565 for the load-balancer.
A possible disadvantage of the Nginx method is that it makes Nginx a bottleneck in your system. If Nginx goes down, then all three servers become unreachable. If some part of your system can't keep up with the volume of traffic on that single port, 25565, all three servers become flaky. And not to mention, Nginx is a big new dependency in your ecosystem. Maybe you don't want to introduce yet another massive piece of software with a complicated config language and a huge attack surface. I can respect that.
A possible advantage of the Nginx method is... that it makes Nginx a bottleneck in your system! You can apply global policies via Nginx, such as rejecting packets above a certain size, or responding with a static web page to HTTP connections on port 80. You can also firewall off ports 25566, 25567, and 25568 from the Internet, since now they should be talked to only by Nginx over the loopback interface. This reduces your attack surface somewhat.
Nginx also makes it easier to add new Minecraft servers to your backend; now you can just add a server
line to your config and service nginx reload
. Using the old port-based approach, you'd have to add a new SRV record with your DNS provider (and it could take up to 86400
seconds for clients to notice the change) and then also remember to edit your firewall (e.g. /etc/iptables.rules
) to permit external traffic over that new port.
Nginx also frees you from having to think about DNS TTLs when making ops changes. Suppose you decide to split up your three Minecraft servers onto three different physical machines with different IP addresses. Using Nginx, you can do that completely via config changes to your server
lines, and you can keep those new machines inside your firewall (connected only to Nginx over a private interface), and the changes will take effect immediately, by definition. Whereas, using SRV records, you'll have to rewrite your zone file to something like this...
arboristal.com. 86400 IN CNAME mc1.arboristal.com.
mc1.arboristal.com. 86400 IN A <a new machine's IP address>
mc2.arboristal.com. 86400 IN A <a new machine's IP address>
mc3.arboristal.com. 86400 IN A <a new machine's IP address>
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 20 25565 mc1.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc2.arboristal.com.
_minecraft._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc3.arboristal.com.
...and you'll have to leave all three new machines poking outside your firewall so that they can receive connections from the Internet. And you'll have to wait up to 86400
seconds for your clients to notice the change, which could affect the complexity of your rollout plan. And if you were running any other services (such as an HTTP server) on arboristal.com
, now you have to move them to the mc1.arboristal.com
machine because of how I did that CNAME. I did that only for the benefit of those hypothetical Minecraft clients who don't respect SRV records and will still be trying to connect to arboristal.com:25565
.
So, I think both ways (SRV records and Nginx load-balancing) are reasonable, and your choice will depend on your personal preferences. I caricature the options as:
arboristal.com
taking over the world, or at least moving to a bigger machine someday. I'm not scared of learning a new tool. What's a zone file?"I was having a similar problem, however my program would crash when I tried to set the text. I was attempting to set the text value from within a class that extends AsyncTask, and that was what was causing the problem.
To resolve it, I moved my setText to the onPostExecute method
protected void onPostExecute(Void result) {
super.onPostExecute(result);
TextView text = (TextView) findViewById(R.id.errorsToday);
text.setText("new string value");
}
Piping to another process (Although this WON'T accomplish what you said you are trying to do):
command1 | command2
This will send the output of command1 as the input of command2
-exec
on a find
(this will do what you are wanting to do -- but is specific to find
)
find . -name '*.foo' -exec cat {} \;
(Everything between find
and -exec
are the find predicates you were already using. {}
will substitute the particular file you found into the command (cat {}
in this case); the \;
is to end the -exec
command.)
send output of one process as command line arguments to another process
command2 `command1`
for example:
cat `find . -name '*.foo' -print`
(Note these are BACK-QUOTES not regular quotes (under the tilde ~ on my keyboard).)
This will send the output of command1
into command2
as command line arguments. Note that file names containing spaces (newlines, etc) will be broken into separate arguments, though.
For what its worth if you have a more than a handful of projects, which I do, use:
gcloud init
This will list all your projects and give you the option to change current project settings, add a new project configuration or switch:
Pick configuration to use:
[1] Re-initialize this configuration [esqimo-preprod] with new settings
[2] Create a new configuration
[3] Switch to and re-initialize existing configuration: [default]
[4] Switch to and re-initialize existing configuration: [project 1]
[5] Switch to and re-initialize existing configuration: [project 2]
Please enter your numeric choice:
It will always ask you to login and display options for different google accounts that you may have.
Given that I manage multiple organisations and projects this approach lets' me to simply switch between them.
In kruskal Algorithm we have number of edges and number of vertices on a given graph but on each edge we have some value or weight on behalf of which we can prepare a new graph which must be not cyclic or not close from any side For Example
graph like this _____________ | | | | | | |__________| | Give name to any vertex a,b,c,d,e,f .
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
set()
is exactly what you want. O(1) lookups, and smaller than a dict.
Another workaround is to sort the spreadsheet with the character data at the top, thereby causing Excel to see the column as string, and importing everything as such.
1) Nowadays, pretty much never. If it's a good idea to inline a function, the compiler will do it without your help.
2) Always. See #1.
(Edited to reflect that you broke your question into two questions...)
Better to declare it styleable, so you can change its property from xml:
private boolean swipeable;
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPager);
try {
swipeable = a.getBoolean(R.styleable.MyViewPager_swipeable, true);
} finally {
a.recycle();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return swipeable ? super.onInterceptTouchEvent(event) : false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return swipeable ? super.onTouchEvent(event) : false;
}
And in your values/attr.xml:
<declare-styleable name="MyViewPager">
<attr name="swipeable" format="boolean" />
</declare-styleable>
so that you can use it in you layout xml:
<mypackage.MyViewPager
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:swipeable="false" />
Of course, you can still have a get/set property.
The most direct way is sum(numbers == x)
.
numbers == x
creates a logical vector which is TRUE at every location that x occurs, and when sum
ing, the logical vector is coerced to numeric which converts TRUE to 1 and FALSE to 0.
However, note that for floating point numbers it's better to use something like: sum(abs(numbers - x) < 1e-6)
.
No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor
Snapshot() : x(0), y(0) {
}
This ensures that all uses of Snapshot will have initialized values.
Assuming that you have your data in a 2d array, this should work:
import numpy
import pylab
xy = numpy.zeros((2, 1000))
xy[0] = range(1000)
xy[1] = range(1000)
colors = [int(i % 23) for i in xy[0]]
pylab.scatter(xy[0], xy[1], c=colors)
pylab.show()
You can also set a cmap
attribute to control which colors will appear through use of a colormap; i.e. replace the pylab.scatter
line with:
pylab.scatter(xy[0], xy[1], c=colors, cmap=pylab.cm.cool)
A list of color maps can be found here
It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.
In general, I suggest calling a function on ng-click like so:
<a ng-click="navigateToPath()">click me</a>
obj.val1
& obj.val2
should be available on your controller's $scope, you dont need to pass those into a function from the markup.
then, in your controller:
$scope.navigateToPath = function(){
var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
$location.path(path)
}
Here Is my code For Zip the folders and its sub folders and its files and make it downloadable in zip Format
function zip()
{
$source='path/folder'// Path To the folder;
$destination='path/folder/abc.zip'// Path to the file and file name ;
$include_dir = false;
$archive = 'abc.zip'// File Name ;
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
if (file_exists($destination)) {
unlink ($destination);
}
$zip = new ZipArchive;
if (!$zip->open($archive, ZipArchive::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
if ($include_dir) {
$arr = explode("/",$source);
$maindir = $arr[count($arr)- 1];
$source = "";
for ($i=0; $i < count($arr) - 1; $i++) {
$source .= '/' . $arr[$i];
}
$source = substr($source, 1);
$zip->addEmptyDir($maindir);
}
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$archive);
header('Content-Length: '.filesize($archive));
readfile($archive);
unlink($archive);
}
If Any Issue With the Code Let Me know.
You can use triggers.
Also check this introduction guide to triggers.
Maybe:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
Alternatively, you can just use,
<li v-for="catalog, key in catalogs">this is index {{++key}}</li>
This is working just fine.
I think the equivalent is Int64
The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.
(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)
If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.
The specific code I used to fix this was:
renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
return (
<View style={styles.separator} key={`${sectionID}-${rowID}`}/>
)
}
I'm including the specific code because you need the keys to be unique--even for separators. If you do something similar e.g., if you set this to a constant, you will just get another annoying error about reuse of keys. If you don't know JSX, constructing the callback to JS to execute the various parts can be quite a pain.
And on the ListView, obviously attaching this:
<ListView
style={styles.listview}
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
renderSeparator={this.renderSeparator.bind(this)}
renderSectionHeader={this.renderSectionHeader.bind(this)}/>
Credit to coldbuffet and Nader Dabit who pointed me down this path.
Here is good example of the CRUD operation using fetch API:
“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW
Here is the sample code I tried for PATCH or PUT
function update(id, data){
fetch(apiUrl + "/" + id, {
method: 'PATCH',
body: JSON.stringify({
data
})
}).then((response) => {
response.json().then((response) => {
console.log(response);
})
}).catch(err => {
console.error(err)
})
For DELETE:
function remove(id){
fetch(apiUrl + "/" + id, {
method: 'DELETE'
}).then(() => {
console.log('removed');
}).catch(err => {
console.error(err)
});
For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.
In my case it was looking after .babelrc
file, and it should contain something like this:
{
"presets": ["es2015-node5", "stage-3"],
"plugins": []
}
As others have pointed out, thread safety means that a piece of code will work without errors if it's used by more than one thread at once.
It's worth being aware that this sometimes comes at a cost, of computer time and more complex coding, so it isn't always desirable. If a class can be safely used on only one thread, it may be better to do so.
For example, Java has two classes that are almost equivalent, StringBuffer
and StringBuilder
. The difference is that StringBuffer
is thread-safe, so a single instance of a StringBuffer
may be used by multiple threads at once. StringBuilder
is not thread-safe, and is designed as a higher-performance replacement for those cases (the vast majority) when the String is built by only one thread.
In this context, "attribute" simply means a data member of an object.
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
You can use:
<head>
<meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1.0, user-scalable=no" />
...
</head>
But please note that with Android 4.4 the property target-densitydpi is no longer supported. So for Android 4.4 and later the following is suggested as best practice:
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
import gzip
f = gzip.open('file.txt.gz', 'rb')
file_content = f.read()
f.close()
It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:
* { margin: 0, padding: 0 }
This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.
In my case the problem was caused by version inconsistency:
Build tools 25
compileSdk 24
targetSdk 24
Support library 24
The solution was simple: Make everything version 25
Mac Users, let me save you the time:
The method version
on ionic
object returns the current version in string
format.
You can with flexbox:
ul.list {
padding: 0;
list-style: none;
display: flex;
align-items: stretch;
justify-items: center;
flex-wrap: wrap;
justify-content: center;
}
li {
width: 100px;
padding: .5rem;
border-radius: 1rem;
background: yellow;
margin: 0 5px;
}
_x000D_
<ul class="list">
<li>title 1</li>
<li>title 2<br>new line</li>
<li>title 3<br>new<br>line</li>
</ul>
_x000D_
Another way to do it could be by creating an alias. For example in terminal write:
alias printhello='python /home/hello_world.py'
Writing printhello
will run hello_world.py, but this is only temporary.
To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:
gedit ~/.bashrc
The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template
. However if your directive takes advantage of templateUrl
his answer will not work. Here is what worked for me:
.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: "app/views/modal.html",
link: function (scope, element, attrs) {
scope.modalTitle = attrs.modaltitle;
scope.modalContentDirective = attrs.modalcontentdirective;
},
controller: function ($scope, $element, $attrs) {
if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
var el = $compile($attrs.modalcontentdirective)($scope);
$timeout(function () {
$scope.$digest();
$element.find('.modal-body').append(el);
}, 0);
}
}
}
}]);
It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.
Following Traveling Tech Guy's answer, which already awesome, we can create a plugin and attach it to mongoose once we initialise it so that .upsert()
will be available on all models.
plugins.js
export default (schema, options) => {
schema.statics.upsert = async function(query, data) {
let record = await this.findOne(query)
if (!record) {
record = new this(data)
} else {
Object.keys(data).forEach(k => {
record[k] = data[k]
})
}
return await record.save()
}
}
db.js
import mongoose from 'mongoose'
import Plugins from './plugins'
mongoose.connect({ ... })
mongoose.plugin(Plugins)
export default mongoose
Then you can do something like User.upsert({ _id: 1 }, { foo: 'bar' })
or YouModel.upsert({ bar: 'foo' }, { value: 1 })
whenever you want.
The answer from ks1322 helped me to identify the issue while using docker-compose exec
:
If you omit the -T
flag, docker-compose exec
add a special character that break output, we see b
instead of 1b
:
$ test=$(/usr/local/bin/docker-compose exec db bash -c "echo 1")
$ echo "${test}b"
b
echo "${test}" | cat -vte
1^M$
With -T
flag, docker-compose exec
works as expected:
$ test=$(/usr/local/bin/docker-compose exec -T db bash -c "echo 1")
$ echo "${test}b"
1b
You can also use the Get-Counter cmdlet (PowerShell 2.0):
Get-Counter '\Memory\Available MBytes'
Get-Counter '\Processor(_Total)\% Processor Time'
To get a list of memory counters:
Get-Counter -ListSet *memory* | Select-Object -ExpandProperty Counter
Dragon NaturallySpeaking seems to support MP3 input.
If you want an open source version (I think there are some Asterisk integration projects based on this one).
Your using
statements appear to be correct.
Are you, perhaps, missing the assembly reference to System.configuration.dll
?
Right click the "References" folder in your project and click on "Add Reference..."
The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.
Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).
The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.
Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.
<<
Getting started example:
xml file:
<inventory>
<book year="2000">
<title>Snow Crash</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553380958</isbn>
<price>14.95</price>
</book>
<book year="2005">
<title>Burning Tower</title>
<author>Larry Niven</author>
<author>Jerry Pournelle</author>
<publisher>Pocket</publisher>
<isbn>0743416910</isbn>
<price>5.99</price>
</book>
<book year="1995">
<title>Zodiac</title>
<author>Neal Stephenson</author>
<publisher>Spectra</publisher>
<isbn>0553573862</isbn>
<price>7.50</price>
</book>
<!-- more books... -->
</inventory>
Java code:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));
// normalize text representation
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList listOfBooks = doc.getElementsByTagName("book");
int totalBooks = listOfBooks.getLength();
System.out.println("Total no of books : " + totalBooks);
for(int i=0; i<listOfBooks.getLength() ; i++) {
Node firstBookNode = listOfBooks.item(i);
if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstElement = (Element)firstBookNode;
System.out.println("Year :"+firstElement.getAttribute("year"));
//-------
NodeList firstNameList = firstElement.getElementsByTagName("title");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("title : " + ((Node)textFNList.item(0)).getNodeValue().trim());
}
}//end of for loop with s var
} catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
} catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
} catch (Throwable t) {
t.printStackTrace ();
}
You can do this another way by checking the array length
<div *ngIf="stuff.length>0">
<div *ngFor="let thing of stuff">
{{log(thing)}}
<span>{{thing.name}}</span>
</div>
</div>
Use both @Deprecated
annotation and the @deprecated
JavaDoc tag.
The @deprecated
JavaDoc tag is used for documentation purposes.
The @Deprecated
annotation instructs the compiler that the method is deprecated. Here is what it says in Sun/Oracles document on the subject:
Using the
@Deprecated
annotation to deprecate a class, method, or field ensures that all compilers will issue warnings when code uses that program element. In contrast, there is no guarantee that all compilers will always issue warnings based on the@deprecated
Javadoc tag, though the Sun compilers currently do so. Other compilers may not issue such warnings. Thus, using the@Deprecated
annotation to generate warnings is more portable that relying on the@deprecated
Javadoc tag.
You can find the full document at How and When to Deprecate APIs
Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.
Delegate.Invoke() synchronously calls the delegate in the same thread.
Rotate 90 clockwise:
ffmpeg -i in.mov -vf "transpose=1" out.mov
For the transpose parameter you can pass:
0 = 90CounterCLockwise and Vertical Flip (default)
1 = 90Clockwise
2 = 90CounterClockwise
3 = 90Clockwise and Vertical Flip
Use -vf "transpose=2,transpose=2"
for 180 degrees.
Make sure you use a recent ffmpeg version from here (a static build will work fine).
Note that this will re-encode the audio and video parts. You can usually copy the audio without touching it, by using -c:a copy
. To change the video quality, set the bitrate (for example with -b:v 1M
) or have a look at the H.264 encoding guide if you want VBR options.
A solution is also to use this convenience script.
anyone who says activex is less secure then NPAPI is crazy. They both allow the exact same access. Yes I've written both. The only reason people think activeX is insecure is because 10+ years ago IE had default settings that allowed a remote site to auto download the plugin.
GregorianCalendar date;
CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date);
Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show();
If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
In addition to the previous answers, if you use the tool pgAdmin III you can set the time zone as follows:
To move a table from database A to database B at your local setup, use the following command:
pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2
This is not specifically for eclipse, but the way I got around this was by creating a symbolic link to my maven repository and pointing it to something like "C:\R". Then I added the following to my settings.xml file:
<localRepository>C:\R</localRepository>
The maven repository path was contributing to the length problems in my windows machine.
In line with @Qwertie's suggestion, but going further on the lazy side, you could just pretend that each byte is a ISO-8859-1 character. For the uninitiated, ISO-8859-1 is a single-byte encoding that matches the first 256 code points of Unicode.
So @Ash's answer is actually redeemable with a charset:
byte[] args2 = getByteArry();
String byteStr = new String(args2, Charset.forName("ISO-8859-1"));
This encoding has the same readability as BAIS, with the advantage that it is processed faster than either BAIS or base64 as less branching is required. It might look like the JSON parser is doing a bit more, but it's fine because dealing with non-ASCII by escaping or by UTF-8 is part of a JSON parser's job anyways. It could map better to some formats like MessagePack with a profile.
Space-wise however, it is usually a loss, as nobody would be using UTF-16 for JSON. With UTF-8 each non-ASCII byte would occupy 2 bytes, while BAIS uses (2+4n + r?(r+1):0) bytes for every run of 3n+r such bytes (r is the remainder).
They've now deprecated click(), so best to go with on('click')
<div class="content">
Counter-Strike 1.6 Steam
<img src="images/CSsteam.png">
<a href="#">Koupit</a>
</div>
/*Use this css*/
content {
width: 182px; /*328 co je 1/3 - 20margin left*/
height: 121px;
line-height: 20px;
margin-top: 0px;
margin-left: 9px;
margin-right:0px;
display:inline-block;
position:relative;
}
content a{
display:inline-block;
padding:10px;
position:absolute;
bottom:10px;
right:10px;
}
For installing Hadoop it is soooooo much easier installing the free version from Cloudera. It comes with a nice GUI that makes it simple to add nodes, there is no compiling or stuffing around with dependencies, it comes with stuff like hive, pig etc.
http://www.cloudera.com/content/support/en/downloads.html
Steps are: 1) Download 2) Run it 3) Go to web GUI (1.2.3.4:7180) 4) Add extra nodes in the web gui (do NOT install the cloudera software on other nodes, it does it all for you) 5) Within the web GUI go to Home, click Hue and Hue Web UI. This gives you access to Hive, Pig, Sqoop etc.
As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:
1) Login as sysdba (sqlplus / as sysdba)
2) SHUTDOWN IMMEDIATE;
3) STARTUP UPGRADE;
4) ALTER SYSTEM SET max_string_size=extended;
5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql
6) SHUTDOWN IMMEDIATE;
7) STARTUP;
you can use lst.pop()
or del lst[-1]
pop()
removes and returns the item, in case you don't want have a return use del
There are few mistakes you are doing:
addRow
methodsplice
method to remove an element from an array at particular index.my-item
component, where this can be modified.You can see working code here.
addRow(){
this.rows.push({description: '', unitprice: '' , code: ''}); // what to push unto the rows array?
},
removeRow(index){
this. itemList.splice(index, 1)
}
Read carefully about the reason.
"Failed to resolve version for org.apache.maven.archetypes:maven-archetype- webapp:pom:RELEASE: Could not find metadata org.apache.maven.archetypes:maven-archetype- webapp/maven-metadata.xml in local"
So all you need to do is download the maven-metadata.xml to your {HOME}.m2\repository
That's it.
TL;DR
headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
headroom_by_DOM = $('#id')[0].getBoundingClientRect().top; // if no iframe
.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.
Centering content has so many avenues that it can't really be explored in a single answer. If you would like to explore them, CSS Zen Garden is an enjoyable-if-old resource exploring the many, many ways to layout content in a way even old browsers will tolerate.
The correct way, if you don't have any mitigating requirements, is to just apply margin: auto
to the sides, and a width
. If your page has no content that needs to go outside those margins, just apply it to the body:
body {
padding: 0;
margin: 15px auto;
width: 500px;
}
https://jsfiddle.net/b9chris/62wgq8nk/
So here we've got a 500px wide set of content centered at all* sizes. The padding 0 is to deal with some browsers that like to apply some default padding and throw us off a bit. In the example I do wrap the content in an article
tag to be nice to Screen Readers, Pocket, etc so for example the blind can jump past the nav you likely have (which should be in nav
) and straight to the content.
I say all* because below 500px this will mess up - we're not being Responsive. To get Responsive, you could just use Bootstrap etc, but building it yourself you use a Media Query like:
body {
padding: 0;
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
Note that this is SCSS/SASS syntax - if you're using plain CSS, it's inverted:
body {
padding: 0;
margin: 15px;
}
@media (min-width: 500px) {
body {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/6/
It's common however to want to center just one chunk of a page, so let's apply this to only the article tag in a final example.
body {
padding: 0;
margin: 0;
}
nav {
width: 100%;
box-sizing: border-box;
padding: 15px;
}
article {
margin: 15px;
@media (min-width: 500px) {
margin: 15px auto;
width: 500px;
}
}
https://jsfiddle.net/b9chris/62wgq8nk/17/
Note that this final example also uses CSS Flexbox in the nav, which is also one of the newer ways you could center things. So, that's fun.
But, there are special circumstances where you need to use other approaches to center content, and each of those is probably worth its own question (many of them already asked and answered here on this site).
I ran into this as well, but in the case where I wanted to avoid the extra error messages while keeping the range provided. An option is also to subset the data prior to setting the range, so that the range can be kept however you like without triggering warnings.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# Setting limits with scale_y_continous (or ylim) and subsetting accordingly
## avoid warning messages about removing data
ggplot(data= subset(mtcars, hp<=300 & hp >= 100), aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(100,300))
I have found that using cabs(double)
, cabsf(float)
, cabsl(long double)
, __cabsf(float)
, __cabs(double)
, __cabsf(long double)
is the solution
<whatever onclick="doStuff();" onmouseover="in()" onmouseout="out()" />
onclick, onmouseover, onmouseout, etc. events are actually bad for performance (in Internet Explorer mainly, go figure). If you code using Visual Studio, when you run a page with these, every single one of these will create a separate SCRIPT block taking up memory, and thus slowing down performance.
Not to mention you should have a separation of concerns: JavaScript and layouts should be separated!
It is always better to create evenHandlers for any of these events, one event can capture hundreds/thousands of items, instead of creating thousands of separate script blocks for each one!
(Also, everything everyone else is saying.)
Maybe try this
Select cust.*
From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null
Just set the environment variable to the EXACT path to gcc.exe like this:
C:\Program Files (x86)\CodeBlocks\MinGW\bin\gcc.exe
The -D
properties will not be reliable propagated from the surefire-pluging to your test (I do not know why it works with eclipse). When using maven on the command line use the argLine property to wrap your property. This will pass them to your test
mvn -DargLine="-DWSNSHELL_HOME=conf" test
Use System.getProperty
to read the value in your code. Have a look to this post about the difference of System.getenv
and Sytem.getProperty
.
Yet another functional solution for Python 2:
from functools import partial
map(partial(map, int), T1)
Python 3 will be a little bit messy though:
list(map(list, map(partial(map, int), T1)))
we can fix this with a wrapper
def oldmap(f, iterable):
return list(map(f, iterable))
oldmap(partial(oldmap, int), T1)
If we use SQL Server >= 2005, then we can solve the task with one select only:
declare @t table (
Id int ,
Section int,
Moment date
);
insert into @t values
( 1 , 1 , '2014-01-01'),
( 2 , 1 , '2014-01-02'),
( 3 , 1 , '2014-01-03'),
( 4 , 1 , '2014-01-04'),
( 5 , 1 , '2014-01-05'),
( 6 , 2 , '2014-02-06'),
( 7 , 2 , '2014-02-07'),
( 8 , 2 , '2014-02-08'),
( 9 , 2 , '2014-02-09'),
( 10 , 2 , '2014-02-10'),
( 11 , 3 , '2014-03-11'),
( 12 , 3 , '2014-03-12'),
( 13 , 3 , '2014-03-13'),
( 14 , 3 , '2014-03-14'),
( 15 , 3 , '2014-03-15');
-- TWO earliest records in each Section
select top 1 with ties
Id, Section, Moment
from
@t
order by
case
when row_number() over(partition by Section order by Moment) <= 2
then 0
else 1
end;
-- THREE earliest records in each Section
select top 1 with ties
Id, Section, Moment
from
@t
order by
case
when row_number() over(partition by Section order by Moment) <= 3
then 0
else 1
end;
-- three LATEST records in each Section
select top 1 with ties
Id, Section, Moment
from
@t
order by
case
when row_number() over(partition by Section order by Moment desc) <= 3
then 0
else 1
end;
Using has a gotcha, while it is by far the fastest method, it also expects all of your filenames to be lowercase.
spl_autoload_extensions(".php");
spl_autoload_register();
For example:
A file containing the class SomeSuperClass would need to be named somesuperclass.php, this is a gotcha when using a case sensitive filesystem like Linux, if your file is named SomeSuperClass.php but not a problem under Windows.
Using __autoload in your code may still work with current versions of PHP but expect this feature to become deprecated and finally removed in the future.
So what options are left:
This version will work with PHP 5.3 and above and allows for filenames SomeSuperClass.php and somesuperclass.php. If your using 5.3.2 and above, this autoloader will work even faster.
<?php
if ( function_exists ( 'stream_resolve_include_path' ) == false ) {
function stream_resolve_include_path ( $filename ) {
$paths = explode ( PATH_SEPARATOR, get_include_path () );
foreach ( $paths as $path ) {
$path = realpath ( $path . PATH_SEPARATOR . $filename );
if ( $path ) {
return $path;
}
}
return false;
}
}
spl_autoload_register ( function ( $className, $fileExtensions = null ) {
$className = str_replace ( '_', '/', $className );
$className = str_replace ( '\\', '/', $className );
$file = stream_resolve_include_path ( $className . '.php' );
if ( $file === false ) {
$file = stream_resolve_include_path ( strtolower ( $className . '.php' ) );
}
if ( $file !== false ) {
include $file;
return true;
}
return false;
});
Yes. As the session ID is either transported over the URL (document.location.href
) or via a cookie (document.cookie
), you could check both for the presence of a session ID.
I've tried a few solutions here and didn't find the one that writes into file and into console at the same time. So here is what I did (based on this answer)
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
def write(self, message):
with open ("logfile.log", "a", encoding = 'utf-8') as self.log:
self.log.write(message)
self.terminal.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
This solution uses more computing power, but reliably saves all of the data from stdout into logger file and uses less memeory. For my needs I've added time stamp into self.log.write(message) aswell. Works great.
You need to do a few things:
-- 1. Remove constraint and drop column
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TABLE_NAME'
AND COLUMN_NAME = N'LOWER_LIMIT')
BEGIN
DECLARE @sql NVARCHAR(MAX)
WHILE 1=1
BEGIN
SELECT TOP 1 @sql = N'alter table [TABLE_NAME] drop constraint ['+dc.name+N']'
FROM sys.default_constraints dc
JOIN sys.columns c
ON c.default_object_id = dc.object_id
WHERE dc.parent_object_id = OBJECT_ID('[TABLE_NAME]') AND c.name = N'LOWER_LIMIT'
IF @@ROWCOUNT = 0
BEGIN
PRINT 'DELETED Constraint on column LOWER_LIMIT'
BREAK
END
EXEC (@sql)
END;
ALTER TABLE TABLE_NAME DROP COLUMN LOWER_LIMIT;
PRINT 'DELETED column LOWER_LIMIT'
END
ELSE
PRINT 'Column LOWER_LIMIT does not exist'
GO
The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.
Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :
Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)
Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)
public String CleanStringToLettersNumbers(String data)
{
var result = String.Empty;
foreach (var item in data)
{
var c = '_';
if ((int)item >= 97 && (int)item <= 122 ||
(int)item >= 65 && (int)item <= 90 ||
(int)item >= 48 && (int)item <= 57 ||
(int)item == 32)
{
c = item;
}
result = result + c;
}
return result;
}
Regardless of following a naming convention that avoids using reserved words, Microsoft does add new reserved words. Using brackets allows your code to be upgraded to a new SQL Server version, without first needing to edit Microsoft's newly reserved words out of your client code. That editing can be a significant concern. It may cause your project to be prematurely retired....
Brackets can also be useful when you want to Replace All in a script. If your batch contains a variable named @String and a column named [String], you can rename the column to [NewString], without renaming @String to @NewString.
This line of yours:
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
Requires an @
symbol before %
like this:
<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>
Also you could use
${pageContext.request.requestURI}
I think there is no way to find out whether a dynamic
variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.
So you should actually try to access the member and catch an exception, if it fails:
dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();
try
{
var x = myVariable.MyProperty;
// do stuff with x
}
catch (RuntimeBinderException)
{
// MyProperty doesn't exist
}
See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS
filter when you do.
Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.
I ran into the same issue and noticed that I had mixed up the casing while checking out the branch. I checked out branchName
instead of BranchName
and when I tried to push to remote, I got the same error.
The fix:
git push --set-upstream origin BranchName
By setting upstream to the correct name, the correct branch was updated on github and I was then able to checkout the correct branch name with
git checkout BranchName
And it should be up to date with your last push.
In C++11, use std::to_string
if you can accept the default format (%f
).
storedCorrect[count]= "(" + std::to_string(c1) + ", " + std::to_string(c2) + ")";
The simplest way would be to directly subtract the date objects from one another.
For example:
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5
is the scientific notation for 60*60*1000
, dividing by which converts the milliseconds difference into hours.
I found IE11 is giving more than one user agent strings in different environments.
Instead of relying on MSIE
, and other approaches, It's better to rely on Trident
version
const isIE11 = userAgent => userAgent.match(/Trident\/([\d.]+)/) ? +userAgent.match(/Trident\/([\d.]+)/)[1] >= 7;
Hope this helps :)
Since Nick's answer is deprecated by now and Rafael's comment is really useful, I want to add this as an Answer. If you want to change all factor
columns to character
use mutate_if
:
dat %>% mutate_if(is.factor, as.character)
Also other functions are allowed. I for instance used iconv
to change the encoding of all character
columns:
dat %>% mutate_if(is.character, function(x){iconv(x, to = "ASCII//TRANSLIT")})
or to substitute all NA
by 0 in numeric columns:
dat %>% mutate_if(is.numeric, function(x){ifelse(is.na(x), 0, x)})
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.
I know this is old, but I'm gonna chime in anyway because it may be useful to someone. If you can still see the file in Finder, then click on the file in your project and delete it, selecting "remove references" and not "move to trash".
Once the reference is removed, drag and drop the file from finder into your project again and it should sort itself out.
After trying to add the path using:
pip show
on command prompt and using
sys.path.insert(0, "/home/myname/pythonfiles")
and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.
I simply copied the module that wasn't found from the path "Mine was in
C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages
so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'
Missing a semicolon
if [ -a myApp ];
then
rm myApp
fi
However, I assume you are checking for existence before deletion to prevent an error message. If so, you can just use rm -f myApp
which "forces" delete, i.e. doesn't error out if the file didn't exist.
Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.
Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).
Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.
A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:
public class MyClass
{
public string[] GetMyData(string fileName)
{
string[] data = FileUtil.ReadDataFromFile(fileName);
return data;
}
}
Instead of trying to mock FileUtil.ReadDataFromFile
, you could wrap it in a protected virtual
method, like this:
public class MyClass
{
public string[] GetMyData(string fileName)
{
string[] data = GetDataFromFile(fileName);
return data;
}
protected virtual string[] GetDataFromFile(string fileName)
{
return FileUtil.ReadDataFromFile(fileName);
}
}
Then, in your unit test, derive from MyClass
and call it TestableMyClass
. Then you can override the GetDataFromFile
method to return your own test data.
Hope that helps.
Just append :after
to your #alertlist li:hover
selector the same way you do with your #alertlist li.selected
selector:
#alertlist li.selected:after, #alertlist li:hover:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}
Click in the grid so it has focus.
Ctrl+End
This will force the rest of the records back into the grid.
All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/
here I'm providing solution to setup terraform enviroment variable in windows to beginners.
Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\
and Save it.
If some one is still finding difficulties, i have made a video on this
https://www.youtube.com/watch?v=tbLAHKhjjI4
Because the new version of Apple does not support bash shell so i have explained in details how do we set variables in 2020.
Much simpler approach is to use OdeToCode.UseNodeModules Nuget package. I just tested it with .Net Core 3.0. All you need to do is add the package to the solution and reference it in the Configure method of the Startup class:
app.UseNodeModules();
I learned about it from the excellent Building a Web App with ASP.NET Core, MVC, Entity Framework Core, Bootstrap, and Angular Pluralsight course by Shawn Wildermuth.
For Set you can use TreeSet. TreeSet orders it's elements on the basis of a natural ordering or any sorting order passed to the Comparable for that particular object. For map use TreeMap. TreeMap provides the sorting over keys. To add an object as a key to the TreeMap that class should implement comparable interface which in turn forces to implement compare to() method which contains the definition of the sorting order. http://techmastertutorial.in/java-collection-impl.html
Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.
'<option value="' + col + '"'+ (col === "screwdriver" ? " selected " : "") +'>Very roomy</option>';
For Development purpose you can just export the required tables data into a single HTML and make a direct search on it.
You need to run the script like this:
groovy helloworld.groovy
If you want to use jQuery's validate
you can by creating this method:
$.validator.addMethod('filesize', function(value, element, param) {
// param = size (en bytes)
// element = element to validate (<input>)
// value = value of the element (file name)
return this.optional(element) || (element.files[0].size <= param)
});
You would use it:
$('#formid').validate({
rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576 }},
messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});
This is the solution which can avoid using function:
alias addone='{ num=$(cat -); echo "input: $num"; echo "result:$(($num+1))"; }<<<'
test result
addone 200
input: 200
result:201
There is a case for either solution, depending on what you want to do conditional on the existence of the environment variable.
When you want to take different actions purely based on the existence of the environment variable, without caring for its value, the first solution is the best practice. It succinctly describes what you test for: is 'FOO' in the list of environment variables.
if 'KITTEN_ALLERGY' in os.environ:
buy_puppy()
else:
buy_kitten()
When you want to set a default value if the value is not defined in the environment variables the second solution is actually useful, though not in the form you wrote it:
server = os.getenv('MY_CAT_STREAMS', 'youtube.com')
or perhaps
server = os.environ.get('MY_CAT_STREAMS', 'youtube.com')
Note that if you have several options for your application you might want to look into ChainMap
, which allows to merge multiple dicts based on keys. There is an example of this in the ChainMap
documentation:
[...]
combined = ChainMap(command_line_args, os.environ, defaults)
You could also Stub Consecutive Calls (#10 in 2.8.9 api). In this case, you would use multiple thenReturn calls or one thenReturn call with multiple parameters (varargs).
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
public class TestClass {
private Foo mockFoo;
@Before
public void setup() {
setupFoo();
}
@Test
public void testFoo() {
TestObject testObj = new TestObject(mockFoo);
assertEquals(0, testObj.bar());
assertEquals(1, testObj.bar());
assertEquals(-1, testObj.bar());
assertEquals(-1, testObj.bar());
}
private void setupFoo() {
mockFoo = mock(Foo.class);
when(mockFoo.someMethod())
.thenReturn(0)
.thenReturn(1)
.thenReturn(-1); //any subsequent call will return -1
// Or a bit shorter with varargs:
when(mockFoo.someMethod())
.thenReturn(0, 1, -1); //any subsequent call will return -1
}
}
You need to use a dictionary and reverse of that dictionary. It means you need another data structure. If you are in python 3, use enum
module but if you are using python 2.7 use enum34
which is back ported for python 2.
Example:
from enum import Enum
class Color(Enum):
red = 1
green = 2
blue = 3
>>> print(Color.red)
Color.red
>>> print(repr(Color.red))
<color.red: 1="">
>>> type(Color.red)
<enum 'color'="">
>>> isinstance(Color.green, Color)
True
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1
By default flush mode is AUTO which means that: "The Session is sometimes flushed before query execution in order to ensure that queries never return stale state", but most of the time session is flushed when you commit your changes. Manual calling of the flush method is usefull when you use FlushMode=MANUAL or you want to do some kind of optimization. But I have never done this so I can't give you practical advice.
To slow down your game, use pygame.clock.tick(10)
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
Use ExitCode if your main has a void return signature, otherwise you need to "set" it by the value you return.
If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment. If Main does not return void, this property is ignored. The initial value of this property is zero.
As I said in your previous question, there is no need to base64 encode the string, it will only make the program slower. Just use the repr
>>> with open("images/image.gif", "rb") as fin:
... image_data=fin.read()
...
>>> with open("image.py","wb") as fout:
... fout.write("image_data="+repr(image_data))
...
Now the image is stored as a variable called image_data
in a file called image.py
Start a fresh interpreter and import the image_data
>>> from image import image_data
>>>
I've created an NPM module, which allows you to share locally-stored data across domains: https://www.npmjs.com/package/cookie-toss
By using an iframe hosted on Domain A, you can store all of your user data on Domain A, and reference that data by posting requests to the Domain A iframe.
Thus, Domains B, C, etc. can inject the iframe and post requests to it to store and access the desired data. Domain A becomes the hub for all shared data.
With a domain whitelist inside of Domain A, you can ensure only your dependent sites can access the data on Domain A.
The trick is to have the code inside of the iframe on Domain A which is able to recognize which data is being requested. The README in the above NPM module goes more in depth into the procedure.
Hope this helps!