There is no such thing as importing in MS SQL. I understand what you mean. It is so simple. Whenever you get/have a something.SQL file, you should just double click and it will directly open in your MS SQL Studio.
BEWARE! This answer contains a severe SQL injection vulnerability. Do NOT use the code samples as presented here, without making sure that any external input is sanitized.
$ids = join("','",$galleries);
$sql = "SELECT * FROM galleries WHERE id IN ('$ids')";
I found both, x64 and x86 version 6.12.0002.633 here:
http://rxwen.blogspot.de/2010/04/standalone-windbg-v6120002633.html
As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:
theme(plot.title = element_text(hjust = 0.5))
However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with
theme_update(plot.title = element_text(hjust = 0.5))
Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5)
as their default:
theme_update(plot.title = element_text(hjust = 0.5))
ggplot() + ggtitle("Default is now set to centered")
To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with
theme_set(theme_gray())
The code works for me. (after adding missing except
clause / import
statements)
Did you put \
in the original code?
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
+ stock + '/chartdata;type=quote;range=5d/csv'
If you omit it, it could be a cause of the exception:
>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'
BTW, string(e)
should be str(e)
.
This will work:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
If you are using STS and your server is Pivotal Just double click on the server and go to >Modules tab >display Configure the Web Modules on this server.>you can just remove modules and run once again.
You are trying to read xls
with explicit implementation poi classes for xlsx
.
G:\Selenium Jar Files\TestData\Data.xls
Either use HSSFWorkbook
and HSSFSheet
classes or make your implementation more generic by using shared interfaces, like;
Change:
XSSFWorkbook workbook = new XSSFWorkbook(file);
To:
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);
And Change:
XSSFSheet sheet = workbook.getSheetAt(0);
To:
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
Use a SQL function (I'm the author):
Usage:
select fn_gen_inserts('select * from tablename', 'p_new_owner_name', 'p_new_table_name')
from dual;
where:
p_sql – dynamic query which will be used to export metadata rows
p_new_owner_name – owner name which will be used for generated INSERT
p_new_table_name – table name which will be used for generated INSERT
p_sql in this sample is 'select * from tablename'
You can find original source code here:
Ashish Kumar's script generates individually usable insert statements instead of a SQL block, but supports fewer datatypes.
After trying everything, Yowsup library worked for me. The bug that I was facing was recently fixed. Anyone trying to do something with Whatsapp should try it.
Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"
Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.
In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.
So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.
Since you're transferring data in xml, you could also (un)marshal directly from/to pojos.
There's an example (and more info) in the jersey user guide, which I copy here:
POJO with JAXB annotations:
@XmlRootElement
public class Planet {
public int id;
public String name;
public double radius;
}
Resource:
@Path("planet")
public class Resource {
@GET
@Produces(MediaType.APPLICATION_XML)
public Planet getPlanet() {
Planet p = new Planet();
p.id = 1;
p.name = "Earth";
p.radius = 1.0;
return p;
}
@POST
@Consumes(MediaType.APPLICATION_XML)
public void setPlanet(Planet p) {
System.out.println("setPlanet " + p.name);
}
}
The xml that gets produced/consumed:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<planet>
<id>1</id>
<name>Earth</name>
<radius>1.0</radius>
</planet>
Check https://pypi.python.org/pypi/tensorflow to see which packages are available.
As of this writing, they don't provide a source package, so if there's no prebuilt one for your platform, this error occurs. If you add -v
to the pip
command line, you'll see it iterating over the packages that are available at PyPI and discarding them for being incompatible.
You need to either find a prebuilt package somewhere else, or compile tensorflow
yourself from its sources by instructions at https://www.tensorflow.org/install/install_sources .
They have a good reason for not building for some platforms though:
win32
package is missing because TensorFlow's dependency, Bazel, only supports win64
.win64
, only 3.5+ is supported because earlier versions are compiled with compilers without C++11 support.Two reasons:
delete
it later, or it will cause a memory leak.You can try Dummynet, it can simulates queue and bandwidth limitations, delays, packet losses, and multipath effects
This question is very, very, very old, but as a trick in the future, I recommend something like this:
.element{
box-shadow: 0px 0px 10px #232931;
}
.container{
height: 100px;
width: 100px;
overflow: hidden;
}
Basically, you have a box shadow and then wrapping the element in a div with its overflow set to hidden. You'll need to adjust the height, width, and even padding of the div to only show the left box shadow, but it works. See here for an example If you look at the example, you can see how there's no other shadows, but only a black left shadow. Edit: this is a retake of the same screen shot, in case some one thinks that I just cropped out the right. You can find it here
My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.
As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)
List.subList(int startIndex, int endIndex)
First, remove the float
attribute on the inner div
s. Then, put text-align: center
on the main outer div
. And for the inner div
s,
use display: inline-block
. Might also be wise to give them explicit widths too.
<div style="margin: auto 1.5em; display: inline-block;">
<img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
<br/>
Nadia Bjorlin
</div>
Here are my solutions. Their advantages are : easy-understanding code, works for all characters. Enjoy.
Solution 1 :
public static void main(String[] args) {
String str = "CC%";
String result = "";
char[] messChar = str.toCharArray();
for (int i = 0; i < messChar.length; i++) {
result += Integer.toBinaryString(messChar[i]) + " ";
}
System.out.println(result);
}
prints :
1000011 1000011 100101
Solution 2 :
Possibility to choose the number of displayed bits per char.
public static String toBinary(String str, int bits) {
String result = "";
String tmpStr;
int tmpInt;
char[] messChar = str.toCharArray();
for (int i = 0; i < messChar.length; i++) {
tmpStr = Integer.toBinaryString(messChar[i]);
tmpInt = tmpStr.length();
if(tmpInt != bits) {
tmpInt = bits - tmpInt;
if (tmpInt == bits) {
result += tmpStr;
} else if (tmpInt > 0) {
for (int j = 0; j < tmpInt; j++) {
result += "0";
}
result += tmpStr;
} else {
System.err.println("argument 'bits' is too small");
}
} else {
result += tmpStr;
}
result += " "; // separator
}
return result;
}
public static void main(String args[]) {
System.out.println(toBinary("CC%", 8));
}
prints :
01000011 01000011 00100101
( Month(Created) + ',' + Year(Created) ) AS Date
from Swift 3 and above, Date is Comparable so we can directly compare dates like
let date1 = Date()
let date2 = Date().addingTimeInterval(50)
let isGreater = date1 > date2
print(isGreater)
let isSmaller = date1 < date2
print(isSmaller)
let isEqual = date1 == date2
print(isEqual)
Alternatively We can create extension on Date
extension Date {
func isEqualTo(_ date: Date) -> Bool {
return self == date
}
func isGreaterThan(_ date: Date) -> Bool {
return self > date
}
func isSmallerThan(_ date: Date) -> Bool {
return self < date
}
}
Use: let isEqual = date1.isEqualTo(date2)
Best practice is that exception handling should never hide issues. This means that try-catch
blocks should be extremely rare.
There are 3 circumstances where using a try-catch
makes sense.
Always deal with known exceptions as low-down as you can. However, if you're expecting an exception it's usually better practice to test for it first. For instance parse, formatting and arithmetic exceptions are nearly always better handled by logic checks first, rather than a specific try-catch
.
If you need to do something on an exception (for instance logging or roll back a transaction) then re-throw the exception.
Always deal with unknown exceptions as high-up as you can - the only code that should consume an exception and not re-throw it should be the UI or public API.
Suppose you're connecting to a remote API, here you know to expect certain errors (and have things to in those circumstances), so this is case 1:
try
{
remoteApi.Connect()
}
catch(ApiConnectionSecurityException ex)
{
// User's security details have expired
return false;
}
return true;
Note that no other exceptions are caught, as they are not expected.
Now suppose that you're trying to save something to the database. We have to roll it back if it fails, so we have case 2:
try
{
DBConnection.Save();
}
catch
{
// Roll back the DB changes so they aren't corrupted on ANY exception
DBConnection.Rollback();
// Re-throw the exception, it's critical that the user knows that it failed to save
throw;
}
Note that we re-throw the exception - the code higher up still needs to know that something has failed.
Finally we have the UI - here we don't want to have completely unhandled exceptions, but we don't want to hide them either. Here we have an example of case 3:
try
{
// Do something
}
catch(Exception ex)
{
// Log exception for developers
WriteException2LogFile(ex);
// Display message to users
DisplayWarningBox("An error has occurred, please contact support!");
}
However, most API or UI frameworks have generic ways of doing case 3. For instance ASP.Net has a yellow error screen that dumps the exception details, but that can be replaced with a more generic message in the production environment. Following those is best practice because it saves you a lot of code, but also because error logging and display should be config decisions rather than hard-coded.
This all means that case 1 (known exceptions) and case 3 (one-off UI handling) both have better patterns (avoid the expected error or hand error handling off to the UI).
Even case 2 can be replaced by better patterns, for instance transaction scopes (using
blocks that rollback any transaction not committed during the block) make it harder for developers to get the best practice pattern wrong.
For instance suppose you have a large scale ASP.Net application. Error logging can be via ELMAH, error display can be an informative YSoD locally and a nice localised message in production. Database connections can all be via transaction scopes and using
blocks. You don't need a single try-catch
block.
TL;DR: Best practice is actually to not use try-catch
blocks at all.
Also possible is to fix this with np.arange() instead of range which works for float numbers:
import numpy as np
for i in np.arange(c/10):
You can now specify the port in the .angular-cli.json under the defaults:
"defaults": {
"styleExt": "scss",
"serve": {
"port": 8080
},
"component": {}
}
Tested in angular-cli v1.0.6
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console
class. you can not get Console instance from System.console()
when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
$("selector").css("border-bottom-color", "#fff");
#mydiv
, then $("#mydiv")
.css()
method provided by jQuery to modify specified object's css property values. You can use:
input[type=text]
{
/*Styles*/
}
Define your common style attributes inside this. and for extra style you can add a class then.
Quit vim before "git commit".
to make vim
use other folders for backup files, (/tmp
for example):
set bdir-=.
set bdir+=/tmp
to make vim stop using current folder for .swp files:
set dir-=.
set dir+=/tmp
Use -=, +=
would be generally good, because vim has other defaults for bdir, dir, we don't want to clear all. Check vim help for more about bdir, dir:
:h bdir
:h dir
I'd question the wisdom, but perhaps:
source.TakeWhile(x => x != value).Count();
(using EqualityComparer<T>.Default
to emulate !=
if needed) - but you need to watch to return -1 if not found... so perhaps just do it the long way
public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
int index = 0;
var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
foreach (T item in source)
{
if (comparer.Equals(item, value)) return index;
index++;
}
return -1;
}
Just add throw
where needed, and try
block to the caller that handles the error. By convention you should only throw things that derive from std::exception
, so include <stdexcept>
first.
int compare(int a, int b) {
if (a < 0 || b < 0) {
throw std::invalid_argument("a or b negative");
}
}
void foo() {
try {
compare(-1, 0);
} catch (const std::invalid_argument& e) {
// ...
}
}
Also, look into Boost.Exception.
To create a popup you'll need the following script:
<script language="javascript" type="text/javascript">
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
</script>
Then, you link to it by:
<a href="popupex.html" onclick="return popitup('popupex.html')">Link to popup</a>
If you want you can call the function directly from document.ready also. Or maybe from another function.
I tried maximum to use the comparator with primitive type itself. At-last i concluded that there is no way to cheat the comparator.This is my implementation.
public class ArrSortComptr {
public static void main(String[] args) {
int[] array = { 3, 2, 1, 5, 8, 6 };
int[] sortedArr=SortPrimitiveInt(new intComp(),array);
System.out.println("InPut "+ Arrays.toString(array));
System.out.println("OutPut "+ Arrays.toString(sortedArr));
}
static int[] SortPrimitiveInt(Comparator<Integer> com,int ... arr)
{
Integer[] objInt=intToObject(arr);
Arrays.sort(objInt,com);
return intObjToPrimitive(objInt);
}
static Integer[] intToObject(int ... arr)
{
Integer[] a=new Integer[arr.length];
int cnt=0;
for(int val:arr)
a[cnt++]=new Integer(val);
return a;
}
static int[] intObjToPrimitive(Integer ... arr)
{
int[] a=new int[arr.length];
int cnt=0;
for(Integer val:arr)
if(val!=null)
a[cnt++]=val.intValue();
return a;
}
}
class intComp implements Comparator<Integer>
{
@Override //your comparator implementation.
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1.compareTo(o2);
}
}
@Roman: I can't say that this is a good example but since you asked this is what came to my mind. Suppose in an array you want to sort number's just based on their absolute value.
Integer d1=Math.abs(o1);
Integer d2=Math.abs(o2);
return d1.compareTo(d2);
Another example can be like you want to sort only numbers greater than 100.It actually depends on the situation.I can't think of any more situations.Maybe Alexandru can give more examples since he say's he want's to use a comparator for int array.
You can use sudo gem install -n /usr/local/bin cocoapods
This works for me.
'C:/PHP/5.2.13/ext\php_mcrypt1.dll'
I'd say there's some typo on your php.ini (the extra 1). Perhaps you're loading a different php.ini from what you expect (see the output of php.ini to make sure).
Other than that make sure that php_mcrypt.dll and PHP:
Were linked to the same VC runtime library (typically msvcrt.dll for VC6 or msvcrt90.dll for VC9) – use e.g. the dependency walker for this Are both debug builds or both release builds Both have ZTS enabled or ZTS disabled For libraries that depend on further libraries (DLLs), make sure they are available (e.g. in the same directory as the extension) PHP should give you meaning errors if any of the first three conditions above is not satisfied, but I wrote those anyway because I'm not sure for PHP 5.2.
i had the same problem, my solution was apply the required attribute to all elements
<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>
when the user check one of the elements i remove the required attribute from all elements:
var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
$checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');
$checkboxes.click(function() {
if($checkedCheckboxes.length) {
$checkboxes.removeAttr('required');
} else {
$checkboxes.attr('required', 'required');
}
});
You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):
curl http://www.myurl.com/?[1-20]
If you have other query strings in your URL, assign the sequence to a throwaway variable:
curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]
Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html
In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.
According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.
In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.
Since 2020-05-07, the docker-compose spec also defines the "pull_policy" property for a service:
version: '3.7'
services:
my-service:
image: someimage/somewhere
pull_policy: always
The docker-compose spec says:
pull_policy defines the decisions Compose implementations will make when it starts to pull images.
Possible values are (tl;dr, check spec for more details):
$(document).ready( function(){
$("button").click(function(){
$("p").toggle(1000,'linear');
});
});
Make sure if your table doesn't already have rows whose Primary Key values are same as the the Primary Key Id in your Query.
For anyone having trouble after upgrading to 14.04 https://askubuntu.com/questions/452042/why-is-my-apache-not-working-after-upgrading-to-ubuntu-14-04 as root changed before upgrade = /var/www after upgrade = /var/www/html
I encountered two issues related to the foregoing, when extracting text delimited by \
and /
, and found a solution that fits both, other than using new RegExp
, which requires \\\\
at the start. These findings are in Chrome and IE11.
The regular expression
/\\(.*)\//g
does not work. I think the //
is interpreted as the start of a comment in spite of the escape character. The regular expression (equally valid in my case though not in general)
/\b/\\(.*)\/\b/g
does not work either. I think the second /
terminates the regular expression in spite of the escape character.
What does work for me is to represent /
as \x2F
, which is the hexadecimal representation of /
. I think that's more efficient and understandable than using new RegExp
, but of course it needs a comment to identify the hex code.
The issue here is that your JSP is talking directly to the response OutputStream
. This technically isn't forbidden, but it's very much not a good idea.
Specifically, you call response.getOutputStream()
and write data to that. Later, when the JSP engine tries to flush the response, it fails because your code has already "claimed" the response. An application can either call getOutputStream
or getWriter
on any given response, it's not allowed to do both. JSP engines use getWriter
, and so you cannot call getOutputStream
.
You should be writing this code as a Servlet, not a JSP. JSPs are only really suitable for textual output as contained in the JSP. You can see that there's no actual text output in your JSP, it only contains java.
Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py
to run the script. So, for a script named test.py
containing
name = raw_input("Enter your name: ")
print "Hello, " + name
The PowerShell session would be
PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>
Add the following dependency. The scope should be compile then it will work.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>compile</scope>
</dependency>
The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <
)
select *
from xxx
where dates >= '20121026'
and dates < '20121028'
If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.
select *
from xxx
where CAST(dates as DATE) between '20121026' and '20121027'
This explicitly tells SQL Server that you are only interested in the DATE portion of the dates
column for comparison against the BETWEEN range.
Use .clf
or .cla
on your figure object instead of creating a new figure. From @DavidZwicker
Assuming you have imported pyplot
as
import matplotlib.pyplot as plt
plt.cla()
clears an axis, i.e. the currently active axis in the current figure. It leaves the other axes untouched.
plt.clf()
clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.
plt.close()
closes a window, which will be the current window, if not specified otherwise. plt.close('all')
will close all open figures.
The reason that del fig
does not work is that the pyplot
state-machine keeps a reference to the figure around (as it must if it is going to know what the 'current figure' is). This means that even if you delete your ref to the figure, there is at least one live ref, hence it will never be garbage collected.
Since I'm polling on the collective wisdom here for this answer, @JoeKington mentions in the comments that plt.close(fig)
will remove a specific figure instance from the pylab state machine (plt._pylab_helpers.Gcf) and allow it to be garbage collected.
Gabriel Garcia's mention of MutationObservers is on the right track, but didn't quite work for me. I am not sure if that was because of a browser quirk or due to a mistake on my end, but the version that ended up working for me was the following:
document.addEventListener("DOMContentLoaded", function(event) {
var observer = new MutationObserver(mutations=>{
mutations.map(mutation=>{
Array.from(mutation.addedNodes).map(node=>{
if (node.tagName === "SCRIPT") {
var s = document.createElement("script");
s.text=node.text;
if (typeof(node.parentElement.added) === 'undefined')
node.parentElement.added = [];
node.parentElement.added[node.parentElement.added.length] = s;
node.parentElement.removeChild(node);
document.head.appendChild(s);
}
})
})
})
observer.observe(document.getElementById("element_to_watch"), {childList: true, subtree: true,attributes: false});
};
Of course, you should replace element_to_watch
with the name of the element that is being modified.
node.parentElement.added
is used to store the script tags that are added to document.head
. In the function used to load the external page, you can use something like the following to remove no longer relevant script tags:
function freeScripts(node){
if (node === null)
return;
if (typeof(node.added) === 'object') {
for (var script in node.added) {
document.head.removeChild(node.added[script]);
}
node.added = {};
}
for (var child in node.children) {
freeScripts(node.children[child]);
}
}
And an example of the beginning of a load function:
function load(url, id, replace) {
if (document.getElementById(id) === null) {
console.error("Element of ID "+id + " does not exist!");
return;
}
freeScripts(document.getElementById(id));
var xhttp = new XMLHttpRequest();
// proceed to load in the page and modify innerHTML
}
I've created a function that uses readable basic functions and no reg-exps.
The function accepts color in hex, rgb or rgba CSS format and returns hex representation.
EDIT: there was a bug with parsing out rgba() format, fixed...
function getHexColor( color ){
//if color is already in hex, just return it...
if( color.indexOf('#') != -1 ) return color;
//leave only "R,G,B" :
color = color
.replace("rgba", "") //must go BEFORE rgb replace
.replace("rgb", "")
.replace("(", "")
.replace(")", "");
color = color.split(","); // get Array["R","G","B"]
// 0) add leading #
// 1) add leading zero, so we get 0XY or 0X
// 2) append leading zero with parsed out int value of R/G/B
// converted to HEX string representation
// 3) slice out 2 last chars (get last 2 chars) =>
// => we get XY from 0XY and 0X stays the same
return "#"
+ ( '0' + parseInt(color[0], 10).toString(16) ).slice(-2)
+ ( '0' + parseInt(color[1], 10).toString(16) ).slice(-2)
+ ( '0' + parseInt(color[2], 10).toString(16) ).slice(-2);
}
Use combinations of these to get the desired result:
Set Anchor
property to None, the controls will not be resized, they only shift their position.
Set Anchor
property to Top+Bottom+Left+Right, the controls will be resized but they don't change their position.
Set the Minimum Size
of the form to a proper value.
Set Dock
property.
Use Form Resize
event to change whatever you want
I don't know how font size (label, textbox, combobox, etc.) will be affected in (1) - (4), but it can be controlled in (5).
I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-
This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.
This did work in my case and hope it helps you too.
use this command for run every service just write name service for example :
for xrdp :
sudo /etc/init.d/xrdp start
for redis :
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
First thing, at the time the question was asked, uintptr_t
was not in C++. It's in C99, in <stdint.h>
, as an optional type. Many C++03 compilers do provide that file. It's also in C++11, in <cstdint>
, where again it is optional, and which refers to C99 for the definition.
In C99, it is defined as "an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer".
Take this to mean what it says. It doesn't say anything about size.
uintptr_t
might be the same size as a void*
. It might be larger. It could conceivably be smaller, although such a C++ implementation approaches perverse. For example on some hypothetical platform where void*
is 32 bits, but only 24 bits of virtual address space are used, you could have a 24-bit uintptr_t
which satisfies the requirement. I don't know why an implementation would do that, but the standard permits it.
To find and count duplicate lines in multiple files, you can try the following command:
sort <files> | uniq -c | sort -nr
or:
cat <files> | sort | uniq -c | sort -nr
If you still get error after running,
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Then try to download and install command line tool from https://developer.apple.com/download/more/ for your particular Mac os and Xcode version.
Then try to run,
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
and then
brew install node
xml:space="preserve"
has to work for all compliant XML parsers.
However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br />
(X)HTML tag, maybe this is the problem which you are facing.
You can also add
and/or
to insert CR/LF characters.
You also should have Tools->Android->Enable ADB Integration active.
if (StartDate>=EndDate)
{
throw new InvalidOperationException("Ack! StartDate is not before EndDate!");
}
Well, it would be easier to exclude them in the first place:
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
However, that would just change the value of authorsList
instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll
:
authorsList.RemoveAll(x => x.FirstName == "Bob");
If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:
var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
sklearn.cross_validation
has changed to
sklearn.model_selection
Checkout the documentation here: https://scikit-learn.org/stable/modules/cross_validation.html
You can also do it with two sed calls:
$ cat file.txt
something1: +12.0 (some unnecessary trailing data (this must go))
something2: +15.5 (some more unnecessary trailing data)
something4: +9.0 (some other unnecessary data)
something1: +13.5 (blah blah blah)
$ sed 's/^[^:]*: *\([+0-9.]\+\) .*/\1/' file.txt | sed -e :a -e '$!N; s/\n/,/; ta'
+12.0,+15.5,+9.0,+13.5
First sed call removes uninteresting data, and the second join all lines.
margin: auto;
I can't seem to post a comment, so I'll just say that updating pg_enum works in Postgres 8.4 . For the way our enums are set up, I've added new values to existing enum types via:
INSERT INTO pg_enum (enumtypid, enumlabel)
SELECT typelem, 'NEWENUM' FROM pg_type WHERE
typname = '_ENUMNAME_WITH_LEADING_UNDERSCORE';
It's a little scary, but it makes sense given the way Postgres actually stores its data.
You can use a predefined "qualitative colormap" like this:
from matplotlib.cm import get_cmap
name = "Accent"
cmap = get_cmap(name) # type: matplotlib.colors.ListedColormap
colors = cmap.colors # type: list
axes.set_prop_cycle(color=colors)
Tested on matplotlib 3.0.3. See https://github.com/matplotlib/matplotlib/issues/10840 for discussion on why you can't call axes.set_prop_cycle(color=cmap)
.
A list of predefined qualititative colormaps is available at https://matplotlib.org/gallery/color/colormap_reference.html :
As mentioned in several places, I'm also not able to get the req.session.destroy() function to work correctly.
This is my work around .. seems to do the trick, and still allows req.flash to be used
req.session = {};
If you delete or set req.session = null; , seems then you can't use req.flash
I had this issue for days looking for answers. My error log was similar to this npm just won't install node sass The only problem was the node version. Maybe it can help some of you.
I downgraded my Node.js from 9.3.0 to 6.12.2 and run:
npm update
Same problem with the 'script' plugin in the Atom editor, which is an old version of node, not having btoa(), nor atob(), nor does it support the Buffer datatype. Following code does the trick:
var Base64 = new function() {_x000D_
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="_x000D_
this.encode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = Base64._utf8_encode(input);_x000D_
while (i < input.length) {_x000D_
chr1 = input.charCodeAt(i++);_x000D_
chr2 = input.charCodeAt(i++);_x000D_
chr3 = input.charCodeAt(i++);_x000D_
enc1 = chr1 >> 2;_x000D_
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);_x000D_
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);_x000D_
enc4 = chr3 & 63;_x000D_
if (isNaN(chr2)) {_x000D_
enc3 = enc4 = 64;_x000D_
} else if (isNaN(chr3)) {_x000D_
enc4 = 64;_x000D_
}_x000D_
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
this.decode = function(input) {_x000D_
var output = "";_x000D_
var chr1, chr2, chr3;_x000D_
var enc1, enc2, enc3, enc4;_x000D_
var i = 0;_x000D_
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");_x000D_
while (i < input.length) {_x000D_
enc1 = keyStr.indexOf(input.charAt(i++));_x000D_
enc2 = keyStr.indexOf(input.charAt(i++));_x000D_
enc3 = keyStr.indexOf(input.charAt(i++));_x000D_
enc4 = keyStr.indexOf(input.charAt(i++));_x000D_
chr1 = (enc1 << 2) | (enc2 >> 4);_x000D_
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);_x000D_
chr3 = ((enc3 & 3) << 6) | enc4;_x000D_
output = output + String.fromCharCode(chr1);_x000D_
if (enc3 != 64) {_x000D_
output = output + String.fromCharCode(chr2);_x000D_
}_x000D_
if (enc4 != 64) {_x000D_
output = output + String.fromCharCode(chr3);_x000D_
}_x000D_
}_x000D_
output = Base64._utf8_decode(output);_x000D_
return output;_x000D_
}_x000D_
_x000D_
this._utf8_encode = function(string) {_x000D_
string = string.replace(/\r\n/g, "\n");_x000D_
var utftext = "";_x000D_
for (var n = 0; n < string.length; n++) {_x000D_
var c = string.charCodeAt(n);_x000D_
if (c < 128) {_x000D_
utftext += String.fromCharCode(c);_x000D_
} else if ((c > 127) && (c < 2048)) {_x000D_
utftext += String.fromCharCode((c >> 6) | 192);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
} else {_x000D_
utftext += String.fromCharCode((c >> 12) | 224);_x000D_
utftext += String.fromCharCode(((c >> 6) & 63) | 128);_x000D_
utftext += String.fromCharCode((c & 63) | 128);_x000D_
}_x000D_
}_x000D_
return utftext;_x000D_
}_x000D_
_x000D_
this._utf8_decode = function(utftext) {_x000D_
var string = "";_x000D_
var i = 0;_x000D_
var c = 0,_x000D_
c1 = 0,_x000D_
c2 = 0,_x000D_
c3 = 0;_x000D_
while (i < utftext.length) {_x000D_
c = utftext.charCodeAt(i);_x000D_
if (c < 128) {_x000D_
string += String.fromCharCode(c);_x000D_
i++;_x000D_
} else if ((c > 191) && (c < 224)) {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));_x000D_
i += 2;_x000D_
} else {_x000D_
c2 = utftext.charCodeAt(i + 1);_x000D_
c3 = utftext.charCodeAt(i + 2);_x000D_
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));_x000D_
i += 3;_x000D_
}_x000D_
}_x000D_
return string;_x000D_
}_x000D_
}()_x000D_
_x000D_
var btoa = Base64.encode;_x000D_
var atob = Base64.decode;_x000D_
_x000D_
console.log("btoa('A') = " + btoa('A'));_x000D_
console.log("btoa('QQ==') = " + atob('QQ=='));_x000D_
console.log("btoa('B') = " + btoa('B'));_x000D_
console.log("btoa('Qg==') = " + atob('Qg=='));
_x000D_
You can use this function
var datastring = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handling here');
}
});
return type is json
EDIT: I use event.preventDefault
to prevent the browser getting submitted in such scenarios.
Adding more data to the answer.
dataType: "jsonp"
if it is a cross-domain call.
beforeSend:
// this is a pre-request call back function
complete:
// a function to be called after the request ends.so code that has to be executed regardless of success or error can go here
async:
// by default, all requests are sent asynchronously
cache:
// by default true. If set to false, it will force requested pages not to be cached by the browser.
Find the official page here
A Simple One-Line Solution:
let query = Object.assign.apply(null, location.search.slice(1).split('&').map(entry => ({ [entry.split('=')[0]]: entry.split('=')[1] })));
Expanded & Explained:
// define variable
let query;
// fetch source query
query = location.search;
// skip past the '?' delimiter
query = query.slice(1);
// split source query by entry delimiter
query = query.split('&');
// replace each query entry with an object containing the query entry
query = query.map((entry) => {
// get query entry key
let key = entry.split('=')[0];
// get query entry value
let value = entry.split('=')[1];
// define query object
let container = {};
// add query entry to object
container[key] = value;
// return query object
return container;
});
// merge all query objects
query = Object.assign.apply(null, query);
You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:
namespace X
{
namespace Y
{
class A;
void func(A* a) { ... } // incomplete type here!
}
}
...but, in class A was defined like this:
namespace X
{
class A { ... };
}
Thus, A was defined as X::A
, but I was using it as X::Y::A
.
The fix obviously is to move the forward reference to its proper place like so:
namespace X
{
class A;
namespace Y
{
void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
}
}
"pull-left" is what you need, it looks like you are using Bootstrap 2, I am not sure if that is available, consider bootstrap 3, unless ofcourse it is a huge rework! ... for Bootstrap 3 but you need to make sure you have 12 columns in each row as well, otherwise you will have issues.
You can create an async init() {... return this;}
method, then instead do new MyClass().init()
whenever you'd normally just say new MyClass()
.
This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.
A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined
because the constructor returns nothing. Oops. Much better would be to do something like:
The best thing to do would be:
class AsyncOnlyObject {
constructor() {
}
async init() {
this.someField = await this.calculateStuff();
}
async calculateStuff() {
return 5;
}
}
async function newAsync_AsyncOnlyObject() {
return await new AsyncOnlyObject().init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype)
directly:
async function newAsync_AsyncOnlyObject() {
return await Object.create(AsyncOnlyObject.prototype).init();
}
newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}
However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject)
, but here I'm going to use extends
because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):
class AsyncObject {
constructor() {
throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
}
static async anew(...args) {
var R = Object.create(this.prototype);
R.init(...args);
return R;
}
}
class MyObject extends AsyncObject {
async init(x, y=5) {
this.x = x;
this.y = y;
// bonus: we need not return 'this'
}
}
MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}
(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)
Django 2.2 version now has a bulk_update.
Refer to the following django documentation section
In short you should be able to use:
ModelClass.objects.filter(name='bar').update(name="foo")
You can also use F
objects to do things like incrementing rows:
from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
See the documentation.
However, note that:
ModelClass.save
method (so if you have some logic inside it won't be triggered). .update()
on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the .filter()
and .exclude()
methods.This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.
After successfully running autogen.sh/configure, compile with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make
The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
I found the best way to solving this problem was a combination of trial and error and reading what was written before me:
As you can see I have some pretty tricky stuff going on... but the main kicker of getting this to looking good are:
PARENT ELEMENT (UL): border-collapse: separate; border-spacing: .25em; margin-left: -.25em;
CHILD ELEMENTS (LI): display: table-cell; vertical-align: middle;
HTML
<ul>
<li><span class="large">3</span>yr</li>
<li>in<br>stall</li>
<li><span class="large">9</span>x<span class="large">5</span></li>
<li>on<br>site</li>
<li>globe</li>
<li>back<br>to hp</li>
</ul>
CSS
ul { border: none !important; border-collapse: separate; border-spacing: .25em; margin: 0 0 0 -.25em; }
li { background: #767676 !important; display: table-cell; vertical-align: middle; position: relative; border-radius: 5px 0; text-align: center; color: white; padding: 0 !important; font-size: .65em; width: 4em; height: 3em; padding: .25em !important; line-height: .9; text-transform: uppercase; }
If you are still interested, Chris Wolf made a prototype implementation of SQLite with Stored Procedures. You can find the details at his blog post: Adding Stored Procedures to SQLite
For Java 8, You can have one more solution like below
List<String> list = new ArrayList<>();
String searchTerm = "dvd";
if(String.join(",", list).toLowerCase().contains(searchTerm)) {
System.out.println("Element Present!");
}
Try This:
BEGIN
declare @Date1 datetime
declare @Date2 datetime
declare @chkYear int
declare @chkMonth int
declare @chkDay int
declare @chkHour int
declare @chkMinute int
declare @chkSecond int
declare @chkMiliSecond int
set @Date1='2010-12-31 15:13:48.593'
set @Date2='2010-12-31 00:00:00.000'
set @chkYear=datediff(yyyy,@Date1,@Date2)
set @chkMonth=datediff(mm,@Date1,@Date2)
set @chkDay=datediff(dd,@Date1,@Date2)
set @chkHour=datediff(hh,@Date1,@Date2)
set @chkMinute=datediff(mi,@Date1,@Date2)
set @chkSecond=datediff(ss,@Date1,@Date2)
set @chkMiliSecond=datediff(ms,@Date1,@Date2)
if @chkYear=0 AND @chkMonth=0 AND @chkDay=0 AND @chkHour=0 AND @chkMinute=0 AND @chkSecond=0 AND @chkMiliSecond=0
Begin
Print 'Both Date is Same'
end
else
Begin
Print 'Both Date is not Same'
end
End
Here is sample c# code that are sending 2 parameters to a bat/cmd file for answer this question.
Comment: how can I pass parameters and read a result of command execution?
Option 1 : Without hiding the console window, passing arguments and without getting the outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
}
}
}
Option 2 : Hiding the console window, passing arguments and taking outputs
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var process = new Process();
var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
}
}
I have used for getting route name in larvel 5.3
Request::path()
DO NOT use a 1x1 semi transparent PNG. Size the PNG up to 10x10, 100x100, etc. Whatever makes sense on your page. (I used a 200x200 PNG and it was only 0.25 kb, so there's no real concern over file size here.)
After visiting this post, I created my web page with 3, 1x1 PNGs with varying transparency.
Dreamweaver CS5 was tanking. I was having flash backs to DOS!!! Apparently any time I tried to scroll, insert text, basically do anything, DW was trying to reload the semi transparent areas 1x1 pixel at a time ... YIKES!
Adobe tech support didn't even know what the problem was, but told me to rebuild the file (it worked on their systems, incidentally). It was only when I loaded the first transparent PNG into the css file that the doc dove deep again.
Then I found a post on another help site about PNGs crashing Dreamweaver. Size your PNG up; there's no downside to doing so.
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
You can not give order by
because order by
does a "full scan" on a table.
The following query is better:
SELECT * FROM table WHERE id = (SELECT MAX(id) FROM table);
I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this
got lost. In such cases, I would recommend passing such function bound to this
. E.g.
this.myFunction.bind(this);
I tried to do this with System.Environment back when I was learning extension methods and was not successful. The reason is, as others mention, because extension methods require an instance of the class.
If you installed the system image and still get this error, it might be that the Android SDK manager did not put the files in the right folder for the AVD manager. See an answer to Stack Overflow question How to create an AVD for Android 4.0.3? (Unable to find a 'userdata.img').
var isAlaCarte =
ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") &&
bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));
A data object that can exist without depending upon the existence of another data object is known as Strong Data Object.
If one of the tables M
, S
, D
, or H
has more than one row for a given Id
(if just the Id
column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id
in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).
References:
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
I ran across this question while troubleshooting my own code.
So this does NOT work...
$myLogText = ""
function AddLog ($Message)
{
$myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
This APPEARS to work, but only in the PowerShell ISE:
$myLogText = ""
function AddLog ($Message)
{
$global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $myLogText
This is actually what works in both ISE and command line:
$global:myLogText = ""
function AddLog ($Message)
{
$global:myLogText += ($Message)
}
AddLog ("Hello")
Write-Host $global:myLogText
Use the .split()
method. When specifying an empty string as the separator, the split()
method will return an array with one element per character.
entry = prompt("Enter your name")
entryArray = entry.split("");
This is due to the mismatch of the data type of your java Entity and the database table column. Please review if all the column is exact same data type as your entity. This mismatch happens when we update our model attribute's data-type.
Here's how I addressed this (using a MEAN derivative)
My variables:
{
NODE_ENV : development,
...
ui_varables {
var1: one,
var2: two
}
}
First I had to make sure that the necessary config variables were being passed. MEAN uses the node nconf package, and by default is set up to limit which variables get passed from the environment. I had to remedy that:
config/config.js:
original:
nconf.argv()
.env(['PORT', 'NODE_ENV', 'FORCE_DB_SYNC'] ) // Load only these environment variables
.defaults({
store: {
NODE_ENV: 'development'
}
});
after modifications:
nconf.argv()
.env('__') // Load ALL environment variables
// double-underscore replaces : as a way to denote hierarchy
.defaults({
store: {
NODE_ENV: 'development'
}
});
Now I can set my variables like this:
export ui_varables__var1=first-value
export ui_varables__var2=second-value
Note: I reset the "heirarchy indicator" to "__" (double underscore) because its default was ":", which makes variables more difficult to set from bash. See another post on this thread.
Now the jade part: Next the values need to be rendered, so that javascript can pick them up on the client side. A straightforward way to write these values to the index file. Because this is a one-page app (angular), this page is always loaded first. I think ideally this should be a javascript include file (just to keep things clean), but this is good for a demo.
app/controllers/index.js:
'use strict';
var config = require('../../config/config');
exports.render = function(req, res) {
res.render('index', {
user: req.user ? JSON.stringify(req.user) : "null",
//new lines follow:
config_defaults : {
ui_defaults: JSON.stringify(config.configwriter_ui).replace(/<\//g, '<\\/') //NOTE: the replace is xss prevention
}
});
};
app/views/index.jade:
extends layouts/default
block content
section(ui-view)
script(type="text/javascript").
window.user = !{user};
//new line here
defaults = !{config_defaults.ui_defaults};
In my rendered html, this gives me a nice little script:
<script type="text/javascript">
window.user = null;
defaults = {"var1":"first-value","var2:"second-value"};
</script>
From this point it's easy for angular to utilize the code.
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
I just had the same problem and found your question here ...
This was my solution:
Set<Integer> mySetOfIntegers = new HashSet<Integer>();
/* ... there's at least one integer in the set ... */
Integer iFirstItemInSet = new ArrayList<Integer>(mySetOfIntegers).get(0);
You can use Regex.Match
if(text.matches("\\d*")&& text.length() > 2){
System.out.println("number");
}
Or you could use onversions like Integer.parseInt(String)
or better Long.parseLong(String)
for bigger numbers
like for example:
private boolean onlyContainsNumbers(String text) {
try {
Long.parseLong(text);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
And then test with:
if (onlyContainsNumbers(text) && text.length() > 2) {
// do Stuff
}
Of the top of my head, can you try to use the 'q' operator for the string literal
something like
insert all
into domo_queries values (q'[select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;
Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.
These words existed way before Computer Science came around.
Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.
Property is a quality that exists without any attribution. For example, clay has adhesive qualities; i.e, a property of clay is its adhesive quality. Another example: one of the properties of metals is electrical conductivity. Properties demonstrate themselves through physical phenomena without the need to attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.
To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably - but then again programmers usually don't hold degrees in English Literature and do not write or care much about grammar books :).
According to pip documentation at
http://pip.readthedocs.org/en/stable/user_guide/#configuration
You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows
On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf
On Windows, the configuration file is: %HOME%\pip\pip.ini
The %HOME% is located in C:\Users\Bob
on windows assuming your name is Bob
On linux the $HOME
directory can be located by using cd ~
You may have to create the pip.ini
file when you find your pip directory. Within your pip.ini
or pip.config
you will then need to put (assuming your on windows) something like
[global]
target=C:\Users\Bob\Desktop
Except that you would replace C:\Users\Bob\Desktop
with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path
After saving the command would then be
pip install pandas
However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.
pickBy uses identity by default:
_.pickBy({ a: null, b: 1, c: undefined, d: false });
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
With append you can append a single element that will extend the list:
>>> a = [1,2]
>>> a.append(3)
>>> a
[1,2,3]
If you want to extend more than one element you should use extend, because you can only append one elment or one list of element:
>>> a.append([4,5])
>>> a
>>> [1,2,3,[4,5]]
So that you get a nested list
Instead with extend, you can extend a single element like this
>>> a = [1,2]
>>> a.extend([3])
>>> a
[1,2,3]
Or, differently, from append, extend more elements in one time without nesting the list into the original one (that's the reason of the name extend)
>>> a.extend([4,5,6])
>>> a
[1,2,3,4,5,6]
Both append and extend can add one element to the end of the list, though append is simpler.
>>> x = [1,2]
>>> x.append(3)
>>> x
[1,2,3]
>>> x = [1,2]
>>> x.extend([3])
>>> x
[1,2,3]
If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a NESTED list!
>>> x = [1,2]
>>> x.append([3,4])
>>> x
[1,2,[3,4]]
With extend, instead, you pass a list as an argument, but you will obtain a list with the new element that is not nested in the old one.
>>> z = [1,2]
>>> z.extend([3,4])
>>> z
[1,2,3,4]
So, with more elements, you will use extend to get a list with more items. However, appending a list will not add more elements to the list, but one element that is a nested list as you can clearly see in the output of the code.
You can use Poppy for this. It is normally used to gather the stack trace during a crash but it can also output it for a running program as well.
Now here's the good part: it can output the actual parameter values for each function on the stack, and even local variables, loop counters, etc.
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
Place your pointer on the dock button and long click it (some seconds) or right & left mouse click depending on the browser version.
If you want to show the rating bar in small size, then just copy and paste this code in your project.
<RatingBar
android:id="@+id/MyRating"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/getRating"
android:isIndicator="true"
android:numStars="5"
android:stepSize="0.1" />
So there are advantages and disadvantages to each event. The events onkeypress
and onkeydown
don't retrieve the latest value, and onkeypress
doesn't fire for non-printable characters in some browsers. The onkeyup
event doesn't detect when a key is held down for multiple characters.
This is a little hacky, but doing something like
function edValueKeyDown(input) {
var s = input.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The text box contains: "+s;
//var s = $("#edValue").val();
//$("#lblValue").text(s);
}
<input id="edValue" type="text" onkeydown="setTimeout(edValueKeyDown, 0, this)" />
seems to handle the best of all worlds.
Maybe you can iterate over the map looking for the keys to remove and storing them in a separate collection. Then remove the collection of keys from the map. Modifying the map while iterating is usually frowned upon. This idea may be suspect if the map is very large.
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
For MySQL > 5.1.11 or MariaDB
SET GLOBAL log_output = 'TABLE';
SET GLOBAL general_log = 'ON';
mysql.general_log
If you want to output to a log file:
SET GLOBAL log_output = "FILE";
SET GLOBAL general_log_file = "/path/to/your/logfile.log"
SET GLOBAL general_log = 'ON';
As mentioned by jeffmjack in comments, these settings will be forgetting before next session unless you edit the configuration files (e.g. edit /etc/mysql/my.cnf
, then restart to apply changes).
Now, if you'd like you can tail -f /var/log/mysql/mysql.log
You are not changing the value of line. It should be something like this.
import java.io.BufferedReader;
import java.io.FileReader;
public class InsertValuesIntoTestDb {
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
while((line = br.readLine()) != null){
String[] b = line.split(splitBy);
System.out.println(b[0]);
}
br.close();
}
}
readLine returns each line and only returns null when there is nothing left. The above code sets line and then checks if it is null.
Using the ampersand (&) will run the command in a child process (child to the current bash session). However, when you exit the session, all child processes will be killed.
using nohup + ampersand (&) will do the same thing, except that when the session ends, the parent of the child process will be changed to "1" which is the "init" process, thus preserving the child from being killed.
Why cant I do this:
List<Object> object = new List<Object>();
You can't do this because List
is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List
include ArrayList
, LinkedList
etc.
Here is how one would create an instance of ArrayList
:
List<Object> object = new ArrayList<Object>();
I have a method that returns a
List<?>
, how would I turn that into aList<Object>
Show us the relevant code and I'll update the answer.
It may be bit late but it will help someone for sure You can search password if you remember something otherwise try searching like
signingConfig.storePassword
also if you forgot key alias you can find here that also search something like signingConfig.keyAlias
Project.gradle\3.3\taskArtifacts\taskArtifacts.bin
Hope it will help someone
function.prototype.bind() accepts an Object.
It binds the calling function to the passed Object and the returns the same.
When an object is bound to a function, it means you will be able to access the values of that object from within the function using 'this' keyword.
It can also be said as,
function.prototype.bind() is used to provide/change the context of a function.
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<= this.power; i++) {
product*=number;
}
return product;
}
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));
let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
_x000D_
Let us try to understand this.
let powerOfNumber = function(number) {
let product = 1;
for (let i = 1; i <= this.power; i++) {
product *= number;
}
return product;
}
Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.
Let us create a function powerOfTwo which will find the second power of a number using the above function.
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
Here the object {power : 2} is passed to powerOfNumber function using bind.
The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<=2; i++) {
product*=number;
}
return product;
}
Hence, powerOfTwo will find the second power.
Feel free to check this out.
I'm not sure you can change port numbers with Send-MailMessage since Gmail works on port 587. Anyway, here's how to send email through Gmail with .NET SmtpClient:
$smtpClient = New-Object system.net.mail.smtpClient
$smtpClient.Host = 'smtp.gmail.com'
$smtpClient.Port = 587
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = [Net.NetworkCredential](Get-Credential GmailUserID)
$smtpClient.Send('[email protected]', '[email protected]', 'test subject', 'test message')
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
What you are doing raises an exception (and rightfully so).
You can always do
try{
window.a.b.c
}catch(e){
console.log("YO",e)
}
But I wouldn't, instead think of your use case.
Why are you accessing data, 6 levels nested that you are unfamiliar of? What use case justifies this?
Usually, you'd like to actually validate what sort of object you're dealing with.
Also, on a side note you should not use statements like if(a.b)
because it will return false if a.b is 0 or even if it is "0". Instead check if a.b !== undefined
You need to create it. In most installations I've used it hasn't been created by default.
You usually create it as ~/.vimrc
.
DataRow[] dtr=dtPerson.select("name=Joe");
foreach(var drow in dtr)
{
drow.delete();
}
dtperson.AcceptChanges();
I hope it will help you
Using Promise
and checking if the body
object is a valid JSON. If not a Promise reject
will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
Clean Project -> Invalidate caches/restart. My problem resolved with this.
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
Well, you could try something like this, :
public String getElapsedTimeHoursMinutesSecondsString() {
long elapsedTime = getElapsedTime();
String format = String.format("%%0%dd", 2);
elapsedTime = elapsedTime / 1000;
String seconds = String.format(format, elapsedTime % 60);
String minutes = String.format(format, (elapsedTime % 3600) / 60);
String hours = String.format(format, elapsedTime / 3600);
String time = hours + ":" + minutes + ":" + seconds;
return time;
}
to convert milliseconds to a time value
Problem: After creating a PyDev Project, the project does not show up in "PyDev Package Explorer" ;(
Solution: This is what I do to see them all in "Project Explorer":
I am using Eclipse IDE 2019-12
click on "Resource" icon at the top right corner
Now you shall see all projects show up in "Project Explorer".
Tricky note: now if you click on "PyDev" icon, you will see less projects show up in "PyDev Package Explorer" Magic?
async Task<int> LongTask1() {
...
return 0;
}
async Task<int> LongTask2() {
...
return 1;
}
...
{
Task<int> t1 = LongTask1();
Task<int> t2 = LongTask2();
await Task.WhenAll(t1,t2);
//now we have t1.Result and t2.Result
}
I really don't understand why python still doesn't have such a function. I also don't agree to use the following
f.tell() == os.fstat(f.fileno()).st_size
The main reason is f.tell()
doesn't likely to work for some special conditions.
The method works for me is like the following. If you have some pseudocode like the following
while not EOF(f):
line = f.readline()
" do something with line"
You can replace it with:
lines = iter(f.readlines())
while True:
try:
line = next(lines)
" do something with line"
except StopIteration:
break
This method is simple and you don't need to change most of you code.
In this part of your code:
if(tmp[j] > 57 && tmp[j] < 48)
isDigit = 0;
else
isDigit = 1;
Your if
condition will always be false, resulting in isDigit
always being set to 1
. You are probably wanting:
if(tmp[j] > '9' || tmp[j] < '0')
isDigit = 0;
else
isDigit = 1;
But. this can be simplified to:
isDigit = isdigit(tmp[j]);
However, the logic of your loop seems kind of misguided:
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
isDigit = isdigit(tmp[j]);
j++;
}
As tmp
is not a constant, it is uncertain whether the compiler will optimize the length calculation out of each iteration.
As @andlrc suggests in a comment, you can instead just check for digits, since the terminating NUL will fail the check anyway.
while (isdigit(tmp[j])) ++j;
to Hide All Errors:
error_reporting(0);
ini_set('display_errors', 0);
to Show All Errors:
error_reporting(E_ALL);
ini_set('display_errors', 1);
It's quite easy with Key Value Observing (KVO), just create a subclass of UITextView and do:
private func setup() { // Called from init or somewhere
fitToContentObservations = [
textView.observe(\.contentSize) { _, _ in
self.invalidateIntrinsicContentSize()
},
// For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.
textView.observe(\.contentOffset) { _, _ in
if self.contentOffset != .zero { // Need to check this to stop infinite loop
self.contentOffset = .zero
}
}
]
}
public override var intrinsicContentSize: CGSize {
return contentSize
}
If you don't want to subclass you could try doing textView.bounds = textView.contentSize
in the contentSize
observer.
My advice would be this:
/garages
Returns list of garages (think JSON array here)
/garages/yyy
Returns specific garage
/garage/yyy/cars
Returns list of cars in garage
/garages/cars
Returns list of all cars in all garages (may not be practical of course)
/cars
Returns list of all cars
/cars/xxx
Returns specific car
/cars/colors
Returns lists of all posible colors for cars
/cars/colors/red,blue,green
Returns list of cars of the specific colors (yes commas are allowed :) )
Edit:
/cars/colors/red,blue,green/doors/2
Returns list of all red,blue, and green cars with 2 doors.
/cars/type/hatchback,coupe/colors/red,blue,green/
Same idea as the above but a lil more intuitive.
/cars/colors/red,blue,green/doors/two-door,four-door
All cars that are red, blue, green and have either two or four doors.
Hopefully that gives you the idea. Essentially your Rest API should be easily discoverable and should enable you to browse through your data. Another advantage with using URLs and not query strings is that you are able to take advantage of the native caching mechanisms that exist on the web server for HTTP traffic.
Here's a link to a page describing the evils of query strings in REST: http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful
I used Google's cache because the normal page wasn't working for me here's that link as well: http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful
Does your console app require user interaction? If so, that's a serious no-no and you should redesign your application. While there are some hacks to make this sort of work in older versions of the OS, this is guaranteed to break in the future.
If your app does not require user interaction, then perhaps your problem is related to the user the service is running as. Try making sure that you run as the correct user, or that the user and/or resources you are using have the right permissions.
If you require some kind of user-interaction, then you will need to create a client application and communicate with the service and/or sub-application via rpc, sockets, or named pipes.
As Draemon says, the closest that Java comes to inline arrays is new String[]{"blah", "hey", "yo"}
however there is a neat trick that allows you to do something like
array("blah", "hey", "yo")
with the type automatically inferred.
I have been working on a useful API for augmenting the Java language to allow for inline arrays and collection types. For more details google project Espresso4J or check it out here
I don't understand, why you don't want to set the $HOME
environment variable since that solves exactly what you're asking for.
cd ~
doesn't mean change to the root directory, but change to the user's home directory, which is set by the $HOME
environment variable.
Edit C:\Program Files (x86)\Git\etc\profile
and set $HOME
variable to whatever you want (add it if it's not there). A good place could be for example right after a condition commented by # Set up USER's home directory
. It must be in the MinGW format, for example:
HOME=/c/my/custom/home
Save it, open Git Bash and execute cd ~
. You should be in a directory /c/my/custom/home
now.
Everything that accesses the user's profile should go into this directory instead of your Windows' profile on a network drive.
Note: C:\Program Files (x86)\Git\etc\profile
is shared by all users, so if the machine is used by multiple users, it's a good idea to set the $HOME
dynamically:
HOME=/c/Users/$USERNAME
Set the environment variable HOME
in Windows to whatever directory you want. In this case, you have to set it in Windows path format (with backslashes, e.g. c:\my\custom\home
), Git Bash will load it and convert it to its format.
If you want to change the home directory for all users on your machine, set it as a system environment variable, where you can use for example %USERNAME%
variable so every user will have his own home directory, for example:
HOME=c:\custom\home\%USERNAME%
If you want to change the home directory just for yourself, set it as a user environment variable, so other users won't be affected. In this case, you can simply hard-code the whole path:
HOME=c:\my\custom\home
Have that issue. So long time pass... Without side-fields of page it's break normal, but when fields appears, page and "page break space" will scale. So, with a normal field, within a document, it was shown incorrect. I fix it with set
width:100%
and use
div.page
{
page-break-before: always;
page-break-inside: avoid;
}
Use it on first line.
cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
alert('successful : ' + html);
$("#result").html("Successful");
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
You can't; at least not the same way you can test whether a pointer is NULL
.
A std::string
object is always initialized and always contains a string; its contents by default are an empty string (""
).
You can test for emptiness (using s.size() == 0
or s.empty()
).
The pylab examples page is a very useful source. The example relevant for your question:
http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/scatter_demo2.py http://matplotlib.sourceforge.net/users/screenshots.html#scatter-demo
Untested....but should work.
Dim lastrow as long
lastrow = range("D65000").end(xlup).Row
ActiveCell.FormulaR1C1 = _
"=IF(MONTH(RC[-1])>3,"" ""&YEAR(RC[-1])&""-""&RIGHT(YEAR(RC[-1])+1,2),"" ""&YEAR(RC[-1])-1&""-""&RIGHT(YEAR(RC[-1]),2))"
Selection.AutoFill Destination:=Range("E2:E" & lastrow)
'Selection.AutoFill Destination:=Range("E2:E"& lastrow)
Range("E2:E1344").Select
Only exception being are you sure your Autofill code is perfect...
type C:\temp\test.bat>C:\temp\test.log
$("#elementID").html("another string");
Below code works for me:
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var myCenter = new google.maps.LatLng(51.528308, -0.3817765);
function initialize() {
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
icon: {
url: '/images/marker.png',
size: new google.maps.Size(70, 86), //marker image size
origin: new google.maps.Point(0, 0), // marker origin
anchor: new google.maps.Point(35, 86) // X-axis value (35, half of marker width) and 86 is Y-axis value (height of the marker).
}
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
Go to someplace the namespace is declared in one of your files. Put the cursor on the part of the namespace you want to change, and press F2. This should rename the namespace in every file. At least, it worked in my little demo project I created to test this answer!
Depending on your VS version, the shortcut might also be Ctrl-R,Ctrl-R.
They should be pretty much the same. The difference isn't going to matter. I would go with sprintf
since it requires less code.
I got this error because I was using require('https')
where I should have been using require('http')
.
How about using a Browser plugin that gives you an overview of ANY html page. I have tried the following:
They both work pretty well for IPython Notebooks. I was reluctant to use the previous solutions as they seem a bit unstable and ended up using these extensions.
First check with dmesg | grep tty
if system recognize your adapter.
Then try to run minicom with sudo minicom -s
, go to "Serial port setup" and change the first line to /dev/ttyUSB0
.
Don't forget to save config as default with "Save setup as dfl". It works for me on Ubuntu 11.04 on VirtualBox.
To export a directory from GitHub, replace "/tree/master/" in the directory's url with "/trunk/".
For example, to export the directory from the following URL:
https://github.com/liferay/liferay-plugins/tree/master/portlets/sample-hibernate-portlet
run the following command:
svn export https://github.com/liferay/liferay-plugins/trunk/portlets/sample-hibernate-portlet
for running mutilple js files
#!/bin/bash
cd /root/migrate/
ls -1 *.js | sed 's/.js$//' | while read name; do
start=`date +%s`
mongo localhost:27017/wbars $name.js;
end=`date +%s`
runtime1=$((end-start))
runtime=$(printf '%dh:%dm:%ds\n' $(($runtime1/3600)) $(($secs%3600/60)) $(($secs%60)))
echo @@@@@@@@@@@@@ $runtime $name.js completed @@@@@@@@@@@
echo "$name.js completed"
sync
echo 1 > /proc/sys/vm/drop_caches
echo 2 > /proc/sys/vm/drop_caches
echo 3 > /proc/sys/vm/drop_caches
done
The actual standard key-layout is found in /system/usr/keylayout/qwerty.kl
within the Android running on the handset. And it is a generic keylayout also.
key 115 VOLUME_UP WAKE
key 114 VOLUME_DOWN WAKE
From the AOSP source it can be found in sdk/emulator/keymaps/qwerty.kl
.
But bear in mind this, when the source gets compiled along with a device specific keylayout, that will override the standard layout instead so the mileage will vary depending on what the manufacturer has programmed into the keycode for the volume up/down buttons in your case!
File f = new File(filePathString);
This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:
f.createNewFile();
So f.exists()
can be used to check whether such a file exists or not.
I was trying to fetch table meta data, but had the following error:
Using:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
DatabaseMetaData metaData = connection.getMetaData();
...
metaData.getColumns(...);
returned an empty ResultSet.
But using the following URL instead it worked properly:
String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false";
There was a need to specify: DATABASE_TO_UPPER=false
Add this in your build.gradle
configurations.all {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
exclude group: 'org.springframework.boot', module: 'logback-classic'
}
You can do this by using TPL (task parallel library) instead of direct using await keyword.
private bool CheckInCategory(int? id, out Category category)
{
if (id == null || id == 0)
category = null;
else
category = Task.Run(async () => await _context.Categories.FindAsync(id ?? 0)).Result;
return category != null;
}
if(!CheckInCategory(int? id, out var category)) return error
Were you trying it like this:
string text = GetTextFromSomewhere();
text.Replace("\\", "");
text.Replace("\"", "");
? If so, that's the problem - Replace
doesn't change the original string, it returns a new string with the replacement performed... so you'd want:
string text = GetTextFromSomewhere();
text = text.Replace("\\", "").Replace("\"", "");
Note that this will replace each backslash and each double-quote character; if you only wanted to replace the pair "backslash followed by double-quote" you'd just use:
string text = GetTextFromSomewhere();
text = text.Replace("\\\"", "");
(As mentioned in the comments, this is because strings are immutable in .NET - once you've got a string object somehow, that string will always have the same contents. You can assign a reference to a different string to a variable of course, but that's not actually changing the contents of the existing string.)
Usually two arrays will have some small numeric errors,
You can use numpy.allclose(A,B)
, instead of (A==B).all()
. This returns a bool True/False
If I have much trouble finding a way through the corporate proxy, I connect to the web through my phone (wireless hotspot if I have wifi, USB tether if not) and do a quick pip install
.
Might not work for all setups, but should get most people by in a pinch.
Adding to above answers, we can create on the fly
df= pd.DataFrame()
list1 = list(range(10))
list2 = list(range(10,20))
df['list1'] = list1
df['list2'] = list2
print(df)
hope it helps !
TimeUnit
EnumThe following expression uses the TimeUnit
enum (Java 5 and later) to convert from nanoseconds to seconds:
TimeUnit.SECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS)
I was also looking for this, but didn't want to impersonate a user to simply acquire a path!
user_path=$(grep $username /etc/passwd|cut -f6 -d":");
Now in your script, you can refer to $user_path
in most cases would be /home/username
Assumes: You have previously set $username
with the value of the intended users username.
Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html
Bit is only advantageous over the various byte options (tinyint, enum, char(1)) if you have a lot of boolean fields. One bit field still takes up a full byte. Two bit fields fit into that same byte. Three, four,five, six, seven, eight. After which they start filling up the next byte. Ultimately the savings are so small, there are thousands of other optimizations you should focus on. Unless you're dealing with an enormous amount of data, those few bytes aren't going to add up to much. If you're using bit with PHP you need to typecast the values going in and out.
If you want to allow every bot to crawl everything, this is the best way to specify it in your robots.txt:
User-agent: *
Disallow:
Note that the Disallow
field has an empty value, which means according to the specification:
Any empty value, indicates that all URLs can be retrieved.
Your way (with Allow: /
instead of Disallow:
) works, too, but Allow
is not part of the original robots.txt specification, so it’s not supported by all bots (many popular ones support it, though, like the Googlebot). That said, unrecognized fields have to be ignored, and for bots that don’t recognize Allow
, the result would be the same in this case anyway: if nothing is forbidden to be crawled (with Disallow
), everything is allowed to be crawled.
However, formally (per the original spec) it’s an invalid record, because at least one Disallow
field is required:
At least one Disallow field needs to be present in a record.
You can do the whole thing using Integer math without needing to instantiate a calendar:
return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);
May be off for an hour or two at new year but I don't get the impression that is an issue?
Packets and Frames are the names given to Protocol data units (PDUs) at different network layers
Segments/Datagrams are units of data in the Transport Layer.
In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):
Datagram
A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.
Packets are units of data in the Network Layer (IP in case of the Internet)
Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).
A degree of control is possible over how information travels from a third-party website to Facebook when a page is shared (or liked, etc.). In order to make this possible, information is sent via Open Graph meta tags in the <head>
part of the website’s code.
The simple answer is to turn off async
. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.
Instead of writing this:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
}
});
}
function foo () {
var response = functABC();
some_result = bar(response);
// and other stuff and
return some_result;
}
You should write it like this:
function functABC(callback){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: callback
});
}
function foo (callback) {
functABC(function(data){
var response = data;
some_result = bar(response);
// and other stuff and
callback(some_result);
})
}
That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.
A quick explanation of why I say it's wrong to turn off async:
Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.
I just tried the same in EF6 (code first entity rename). I simply renamed the class and added a migration using the package manager console and voila, a migration using RenameTable(...) was automatically generated for me. I have to admit that I made sure the only change to the entity was renaming it so no new columns or renamed columns so I cannot be certain if this is an EF6 thing or just that EF was (always) able to detect such simple migrations.
cd /usr/local
git status
git status
til it's cleanbrew update
If you prefer an Integer[]
instead array of an int[]
array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
If you'd like to truncate a file to zero bytes, useful for clearing logs, try this:
:> file.log
def versiontuple(v):
return tuple(map(int, (v.split("."))))
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
False
On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.
<span ng-if="selectedItem==item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_active.png)',
'background-size':'52px 57px',
'padding-top':'70px',
'background-repeat':'no-repeat',
'background-position': 'center'}">
</span>
<span ng-if="selectedItem!=item.id"
ng-style="{'background-image':'url(../images/'+'{{item.id}}'+'_deactivated.png)',
'background-size':'52px 57px',
'padding-top':'70px',
'background-repeat':'no-repeat',
'background-position': 'center'}">
</span>
I believe the best way to view revisions is to use a program/app that makes it easy for you. I like to use trac : http://trac.edgewall.org/wiki/TracSubversion
It provides a great svn browser and makes it really easy to go back through your revisions.
It may be a little overkill to set this up for one specific revision you want to check, but it could be useful if you're going to do this a lot in the future.
mvn install:install-file -DgroupId=com.paic.maven -DartifactId=tplconfig-maven-plugin -Dversion=1.0 -Dpackaging=jar -Dfile=tplconfig-maven-plugin-1.0.jar -DgeneratePom=true
Install the jar to local repository.
With the official Material Components library you can use the MaterialButton
applying a Widget.MaterialComponents.Button.Icon
style.
Something like:
<com.google.android.material.button.MaterialButton
android:layout_width="48dp"
android:layout_height="48dp"
style="@style/Widget.MaterialComponents.Button.Icon"
app:icon="@drawable/ic_add"
app:iconSize="24dp"
app:iconPadding="0dp"
android:insetLeft="0dp"
android:insetTop="0dp"
android:insetRight="0dp"
android:insetBottom="0dp"
app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.MyApp.Button.Rounded"
/>
Currently the app:iconPadding="0dp"
,android:insetLeft
,android:insetTop
,android:insetRight
,android:insetBottom
attributes are needed to center the icon on the button avoiding extra padding space.
Use the app:shapeAppearanceOverlay
attribute to get rounded corners. In this case you will have a circle.
<style name="ShapeAppearanceOverlay.MyApp.Button.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">50%</item>
</style>
The final result:
CSS
li {
display: inline-block;
}
Works for me also.
It actually requires inclusion of Twitter Bootstrap's dropdown.js
#wrap {
min-height: 100%;
height: auto !important;
height: 100%;
width: 100%;
/*Negative indent footer by its height*/
margin: 0 auto -60px;
position: fixed;
left: 0;
top: 0;
}
The footer height matches the size of the bottom indent of the wrap element.
.footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 60px;
}
<head>_x000D_
_x000D_
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
_x000D_
_x000D_
$(function() {_x000D_
$( "#dialog" ).dialog({_x000D_
autoOpen: false,_x000D_
show: {_x000D_
effect: "blind",_x000D_
duration: 1000_x000D_
},_x000D_
hide: {_x000D_
effect: "explode",_x000D_
duration: 1000_x000D_
}_x000D_
});_x000D_
_x000D_
$( "#opener" ).click(function() {_x000D_
$( "#dialog" ).dialog( "open" );_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<div id="dialog" title="Basic dialog">_x000D_
<p>This is an animated dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>_x000D_
</div>_x000D_
_x000D_
<button id="opener">Open Dialog</button>_x000D_
_x000D_
</body>
_x000D_
With SQLDeveloper v19.1.0 on Windows, I found this as a JSON file in
C:\Users\<username>\AppData\Roaming\SQL Developer\system<versionNumber>\o.jdeveloper.db.connection
The file name is connections.json
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}
It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards
you can look for red shards.
I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.
It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head
Read-only locking sometimes happens on network drives with Windows. Try to disconnect and reconnect it again. Then cleanup and update.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
do this:
SELECT * FROM table ORDER BY column `name`+0 ASC
Appending the +0 will mean that:
0, 10, 11, 2, 3, 4
becomes :
0, 2, 3, 4, 10, 11
possibly not so many answers so thinking to share my code which can help someone
from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date
spark = SparkSession.builder.appName("Python Spark SQL basic example")\
.config("spark.some.config.option", "some-value").getOrCreate()
df = spark.createDataFrame([('2019-06-22',)], ['t'])
df1 = df.select(to_date(df.t, 'yyyy-MM-dd').alias('dt'))
print df1
print df1.show()
output
DataFrame[dt: date]
+----------+
| dt|
+----------+
|2019-06-22|
+----------+
the above code to convert to date if you want to convert datetime then use to_timestamp. let me know if you have any doubt.
As a response to your question: "i want to reset all the data and keep last 30 days inside the table."
you can create an event. Check https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html
For example:
CREATE EVENT DeleteExpiredLog
ON SCHEDULE EVERY 1 DAY
DO
DELETE FROM log WHERE date < DATE_SUB(NOW(), INTERVAL 30 DAY);
Will run a daily cleanup in your table, keeping the last 30 days data available
Starting with SQL Server 2016 we string_split
DECLARE @string varchar(100) = 'Richard, Mike, Mark'
SELECT value FROM string_split(@string, ',')
There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.
It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.
You would create a relationship with your User model and Messages Model, and use the containable behavior:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array('Message');
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array('User');
}
You need to change the messages.from
column to be messages.user_id
so that cake can automagically associate the records for you.
Then you can do this from the messages controller:
$this->Message->find('all', array(
'contain' => array('User')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController
:
$this->Message->find('all', array(
'joins' => array(
array(
'table' => 'users',
'alias' => 'UserJoin',
'type' => 'INNER',
'conditions' => array(
'UserJoin.id = Message.from'
)
)
),
'conditions' => array(
'Message.to' => 4
),
'fields' => array('UserJoin.*', 'Message.*'),
'order' => 'Message.datetime DESC'
));
Note, I've left the field name messages.from
the same as your current table in this example.
Here is how you can do the first example using two relationships to the same model:
class User extends AppModel {
public $actsAs = array('Containable');
public $hasMany = array(
'MessagesSent' => array(
'className' => 'Message',
'foreignKey' => 'from'
)
);
public $belongsTo = array(
'MessagesReceived' => array(
'className' => 'Message',
'foreignKey' => 'to'
)
);
}
class Message extends AppModel {
public $actsAs = array('Containable');
public $belongsTo = array(
'UserFrom' => array(
'className' => 'User',
'foreignKey' => 'from'
)
);
public $hasMany = array(
'UserTo' => array(
'className' => 'User',
'foreignKey' => 'to'
)
);
}
Now you can do your find call like this:
$this->Message->find('all', array(
'contain' => array('UserFrom')
'conditions' => array(
'Message.to' => 4
),
'order' => 'Message.datetime DESC'
));
You can use Spannable
to apply effects to your TextView
:
Here is my example for colouring just the first part of a TextView
text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)
Faced similar issue with my Angular Node Server(v6.10.3) which set up in WIndows 10.
http://localhost:4201
worked fine in localhost. But http://{ipaddress}:4201
not working in other machines in local network.
For this I updated the ng serve
like this
//Older ng serve in windows command Prompt
ng serve --host localhost --port 4201
//Updated ng serve
//ng serve --host {ipaddress} --port {portno}
ng serve --host 192.168.1.104 --port 4201
After doing this modification able to access my application in other machines in network bt calling this url
http://192.168.1.104:4201
//http://{ipaddress}:4201
You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.
Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.