var library = [_x000D_
{name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
{name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
{name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
];_x000D_
_x000D_
const sorted_by_name = library.sort( (a,b) => a.name > b.name );_x000D_
_x000D_
for(let k in sorted_by_name){_x000D_
console.log(sorted_by_name[k]);_x000D_
}
_x000D_
This one is a small one:
(([0-9A-F]{2}[:-]?){6})
Have in mind, that weird mix of several chars or separators could pass.
Swift 3
func getTime() -> (hour: Int, minute: Int,second: Int) {
let hour = 1
let minute = 20
let second = 55
return (hour, minute, second)
}
To use :
let(hour, min,sec) = self.getTime()
print(hour,min,sec)
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static:
Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.
I suggest you to see this tutorial list
AUTO:
C, C++
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
just go to add reference then add
system.net.http
updated asnwer for those people 'correctly' pointing out it doesnt directly answer the question, more bring an alternative option.
fs.existsSync('filePath')
also see docs here.
Returns true if the path exists, false otherwise.
In an async context you could just write the async version in sync method with using the await
keyword. You can simply turn the async callback method into an promise like this:
function fileExists(path){
return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,
(err, result) => err ? fail(err) : resolve(result))
//F_OK checks if file is visible, is default does no need to be specified.
}
async function doSomething() {
var exists = await fileExists('filePath');
if(exists){
console.log('file exists');
}
}
the docs on access().
BalusC said:
Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep().
But if you replace Thread.sleep(4000);
with for (int i = 0; i < 5E8; i++) {}
then it doesn't compile, because the empty loop doesn't throw an InterruptedException
.
And for the thread to be interruptible, it needs to throw an InterruptedException
.
This seems like a serious problem to me. I can't see how to adapt this answer to work with a general long-running task.
Edited to add: I reasked this as a new question: [ interrupting a thread after fixed time, does it have to throw InterruptedException? ]
Work-Break has nothing to do with inline-block
.
Make sure you specify width
and notice if there are any overriding attributes in parent nodes. Make sure there is not white-space: nowrap
.
see this codepen
<html>
<head>
</head>
<body>
<style scoped>
.parent {
width: 100vw;
}
p {
border: 1px dashed black;
padding: 1em;
font-size: calc(0.6vw + 0.6em);
direction: ltr;
width: 30vw;
margin:auto;
text-align:justify;
word-break: break-word;
white-space: pre-line;
overflow-wrap: break-word;
-ms-word-break: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
}
</style>
<div class="parent">
<p>
Note: Mind that, as for now, break-word is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to
the standard.
</p>
</div>
</body>
</html>
_x000D_
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
Try this one:
if(FALSE !== ($key = array_search($_GET['name'],$_SESSION['name'])))
{
unset($_SESSION['name'][$key]);
}
As Strings are immutable, when you do:
String a = "xyz"
while creating the string, the JVM searches in the pool of strings if there already exists a string value "xyz"
, if so 'a'
will simply be a reference of that string and no new String object is created.
But if you say:
String a = new String("xyz")
you force JVM to create a new String
reference, even if "xyz"
is in its pool.
For more information read this.
This answer took me forever to find as well. I discovered that all you have to do is concatenate the URL ('?' after the file name and extension) with the URL-encoded query string. It doesn't even look like you have to set the POST cURL options. See the fake example below:
//create URL
$exampleURL = 'http://www.example.com/example.php?';
// create curl resource
$ch = curl_init();
// build URL-encoded query string
$data = http_build_query(
array('first' => 'John', 'last' => 'Smith', '&'); // set url
curl_setopt($ch, CURLOPT_URL, $exampleURL . $data);
// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources <br/>
curl_close($ch);
You can also use file_get_contents()
:
// read entire webpage file into a string
$output = file_get_contents($exampleURL . $data);
I have had an experience using Ctrl + Alt + L in Windows that this shortcut did not work at all because it was reserved by another software, running at the background; which I realized later.
I decided to mention this issue as I thought it may be helpful . . .
root@h1:bin[0]# mount h2:/ /x
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#
ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok
Just to suggest an alternative that does not involve the need to manually invoke a listener event:
Whatever your event listener does, move it into a function and call that function from the event listener.
Then, you can also call that function anywhere else that you need to accomplish the same thing that the event does when it fires.
I find this less "code intensive" and easier to read.
Ok you can use this simply
-webkit-text-stroke-width: .7px;
-webkit-text-stroke-color: #34343b;
-webkit-font-smoothing:antialiased;
Make sure your text color and upper text-stroke-width must me same and that's it.
sed
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed
command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated in a single workflow when a Makefile
with build instructions is employed.
PS: This answer was written at a time when extension link_attributes
was not yet available in Pandoc.
You can create a style,
<style name="noAnimTheme" parent="android:Theme">
<item name="android:windowAnimationStyle">@null</item>
</style>
and set it as theme for your activity in the manifest:
<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>
You can also define a style to specify custom entry and exit animations. http://developer.android.com/reference/android/R.attr.html#windowEnterAnimation
The method Louis's answer, as a String
prototype function:
String.prototype.splice = function(index, count, add) {
if (index < 0) {
index = this.length + index;
if (index < 0) {
index = 0;
}
}
return this.slice(0, index) + (add || "") + this.slice(index + count);
}
Example:
> "Held!".splice(3,0,"lo Worl")
< "Hello World!"
I come across this error often when I import a new project in my workspace.
Reason: Some necessary files (Like R.Java
) is not generated in its respective packages.
Cure: Clean and build projects, All the files that needs to be auto generated will be there on place after building the project.
Best Luck.
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
With Java8 there is a default sort method on the List interface that will allow you to sort the collection if you provide a Comparator. You can easily sort the example in the question as follows:
testList.sort((a, b) -> Double.compare(b, a));
Note: the args in the lambda are swapped when passed in to Double.compare to ensure the sort is descending
In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:
<div class="container">
<div class="row">
<img class='img-fluid w-100' src="#" alt="" />
</div>
</div>
see closed issue: https://github.com/twbs/bootstrap/issues/20830
(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)
useEffect
can hook on a certain prop or state. so, the thing you need to do to avoid infinite loop hook is binding some variable or state to effect
For Example:
useEffect(myeffectCallback, [])
above effect will fire only once the component has rendered. this is similar to componentDidMount
lifecycle
const [something, setSomething] = withState(0)
const [myState, setMyState] = withState(0)
useEffect(() => {
setSomething(0)
}, myState)
above effect will fire only my state has changed this is similar to componentDidUpdate
except not every changing state will fire it.
You can read more detail though this link
<textarea name="hide" style="display:none;"></textarea>
This sets the css display
property to none
, which prevents the browser from rendering the textarea.
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.
Note that there isn't a list of all the different how
options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how
by name.
You can use axe selectors for this.
There are two approaches:
<
)#a:hover < #content + #b
This axe style rule will select #b
, which is the immediate sibling of #content
, which is the immediate parent of #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover < #content + #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
\
)#a:hover \ #b
This axe style rule will select #b
, which is present in the same document as #a
which has a :hover
state.
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}
#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}
#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}
#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}
#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}
#a:hover \ #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>
<div id="b">Show me</div>
<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
--DROP TABLE #Employee
CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)
INSERT INTO #Employee VALUES('M11M','Manager',NULL)
INSERT INTO #Employee VALUES('P11P','Manager',NULL)
INSERT INTO #Employee VALUES('AA','Clerk',1)
INSERT INTO #Employee VALUES('AB','Assistant',1)
INSERT INTO #Employee VALUES('ZC','Supervisor',2)
INSERT INTO #Employee VALUES('ZD','Security',2)
SELECT * FROM #Employee (NOLOCK)
;
WITH Emp_CTE
AS
(
SELECT EmpId,EmpName,Designation, ManagerID
,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
FROM #Employee
)
select EmpId,EmpName,Designation, ManagerID
FROM Emp_CTE
order BY ManagerID_N, EmpId
You can use sprintf: http://php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>
It will only add the zero if it's less than the required number of characters.
Edit: As pointed out by @FelipeAls:
When working with numbers, you should use %d
(rather than %s
), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.
For example:
sprintf("%04s", 10);
returns 0010
sprintf("%04s", -10);
returns 0-10
Where as:
sprintf("%04d", 10);
returns 0010
sprintf("%04d", -10);
returns -010
It is actually possible only using CSS, however, the image you use to replace must be the same size as the original facebook log in button. Fortunately Facebook delivers the button in different sizes.
From facebook:
size - Different sized buttons: small, medium, large, xlarge - the default is medium. https://developers.facebook.com/docs/reference/plugins/login/
Set the login iframe opacity to 0 and show a background image in the parent div
.fb_iframe_widget iframe {
opacity: 0;
}
.fb_iframe_widget {
background-image: url(another-button.png);
background-repeat: no-repeat;
}
If you use an image that is bigger than the original facebook button, the part of the image that is outside the width and height of the original button will not be clickable.
It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!
The only times you should need to escape are when trying to put "
inside a string, or '
in a character:
String quotes = "He said \"Hello, World!\"";
char quote = '\'';
my solution inspired from Aras Alenin answer above where I added one level of object comparison and a custom object for comparison results. I am also interested to get property name with object name:
public static IEnumerable<ObjectPropertyChanged> GetPublicSimplePropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored) where T : class
{
return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, true, null, null);
}
public static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored) where T : class
{
return GetPublicGenericPropertiesChanged(previous, proposedChange, namesOfPropertiesToBeIgnored, false, null, null);
}
/// <summary>
/// Gets the names of the public properties which values differs between first and second objects.
/// Considers 'simple' properties AND for complex properties without index, get the simple properties of the children objects.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="previous">The previous object.</param>
/// <param name="proposedChange">The second object which should be the new one.</param>
/// <param name="namesOfPropertiesToBeIgnored">The names of the properties to be ignored.</param>
/// <param name="simpleTypeOnly">if set to <c>true</c> consider simple types only.</param>
/// <param name="parentTypeString">The parent type string. Meant only for recursive call with simpleTypeOnly set to <c>true</c>.</param>
/// <param name="secondType">when calling recursively, the current type of T must be clearly defined here, as T will be more generic (using base class).</param>
/// <returns>
/// the names of the properties
/// </returns>
private static IReadOnlyList<ObjectPropertyChanged> GetPublicGenericPropertiesChanged<T>(this T previous, T proposedChange,
string[] namesOfPropertiesToBeIgnored, bool simpleTypeOnly, string parentTypeString, Type secondType) where T : class
{
List<ObjectPropertyChanged> propertiesChanged = new List<ObjectPropertyChanged>();
if (previous != null && proposedChange != null)
{
var type = secondType == null ? typeof(T) : secondType;
string typeStr = parentTypeString + type.Name + ".";
var ignoreList = namesOfPropertiesToBeIgnored.CreateList();
IEnumerable<IEnumerable<ObjectPropertyChanged>> genericPropertiesChanged =
from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
where !ignoreList.Contains(pi.Name) && pi.GetIndexParameters().Length == 0
&& (!simpleTypeOnly || simpleTypeOnly && pi.PropertyType.IsSimpleType())
let firstValue = type.GetProperty(pi.Name).GetValue(previous, null)
let secondValue = type.GetProperty(pi.Name).GetValue(proposedChange, null)
where firstValue != secondValue && (firstValue == null || !firstValue.Equals(secondValue))
let subPropertiesChanged = simpleTypeOnly || pi.PropertyType.IsSimpleType()
? null
: GetPublicGenericPropertiesChanged(firstValue, secondValue, namesOfPropertiesToBeIgnored, true, typeStr, pi.PropertyType)
let objectPropertiesChanged = subPropertiesChanged != null && subPropertiesChanged.Count() > 0
? subPropertiesChanged
: (new ObjectPropertyChanged(proposedChange.ToString(), typeStr + pi.Name, firstValue.ToStringOrNull(), secondValue.ToStringOrNull())).CreateList()
select objectPropertiesChanged;
if (genericPropertiesChanged != null)
{ // get items from sub lists
genericPropertiesChanged.ForEach(a => propertiesChanged.AddRange(a));
}
}
return propertiesChanged;
}
Using the following class to store comparison results
[System.Serializable]
public class ObjectPropertyChanged
{
public ObjectPropertyChanged(string objectId, string propertyName, string previousValue, string changedValue)
{
ObjectId = objectId;
PropertyName = propertyName;
PreviousValue = previousValue;
ProposedChangedValue = changedValue;
}
public string ObjectId { get; set; }
public string PropertyName { get; set; }
public string PreviousValue { get; set; }
public string ProposedChangedValue { get; set; }
}
And a sample unit test:
[TestMethod()]
public void GetPublicGenericPropertiesChangedTest1()
{
// Define objects to test
Function func1 = new Function { Id = 1, Description = "func1" };
Function func2 = new Function { Id = 2, Description = "func2" };
FunctionAssignment funcAss1 = new FunctionAssignment
{
Function = func1,
Level = 1
};
FunctionAssignment funcAss2 = new FunctionAssignment
{
Function = func2,
Level = 2
};
// Main test: read properties changed
var propertiesChanged = Utils.GetPublicGenericPropertiesChanged(funcAss1, funcAss2, null);
Assert.IsNotNull(propertiesChanged);
Assert.IsTrue(propertiesChanged.Count == 3);
Assert.IsTrue(propertiesChanged[0].PropertyName == "FunctionAssignment.Function.Description");
Assert.IsTrue(propertiesChanged[1].PropertyName == "FunctionAssignment.Function.Id");
Assert.IsTrue(propertiesChanged[2].PropertyName == "FunctionAssignment.Level");
}
I find this type of approach works for me:
Product ProductDetail Country ========= ================== ========= ProductId ProductDetailId CountryId - etc - ProductId CountryName CountryId Language ProductName - etc - ProductDescription - etc -
The ProductDetail table holds all the translations (for product name, description etc..) in the languages you want to support. Depending on your app's requirements, you may wish to break the Country table down to use regional languages too.
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Well if you know the basics behind them, it shouldn't be too hard.
Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.
When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.
Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).
Check out this fast hash table implementation:
This code may be helpful for you.
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()
I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it
example:
Library ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error was resolved only after specifying the complete path, as it was not getting the callable function.
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:
div.hardware-accelarate {
-webkit-transform: translate3d(0,0,0);
-moz-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
-o-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
I've made a plunkr setup for ya'll to test and tweak...
Get the keys in the first for
loop, sort it, use the sorted result in the 2nd for
loop.
var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;
var b = [];
for (k in a) b.push(k);
b.sort();
for (var i = 0; i < b.length; ++i) alert(b[i]);
I'm going to give you the answers from what I've just went through on Windows Server 2008 R2 which is a 64 bit operating system. The application suite of libraries I was given were developed using .net 3.5 x86 with the older DLL libraries and I was stuck because I had installed the newer x64 clients from oracle.
What I found was the following: Install the latest x64 client from Oracle for Windows Server 2008. I believe this would be the 2.7.0 client. When you select the installation, make sure you do custom and select the .NET libraries. Configure your tnsnames files and test your tnsping against your data source.
Next, if you are running a 32 bit application, install the same version of the client for 32 bit. Also, follow the same installation routine, and select the same home.
When your finished, you will find that you have a single app/product with two client directories (Client1 and Client2).
If you navigate to the windows/assemblies directory you will find that you have a reference to the Oracle.DataAccess.dll (x2) with one for x86 and one for AMD64.
Now, depending on if you have developers or are developing on the machine yourself, you may be ok here, however, if they are using older drivers, then you need to perform one last step.
Navigate to the app\name\product\version\client_1\odp.net\publisher policy\2.x directory. Included in here are two policy files. use gacutil /i to install the Policy.2.111.Oracle.DataAccess.dll into the GAC. This will redirect legacy oracle ODP calls to the newer versions. So, if someone developed with the 10g client, it will now work with the 11 client.
FYI -- Some may be installing the latest ODP.NET with the 2.111.7.20. The main oracle client itself comes with 2.111.7.0 .. I've not had any success with the 7.20 but have no issues with the 7.0 client.
Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.
Declare @ErrorCode int;
... perform stuff ...
Set @ErrorCode = @@ERROR;
... other stuff ...
if @ErrorCode ......
Is this what you are looking for.
$("input.address_field").on('click', function(){
$(this).css('border', '2px solid red');
});
?So if you use pipeline, it would close all other streams and make sure that there are no memory leaks.
Working example:
const http = require('http'); const { pipeline } = require('stream'); const fs = require('fs'); const file = fs.createWriteStream('./file.jpg'); http.get('http://via.placeholder.com/150/92c952', response => { pipeline( response, file, err => { if (err) console.error('Pipeline failed.', err); else console.log('Pipeline succeeded.'); } ); });
From my answer to "What's the difference between .pipe and .pipeline on streams".
The problem is that a link to a closed file works with index( but not with index(indirect(
It seems to me that it is a programming issue of the index function. I solved it with a if clause row
C2=sheetname
if(c2=Sheet1,index(sheet1....),if(C2="Sheet2",index(sheet2....
I did it over five sheets, it's a long formula, but does what I need.
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
Amazon S3 does not have folders/directories. It is a flat file structure.
To maintain the appearance of directories, path names are stored as part of the object Key (filename). For example:
images/foo.jpg
In this case, the whole Key is images/foo.jpg
, rather than just foo.jpg
.
I suspect that your problem is that boto
is returning a file called my_folder/.8Df54234
and is attempting to save it to the local filesystem. However, your local filesystem interprets the my_folder/
portion as a directory name, and that directory does not exist on your local filesystem.
You could either truncate the filename to only save the .8Df54234
portion, or you would have to create the necessary directories before writing files. Note that it could be multi-level nested directories.
An easier way would be to use the AWS Command-Line Interface (CLI), which will do all this work for you, eg:
aws s3 cp --recursive s3://my_bucket_name local_folder
There's also a sync
option that will only copy new and modified files.
To use session variables, it's necessary to start the session by using the session_start
function, this will allow you to store your data in the global variable $_SESSION
in a productive way.
so your code will finally look like this :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// starting the session
session_start();
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
<strong><?php echo $_SESSION['picturenum'];?></strong>
to make it easy to use and to avoid forgetting it again, you can create a session_file.php
which you will want to be included in all your codes and will start the session for you:
session_start.php
<?php
session_start();
?>
and then include it wherever you like :
<strong>Test Form</strong>
<form action="" method"post">
<input type="text" name="picturenum"/>
<input type="submit" name="Submit" value="Submit!" />
</form>
<?php
// including the session file
require_once("session_start.php");
if (isset($_POST['Submit'])) {
$_SESSION['picturenum'] = $_POST['picturenum'];
}
?>
that way it is more portable and easy to maintain in the future.
other remarks
if you are using Apache version 2 or newer, be careful. instead of
<?
to open php's tags, use
<?php
, otherwise your code will not be interpreted
variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters
good work!
Another way to do this is by using a "configure" script. If you are already using one with your makefile, you can use a combination of uname and sed to get things to work out. First, in your script, do:
UNAME=uname
Then, in order to put this in your Makefile, start out with Makefile.in which should have something like
UNAME=@@UNAME@@
in it.
Use the following sed command in your configure script after the UNAME=uname
bit.
sed -e "s|@@UNAME@@|$UNAME|" < Makefile.in > Makefile
Now your makefile should have UNAME
defined as desired. If/elif/else statements are all that's left!
The DataTable.Clone()
method works great when you want to create a completely new DataTable, but there might be cases where you would want to add the schema columns from one DataTable to another existing DataTable.
For example, if you've derived a new subclass from DataTable, and want to import schema information into it, you couldn't use Clone().
E.g.:
public class CoolNewTable : DataTable {
public void FillFromReader(DbDataReader reader) {
// We want to get the schema information (i.e. columns) from the
// DbDataReader and
// import it into *this* DataTable, NOT a new one.
DataTable schema = reader.GetSchemaTable();
//GetSchemaTable() returns a DataTable with the columns we want.
ImportSchema(this, schema); // <--- how do we do this?
}
}
The answer is just to create new DataColumns in the existing DataTable using the schema table's columns as templates.
I.e. the code for ImportSchema would be something like this:
void ImportSchema(DataTable dest, DataTable source) {
foreach(var c in source.Columns)
dest.Columns.Add(c);
}
or, if you're using Linq:
void ImportSchema(DataTable dest, DataTable source) {
var cols = source.Columns.Cast<DataColumn>().ToArray();
dest.Columns.AddRange(cols);
}
This was just one example of a situation where you might want to copy schema/columns from one DataTable into another one without using Clone() to create a completely new DataTable. I'm sure I've come across several others as well.
Use Dictionary Items:
{% for key, value in my_dictionay.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
Suggest use Apache IOUtils.readLines for this. See link below.
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
I think the keystore file you want to use has a different or unsupported format in respect to your Java version. Could you post some more info of your task?
In general, to solve this issue you might need to recreate the whole keystore (using some other JDK version for example). In export-import the keys between the old and the new one - if you manage to open the old one somewhere else.
If it is simply an unsupported version, try the BouncyCastle crypto provider for example (although I'm not sure If it adds support to Java for more keystore types?).
Edit: I looked at the feature spec of BC.
Open the path/to/your/rails/project/tmp/pids/server.pid
file.
Copy the number you find therein.
Run kill -9 [PID]
Where [PID]
is the number you copied from the server.pid
file.
This will kill the running server process and you can start your server again without any trouble.
I have created a working CodePen example to demonstrate how you might accomplish your goals.
I added ng-click
to the <form>
and removed the logic from your button:
<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />
Here's the updated template:
<section ng-app="app" ng-controller="MainCtrl">
<form class="well" name="addRelation" data-ng-click="save(model)">
<label>First Name</label>
<input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
<label>Last Name</label>
<input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
<label>Email</label>
<input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
<span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
<input class="btn" type="submit" value="SAVE" />
</form>
</section>
and controller code:
app.controller('MainCtrl', function($scope) {
$scope.save = function(model) {
$scope.addRelation.submitted = true;
if($scope.addRelation.$valid) {
// submit to db
console.log(model);
} else {
console.log('Errors in form data');
}
};
});
I hope this helps.
When comparing only the date of the datatimes, use the Date property. So this should work fine for you
datetime1.Date == datetime2.Date
Using -s
option will print output of all functions, which may be too much.
If you need particular output, the doc page you mentioned offers few suggestions:
Insert assert False, "dumb assert to make PyTest print my stuff"
at the end of your function, and you will see your output due to failed test.
You have special object passed to you by PyTest, and you can write the output into a file to inspect it later, like
def test_good1(capsys):
for i in range(5):
print i
out, err = capsys.readouterr()
open("err.txt", "w").write(err)
open("out.txt", "w").write(out)
You can open the out
and err
files in a separate tab and let editor automatically refresh it for you, or do a simple py.test; cat out.txt
shell command to run your test.
That is rather hackish way to do stuff, but may be it is the stuff you need: after all, TDD means you mess with stuff and leave it clean and silent when it's ready :-).
Rather than defining contact_email
within app.config
, define it in a parameters
entry:
parameters:
contact_email: [email protected]
You should find the call you are making within your controller now works.
I usually get it from the toString() return value. It works in differently accessed DOM elements:
var a = document.querySelector('a');
var img = document.createElement('img');
document.body.innerHTML += '<div id="newthing"></div>';
var div = document.getElementById('newthing');
Object.prototype.toString.call(a); // "[object HTMLAnchorElement]"
Object.prototype.toString.call(img); // "[object HTMLImageElement]"
Object.prototype.toString.call(div); // "[object HTMLDivElement]"
Then the relevant piece:
Object.prototype.toString.call(...).split(' ')[1].slice(0, -1);
It works in Chrome, FF, Opera, Edge, IE9+ (in older IE it return "[object Object]").
Message queues are ideal for requests which may take a long time to process. Requests are queued and can be processed offline without blocking the client. If the client needs to be notified of completion, you can provide a way for the client to periodically check the status of the request.
Message queues also allow you to scale better across time. It improves your ability to handle bursts of heavy activity, because the actual processing can be distributed across time.
Note that message queues and web services are orthogonal concepts, i.e. they are not mutually exclusive. E.g. you can have a XML based web service which acts as an interface to a message queue. I think the distinction your looking for is Message Queues versus Request/Response, the latter is when the request is processed synchronously.
As of API 26, getDeviceId() is deprecated. If you need to get the IMEI of the device, use the following:
String deviceId = "";
if (Build.VERSION.SDK_INT >= 26) {
deviceId = getSystemService(TelephonyManager.class).getImei();
}else{
deviceId = getSystemService(TelephonyManager.class).getDeviceId();
}
var text = "" &<>";
text = text.replaceHtmlEntites();
String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt" : "<","gt" : ">"};
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
};
try this.....this worked for me
Another simple alternative:
for name_of_the_group, group in grouped_dataframe:
print (name_of_the_group)
print (group)
Try this:
<td bgcolor="#FFFFFF" style="line-height:10px;" colspan=3> </td>
Use RETURN QUERY
:
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text -- also visible as OUT parameter inside function
, cnt bigint
, ratio bigint) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt
, count(*) AS cnt -- column alias only visible inside
, (count(*) * 100) / _max_tokens -- I added brackets
FROM (
SELECT t.txt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
LIMIT _max_tokens
) t
GROUP BY t.txt
ORDER BY cnt DESC; -- potential ambiguity
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM word_frequency(123);
Explanation:
It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE
is one way to do that. There are others. Data types of OUT
parameters have to match exactly what is returned by the query.
Choose names for OUT
parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.
But note the potential naming conflict between the OUT
parameter cnt
and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...
) Postgres uses the column alias over the OUT
parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:
ORDER BY 2 DESC
. Example:
ORDER BY count(*)
.plpgsql.variable_conflict
or use the special command #variable_conflict error | use_variable | use_column
in the function. See:
Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt
and cnt
in my examples.
Added a missing ;
and corrected a syntax error in the header. (_max_tokens int)
, not (int maxTokens)
- type after name.
While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric
(or a floating point type). See below.
This is what I think your query should actually look like (calculating a relative share per token):
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (txt text
, abs_cnt bigint
, relative_share numeric) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt, t.cnt
, round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share
FROM (
SELECT t.txt, count(*) AS cnt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
GROUP BY t.txt
ORDER BY cnt DESC
LIMIT _max_tokens
) t
ORDER BY t.cnt DESC;
END
$func$ LANGUAGE plpgsql;
The expression sum(t.cnt) OVER ()
is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.
A final explicit RETURN
statement is not required (but allowed) when working with OUT
parameters or RETURNS TABLE
(which makes implicit use of OUT
parameters).
round()
with two parameters only works for numeric
types. count()
in the subquery produces a bigint
result and a sum()
over this bigint
produces a numeric
result, thus we deal with a numeric
number automatically and everything just falls into place.
You can use forget method on the widget
from tkinter import * root = Tk() b = Button(root, text="Delete me", command=b.forget) b.pack() b['command'] = b.forget root.mainloop()
You could try something like this:
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double[] numbers = new double[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextDouble();
}
}
It seems pretty basic stuff unless I am misunderstanding you
I believe that what you really want to do is: let's imagine a scenario you have two database and they have a table of products in common And you want to select products from the table "A" that id has in common with the "B"
using the method contains would be too complicated to do this what we are doing is an intersection, and there is a method called intersection for that
an example from msdn: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1
int [] numbers = (0, 2, 4, 5, 6, 8, 9); int [] numbersB = (1, 3, 5, 7, 8); var = commonNumbers numbersA.Intersect (numbersB);
I think what you need is easily solved with intersection
First of all, the stack pointer points to the bottom of the stack since x86 stacks build from high address values to lower address values. The stack pointer is the point where the next call to push (or call) will place the next value. It's operation is equivalent to the C/C++ statement:
// push eax
--*esp = eax
// pop eax
eax = *esp++;
// a function call, in this case, the caller must clean up the function parameters
move eax,some value
push eax
call some address // this pushes the next value of the instruction pointer onto the
// stack and changes the instruction pointer to "some address"
add esp,4 // remove eax from the stack
// a function
push ebp // save the old stack frame
move ebp, esp
... // do stuff
pop ebp // restore the old stack frame
ret
The base pointer is top of the current frame. ebp generally points to your return address. ebp+4 points to the first parameter of your function (or the this value of a class method). ebp-4 points to the first local variable of your function, usually the old value of ebp so you can restore the prior frame pointer.
To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. Replace DBNAME with the database name:
ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;
Fuel UX combobox has all the features you would expect.
In recent Visual Studio Code versions you can find settings here:
Menu File → Preference → Settings → Text Editor → Files → (scroll down a bit) Trim Trailing Whitespace
This is for trimming whitespace when saving a file.
Or you can search "Trim Trailing Whitespace" in the top search bar.
This will trim off any combination of carriage returns and newlines from the end of s
:
s = s.TrimEnd(new char[] { '\r', '\n' });
Edit: Or as JP kindly points out, you can spell that more succinctly as:
s = s.TrimEnd('\r', '\n');
<div class='block1'>
<p style="float:left">text</p>
<div class='block2' style="float:right">block2</div>
<p style="float:left; clear:left">text2</p>
</div>
You can clear:both
or clear:left
depending on the exact context.
Also, you will have to play around with width
to get it to work correctly...
Also you can use DownloadFileAsync
method in WebClient
class. It downloads to a local file the resource with the specified URI
. Also this method does not block the calling thread.
Sample:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
For more information:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
You can try out my implementation of a self-expiring hash map. This implementation does not make use of threads to remove expired entries, instead it uses DelayQueue that is cleaned up at every operation automatically.
Use jquery starts with attribute selector
$('[id^=editDialog]')
Alternative solution - 1 (highly recommended)
A cleaner solution is to add a common class to each of the divs & use
$('.commonClass')
.
But you can use the first one if html markup is not in your hands & cannot change it for some reason.
Alternative solution - 2 (not recommended if n is a large number
)
(as per @Mihai Stancu's suggestion)
$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')
Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.
To be honest I don't know that you can. If you just set up a test instance and open Excel twice, because that is what you are talking about happening, if you name one workbook "test1" and another "test2" if you try to move a workbook, or even a worksheet between the two applications they are totally unaware of each other. I also notice odd behavior while simply manually cutting and pasting from Excel instance 1 and Excel instance 2.
You may have to write two macros kind of a drop off and then a pick up from a location that you share between them. Maybe a command button on the tool bar.
Maybe one of the super excel guys on here have a better answer.
distcc can also be used to distribute compiles not only on the current machine, but also on other machines in a farm that have distcc installed.
variable
- named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable
, instance variable
, local variable
, method parameter
//pattern
<Java_type> <name> ;
//for example
int myInt;
String myString;
CustomClass myCustomClass;
field
- member variable or data member. It is a variable
inside a class
(class variable
or instance variable
)
attribute
- in some articles you can find that attribute
it is an object
representation of class variable
. Object
operates by attributes
which define a set of characteristics.
CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
property
- field
+ bounded getter/setter
. It has a field syntax but uses methods under the hood. Java
does not support it in pure form. Take a look at Objective-C
, Swift
, Kotlin
For example Kotlin
sample:
//field - Backing Field
class Person {
var name: String = "default name"
get() = field
set(value) { field = value }
}
//using
val person = Person()
person.name = "Alex" // setter is used
println(person.name) // getter is used
I have been searching far and wide in the internet.
I'm using Python 3.6 and MacOS. I have uninstalled and installed with pip3 install bs4
but that didn't work. It seems like python is not able to detect or search the bs4
module.
This is what worked:
python3 -m pip install bs4
The -m
option allows you to add a module name.
IllegalStateException is encountered if you commit any fragment transaction after the activity has lost its state- Activity is not in foreground. This is commonly encountered when you try to commit any fragment in AsyncTask or after a network request.
To avoid this crash you just need to delay any fragment transaction untill the state of activity is restored. Following is how it is done
Declare two private boolean variables
public class MainActivity extends AppCompatActivity {
//Boolean variable to mark if the transaction is safe
private boolean isTransactionSafe;
//Boolean variable to mark if there is any transaction pending
private boolean isTransactionPending;
Now in onPostResume() and onPause we set and unset our boolean variable isTransactionSafe. Idea is to mark trasnsaction safe only when the activity is in foreground so there is no chance of stateloss.
/*
onPostResume is called only when the activity's state is completely restored. In this we will
set our boolean variable to true. Indicating that transaction is safe now
*/
public void onPostResume(){
super.onPostResume();
isTransactionSafe=true;
}
/*
onPause is called just before the activity moves to background and also before onSaveInstanceState. In this
we will mark the transaction as unsafe
*/
public void onPause(){
super.onPause();
isTransactionSafe=false;
}
private void commitFragment(){
if(isTransactionSafe) {
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame, myFragment);
fragmentTransaction.commit();
}
}
What we have done so far will save from IllegalStateException but our transactions will be lost if they are done after the activity moves to background, kind of like commitAllowStateloss(). To help with that we have isTransactionPending boolean variable
public void onPostResume(){
super.onPostResume();
isTransactionSafe=true;
/* Here after the activity is restored we check if there is any transaction pending from
the last restoration
*/
if (isTransactionPending) {
commitFragment();
}
}
private void commitFragment(){
if(isTransactionSafe) {
MyFragment myFragment = new MyFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frame, myFragment);
fragmentTransaction.commit();
isTransactionPending=false;
}else {
/*
If any transaction is not done because the activity is in background. We set the
isTransactionPending variable to true so that we can pick this up when we come back to
foreground
*/
isTransactionPending=true;
}
}
This article explains quite in detail of why this exception is encountered and compares various methods to resolve it . Highly recommended
You can use the string formatting operator as so:
num = 49
x = "%.2f" % num # x is now the string "49.00"
I'm not sure what you mean by "efficient" -- this is almost certainly not the bottleneck of your application. If your program is running slowly, profile it first to find the hot spots, and then optimize those.
Try this:
ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"
It could be that the plugin is case-sensitive. Try inputting Te
instead of te
. You can probably have your results setup to not be case-sensitive. This question might help.
For a custom sort function on an Array
, you can use any JavaScript function and pass it as parameter to an Array
's sort()
method like this:
var array = ['White 023', 'White', 'White flower', 'Teatr'];_x000D_
_x000D_
array.sort(function(x, y) {_x000D_
if (x < y) {_x000D_
return -1;_x000D_
}_x000D_
if (x > y) {_x000D_
return 1;_x000D_
}_x000D_
return 0;_x000D_
});_x000D_
_x000D_
// Teatr White White 023 White flower_x000D_
document.write(array);
_x000D_
Where str could be any of these formarts: 555-555-5555 (555)555-5555 (555) 555-5555 555 555 5555 5555555555 1 555 555 5555
function telephoneCheck(str) {_x000D_
var isphone = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);_x000D_
alert(isphone);_x000D_
}_x000D_
telephoneCheck("1 555 555 5555");
_x000D_
DECLARE @str varchar(150)
SET @str='Hello My name is Jiyaul mustafa'
Select REPLACE(REPLACE(REPLACE(@str,' ','{}'),'}{',''),'{}',' ')
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Missing from the other answers is how to allow localhost(or 0.0.0.0 or whatever) as an oauth callback url. Here is the explanation. How can I add localhost:3000 to Facebook App for development
Reg file
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Console]
"CodePage"=dword:fde9
Command Prompt
REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 0xfde9
PowerShell
sp -t d HKCU:\Console CodePage 0xfde9
Cygwin
regtool set /user/Console/CodePage 0xfde9
Here's an example...
static class Program
{
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hWnd);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
{
SetForegroundWindow(proc.MainWindowHandle);
SendKeys.SendWait("{F5}");
}
Thread.Sleep(5000);
}
}
}
a better one... less anoying...
static class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const int VK_F5 = 0x74;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[STAThread]
static void Main()
{
while(true)
{
Process [] processes = Process.GetProcessesByName("iexplore");
foreach(Process proc in processes)
PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);
Thread.Sleep(5000);
}
}
}
For anyone using Windows 10 and nothing else working for him/her:
In my case, I had to clone the repo with https instead of ssh and a window popped-up asking for my credentials. After that everything works fine.
As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives
wrap the first searched character in a character class
ps -ef | grep '[t]omcat'
This searches for tomcat too, but misses the grep [t]omcat
entry, because it isn't matched by [t]omcat
.
use a custom output format with ps
ps -e -o pid,comm | grep tomcat
This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep
and not as grep tomcat
.
Instead of
css=#container
use
css=div.container:nth-of-type(1),css=div.container:nth-of-type(2)
Use
Model.created_at.strftime("%FT%T")
where,
%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)
Following are some of the frequently used useful list of Date
and Time
formats that you could specify in strftime
method:
Date (Year, Month, Day):
%Y - Year with century (can be negative, 4 digits at least)
-0001, 0000, 1995, 2009, 14292, etc.
%C - year / 100 (round down. 20 in 2009)
%y - year % 100 (00..99)
%m - Month of the year, zero-padded (01..12)
%_m blank-padded ( 1..12)
%-m no-padded (1..12)
%B - The full month name (``January'')
%^B uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
%^b uppercased (``JAN'')
%h - Equivalent to %b
%d - Day of the month, zero-padded (01..31)
%-d no-padded (1..31)
%e - Day of the month, blank-padded ( 1..31)
%j - Day of the year (001..366)
Time (Hour, Minute, Second, Subsecond):
%H - Hour of the day, 24-hour clock, zero-padded (00..23)
%k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
%I - Hour of the day, 12-hour clock, zero-padded (01..12)
%l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
%P - Meridian indicator, lowercase (``am'' or ``pm'')
%p - Meridian indicator, uppercase (``AM'' or ``PM'')
%M - Minute of the hour (00..59)
%S - Second of the minute (00..59)
%L - Millisecond of the second (000..999)
%N - Fractional seconds digits, default is 9 digits (nanosecond)
%3N millisecond (3 digits)
%6N microsecond (6 digits)
%9N nanosecond (9 digits)
%12N picosecond (12 digits)
For the complete list of formats for strftime
method please visit APIDock
Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.
The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Add
PATH = C:\Program Files\Java\jdk1.8.0_66\bin
in Advanced system setting
. Then Choose Environment Variable.
If I run the following:
echo '<?php echo $foo; ?>' | php
I get an error:
PHP Notice: Undefined variable: foo in /home/altern8/- on line 1
If I run the following:
echo '<?php if ( isset($foo) ) { echo $foo; } ?>' | php
I do not get the error.
If I have a variable that should be set, I usually do something like the following.
$foo = isset($foo) ? $foo : null;
or
if ( ! isset($foo) ) $foo = null;
That way, later in the script, I can safely use $foo and know that it "is set", and that it defaults to null. Later I can if ( is_null($foo) ) { /* ... */ }
if I need to and know for certain that the variable exists, even if it is null.
The full isset documentation reads a little more than just what was initially pasted. Yes, it returns false for a variable that was previously set but is now null, but it also returns false if a variable has not yet been set (ever) and for any variable that has been marked as unset. It also notes that the NULL byte ("\0") is not considered null and will return true.
Determine whether a variable is set.
If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP NULL constant.
I know this is old, but I was having this same issue, found this post, and while it didn't explain exactly what was wrong, it helped me to the right answer - so hopefully my answer helps someone else who might be having a similar problem to mine.
I had an element I wanted rotated vertical, so naturally I added the filter: for IE8 and then the -ms-transform property for IE9. What I found is that having the -ms-transform property AND the filter applied to the same element causes IE9 to render the element very poorly. My solution:
If you are using the transform-origin property, add one for MS too (-ms-transform-origin: left bottom;). If you don't see your element, it could be that it's rotating on it's middle axis and thus leaving the page somehow - so double check that.
Move the filter: property for IE7&8 to a separate style sheet and use an IE conditional to insert that style sheet for browsers less than IE9. This way it doesn't affect the IE9 styles and all should work fine.
Make sure to use the correct DOCTYPE tag as well; if you have it wrong IE9 will not work properly.
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
TLDR: use theString = theString.replace("\\", "\\\\");
instead.
replaceAll(target, replacement)
uses regular expression (regex) syntax for target
and partially for replacement
.
Problem is that \
is special character in regex (it can be used like \d
to represents digit) and in String literal (it can be used like "\n"
to represent line separator or \"
to escape double quote symbol which normally would represent end of string literal).
In both these cases to create \
symbol we can escape it (make it literal instead of special character) by placing additional \
before it (like we escape "
in string literals via \"
).
So to target
regex representing \
symbol will need to hold \\
, and string literal representing such text will need to look like "\\\\"
.
So we escaped \
twice:
\\
"\\\\"
(each \
is represented as "\\"
). In case of replacement
\
is also special there. It allows us to escape other special character $
which via $x
notation, allows us to use portion of data matched by regex and held by capturing group indexed as x
, like "012".replaceAll("(\\d)", "$1$1")
will match each digit, place it in capturing group 1 and $1$1
will replace it with its two copies (it will duplicate it) resulting in "001122"
.
So again, to let replacement
represent \
literal we need to escape it with additional \
which means that:
\\
\\
looks like "\\\\"
BUT since we want replacement
to hold two backslashes we will need "\\\\\\\\"
(each \
represented by one "\\\\"
).
So version with replaceAll
can look like
replaceAll("\\\\", "\\\\\\\\");
To make out life easier Java provides tools to automatically escape text into target
and replacement
parts. So now we can focus only on strings, and forget about regex syntax:
replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))
which in our case can look like
replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
If we don't really need regex syntax support lets not involve replaceAll
at all. Instead lets use replace
. Both methods will replace all target
s, but replace
doesn't involve regex syntax. So you could simply write
theString = theString.replace("\\", "\\\\");
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
I had to execute the following commands on ubuntu to solve this problem (I know grunt for 1 hour) :
sudo npm install -g grunt
sudo npm install -g grunt-cli
cd /usr/local/bin
# current symlink points to ../lib/node_modules/grunt/bin/grunt*
sudo rm /usr/local/bin/grunt
sudo ln -s ../lib/node_modules/grunt-cli/bin/grunt* grunt
It is dirty but it is the only one solution I found... :(
This type is defined in the C header <stdint.h>
which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.
In the meantime, you could probably fake up your own version of the header by adding typedef
s that map Microsoft's custom integer types to the types expected by C. For example:
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */
Hope this helps!
I wrote a tutorial explaining how to write a simple HTTP server a while back in Java. Explains what the code is doing and why the server is written that way as the tutorial progresses. Might be useful http://kcd.sytes.net/articles/simple_web_server.php
You could use to_timestamp function to convert the dates to timestamps and perform a substract operation.
Something like:
SELECT
TO_TIMESTAMP ('13.10.1990 00:00:00','DD.MM.YYYY HH24:MI:SS') -
TO_TIMESTAMP ('01.01.1990:00:10:00','DD.MM.YYYY:HH24:MI:SS')
FROM DUAL
You can install opencv
from official or unofficial sites.
Refer to this question and this issue if you are using Anaconda
.
<br>
is sufficient but in XHTML <br />
is preferred according to the WHATWG and according to the W3C.
To quote Section 8.1.2.1 of HTML 5.2 W3C Recommendation, 14 December 2017
Start tags must have the following format:
…
After the attributes, or after the tag name if there are no attributes, there may be one or more space characters. (Some attributes are required to be followed by a space. See §8.1.2.3 Attributes below.)
Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
If you use Dreamweaver CS6, then it will autocomplete as <br />
.
To validate your HTML file on W3C see : http://validator.w3.org/
By the way. whenever my forms call the formclosed or form closing event I close the applciation with a this.Hide() function. Does that affect how my application is behaving now?
In short, yes. The entire application will end when the main form (the form started via Application.Run
in the Main
method) is closed (not hidden).
If your entire application should always fully terminate whenever your main form is closed then you should just remove that form closed handler. By not canceling that event and just letting them form close when the user closes it you will get your desired behavior. As for all of the other forms, if you don't intend to show that same instance of the form again you just just let them close, rather than preventing closure and hiding them. If you are showing them again, then hiding them may be fine.
If you want to be able to have the user click the "x" for your main form, but have another form stay open and, in effect, become the "new" main form, then it's a bit more complicated. In such a case you will need to just hide your main form rather than closing it, but you'll need to add in some sort of mechanism that will actually close the main form when you really do want your app to end. If this is the situation that you're in then you'll need to add more details to your question describing what types of applications should and should not actually end the program.
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
You can set the following environment variable:
PIP_TARGET=/path/to/pip/dir
https://pip.pypa.io/en/stable/user_guide/#environment-variables
What happens in your code if $usertable
is not a valid table or doesn't include a column PartNumber or part is not a number.
You must escape $partid and also read the document for mysql_fetch_assoc() because it can return a boolean
nbconvert is not yet fully replaced by nbconvert2, you can still use it if you wish, otherwise we would have removed the executable. It's just a warning that we do not bugfix nbconvert1 anymore.
The following should work :
./nbconvert.py --format=pdf yourfile.ipynb
If you are on a IPython recent enough version, do not use print view, just use the the normal print dialog. Graph beeing cut in chrome is a known issue (Chrome does not respect some print css), and works much better with firefox, not all versions still.
As for nbconvert2, it still highly dev and docs need to be written.
Nbviewer use nbconvert2 so it's pretty decent with HTML.
List of current available profiles:
$ ls -l1 profile|cut -d. -f1
base_html
blogger_html
full_html
latex_base
latex_sphinx_base
latex_sphinx_howto
latex_sphinx_manual
markdown
python
reveal
rst
Give you the existing profiles.
(You can create your own, cf future doc, ./nbconvert2.py --help-all
should give you some option you can use in your profile.)
then
$ ./nbconvert2.py [profilename] --no-stdout --write=True <yourfile.ipynb>
And it should write your (tex) files as long as extracted figures in cwd. Yes I know this is not obvious, and it will probably change hence no doc...
The reason for that is that nbconvert2 will mainly be a python library where in pseudo code you can do :
MyConverter = NBConverter(config=config)
ipynb = read(ipynb_file)
converted_files = MyConverter.convert(ipynb)
for file in converted_files :
write(file)
Entry point will come later, once the API is stabilized.
I'll just point out that @jdfreder (github profile) is working on tex/pdf/sphinx export and is the expert to generate PDF from ipynb file at the time of this writing.
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
class FrontendSkillList extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = { selectedSkill: {} };_x000D_
}_x000D_
render() {_x000D_
return (_x000D_
<ul>_x000D_
{this.props.skills.map((skill, i) => (_x000D_
<li_x000D_
className={_x000D_
this.state.selectedSkill.id === skill.id ? "selected" : ""_x000D_
}_x000D_
onClick={this.selectSkill.bind(this, skill)}_x000D_
style={{ cursor: "pointer" }}_x000D_
key={skill.id}_x000D_
>_x000D_
{skill.name}_x000D_
</li>_x000D_
))}_x000D_
</ul>_x000D_
);_x000D_
}_x000D_
_x000D_
selectSkill(selected) {_x000D_
if (selected.id !== this.state.selectedSkill.id) {_x000D_
this.setState({ selectedSkill: selected });_x000D_
} else {_x000D_
this.setState({ selectedSkill: {} });_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
const data = [_x000D_
{ id: "1", name: "HTML5" },_x000D_
{ id: "2", name: "CSS3" },_x000D_
{ id: "3", name: "ES6 & ES7" }_x000D_
];_x000D_
const element = (_x000D_
<div>_x000D_
<h1>Frontend Skill List</h1>_x000D_
<FrontendSkillList skills={data} />_x000D_
</div>_x000D_
);_x000D_
ReactDOM.render(element, document.getElementById("root"));
_x000D_
.selected {_x000D_
background-color: rgba(217, 83, 79, 0.8);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
@user544079 Hope this demo can help :) I recommend changing background color by toggling classname.
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
this is the solution to close menu when click on anchor then apply this line in list item
data-target="#sidenav-collapse-main" data-toggle="collapse"
the real example that work for me is below
<li class="nav-item" data-target="#sidenav-collapse-main" data-
toggle="collapse" >
<a class="nav-link" routerLinkActive="active" routerLink="/admin/users">
<i class="ni ni-single-02 text-orange"></i> Users
</a>
</li>
A table can have so many column which can uniquely identify a row. This columns are referred as candidate keys, but primary key should be one of them because one primary key is enough for a table. So selection of primary key is important among so many candidate key. Thats the main difference.
Check out javapassion, they have a number of courses that encompass web programming, and were free (until circumstances conspired to make the website need to support itself).
Even with the nominal fee, you get a lot for an entire year. It's a bargain compared to the amount of time you'll be investing.
The other options are to look to Oracle's online tutorials, they lack the glitz of Codeacademy, but are surprisingly good. I haven't read the one on web programming, that might be embedded in the Java EE tutorial(s), which is not tuned for a new beginner to Java.
You can either go for the const char*
solution mentioned above, but then if you need string all the time, you're going to have a lot of overhead.
On the other hand, static string needs dynamic initialization, thus if you want to use its value during another global/static variable's initialization, you might hit the problem of initialization order. To avoid that, the cheapest thing is accessing the static string object through a getter, which checks if your object is initialized or not.
//in a header
class A{
static string s;
public:
static string getS();
};
//in implementation
string A::s;
namespace{
bool init_A_s(){
A::s = string("foo");
return true;
}
bool A_s_initialized = init_A_s();
}
string A::getS(){
if (!A_s_initialized)
A_s_initialized = init_A_s();
return s;
}
Remember to only use A::getS()
. Because any threading can only started by main()
, and A_s_initialized
is initialized before main()
, you don't need locks even in a multithreaded environment. A_s_initialized
is 0 by default (before the dynamic initialization), so if you use getS()
before s is initialized, you call the init function safely.
Btw, in the answer above: "static const std::string RECTANGLE() const" , static functions cannot be const
because they cannot change the state if any object anyway (there is no this pointer).
I use this script on sql server 2008 R2.
USE [db_name]
ALTER DATABASE [db_name] SET RECOVERY SIMPLE WITH NO_WAIT
DBCC SHRINKFILE([log_file_name]/log_file_number, wanted_size)
ALTER DATABASE [db_name] SET RECOVERY FULL WITH NO_WAIT
The StreamReader.CurrentEncoding
property rarely returns the correct text file encoding for me. I've had greater success determining a file's endianness, by analyzing its byte order mark (BOM). If the file does not have a BOM, this cannot determine the file's encoding.
*UPDATED 4/08/2020 to include UTF-32LE detection and return correct encoding for UTF-32BE
/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
{
// Read the BOM
var bom = new byte[4];
using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
file.Read(bom, 0, 4);
}
// Analyze the BOM
if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true); //UTF-32BE
// We actually have no idea what the encoding is if we reach this point, so
// you may wish to return null instead of defaulting to ASCII
return Encoding.ASCII;
}
// First Get DataTable as dt
// DataRowComparer Compare columns numbers in each row & data in each row
IEnumerable<DataRow> Distinct = dt.AsEnumerable().Distinct(DataRowComparer.Default);
foreach (DataRow row in Distinct)
{
Console.WriteLine("{0,-15} {1,-15}",
row.Field<int>(0),
row.Field<string>(1));
}
Use a seperate column to indicate the join condition
SELECT t.importid,
case
when t.importid = g.home
then 'home'
else 'away'
end as join_condition,
g.network,
g.date_start
FROM game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC
LIMIT 7
If anyone would like I converted this to an extension method on IEnumerable:
public static class ListExtensions
{
public static string ExportAsCSV<T>(this IEnumerable<T> listToExport, bool includeHeaderLine, string delimeter)
{
StringBuilder sb = new StringBuilder();
IList<PropertyInfo> propertyInfos = typeof(T).GetProperties();
if (includeHeaderLine)
{
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.Append(propertyInfo.Name).Append(",");
}
sb.Remove(sb.Length - 1, 1).AppendLine();
}
foreach (T obj in listToExport)
{
T localObject = obj;
var line = String.Join(delimeter, propertyInfos.Select(x => SanitizeValuesForCSV(x.GetValue(localObject, null), delimeter)));
sb.AppendLine(line);
}
return sb.ToString();
}
private static string SanitizeValuesForCSV(object value, string delimeter)
{
string output;
if (value == null) return "";
if (value is DateTime)
{
output = ((DateTime)value).ToLongDateString();
}
else
{
output = value.ToString();
}
if (output.Contains(delimeter) || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
output = output.Replace("\n", " ");
output = output.Replace("\r", "");
return output;
}
}
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
For anyone on MacOS (I'm on Mojave 10.14), the following helped me out: https://github.com/reactioncommerce/reaction/issues/1938#issuecomment-284207213
You'd run these commands
echo kern.maxfiles=65536 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=65536 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=65536
sudo sysctl -w kern.maxfilesperproc=65536
ulimit -n 65536
Then try npm install
once more.
I am implementing old http (0.9, 1.0, 1.1) request and response reader/writer. Request URI is the most problematic place.
You can't just use RFC 1738, 2396 or 3986 as it is. There are many old HTTP clients and servers that allows more characters. So I've made research based on accidentally published webserver access logs: "GET URI HTTP/1.0" 200
.
I've found that the following non-standard characters are often used in URI:
\ { } < > | ` ^ "
These characters were described in RFC 1738 as unsafe.
If you want to be compatible with all old HTTP clients and servers - you have to allow these characters in request URI.
Please read more information about this research in oghttp-request-collector.
remove comment in httpd.conf (apache configuration file):
LoadModule rewrite_module modules/mod_rewrite.so
You need to send ping messages from time to time. I think the default timeout is 300 seconds. Sending websocket ping/pong frame from browser
I agree with sepp2k, but there are some other details that might matter:
new HashSet<Foo>(myList);
will give you an unsorted set which doesn't have duplicates. In this case, duplication is identified using the .equals() method on your objects. This is done in combination with the .hashCode() method. (For more on equality look here)
An alternative that gives a sorted set is:
new TreeSet<Foo>(myList);
This works if Foo implements Comparable. If it doesn't then you may want to use a comparator:
Set<Foo> lSet = new TreeSet<Foo>(someComparator);
lSet.addAll(myList);
This depends on either compareTo() (from the comparable interface) or compare() (from the comparator) to ensure uniqueness. So, if you just care about uniqueness, use the HashSet. If you're after sorting, then consider the TreeSet. (Remember: Optimize later!) If time efficiency matters use a HashSet if space efficiency matters, look at TreeSet. Note that more efficient implementations of Set and Map are available through Trove (and other locations).
HTML :
<div class="span4">
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body panel-height">fdoinfds sdofjohisdfj</div>
</div>
</div>
CSS :
.panel-height {
height: 100px; / change according to your requirement/
}
Add try this code .. Its working grt.......
<body>_x000D_
<?php_x000D_
if (isset($_POST['nav'])) {_x000D_
header("Location: $_POST[nav]");_x000D_
}_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
<select name="nav">_x000D_
<option value="">Go to page...</option>_x000D_
<option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
<option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
<option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
</select>_x000D_
<input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
$("#submit").hide();_x000D_
_x000D_
$("#page-changer select").change(function() {_x000D_
window.location = $("#page-changer select option:selected").val();_x000D_
})_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
Make sure you are running latest version of pip
Tried to install ansible
and it failed with
ModuleNotFoundError: No module named 'setuptools_rust'
python3-setuptools
already in place so upgrading pip
solved it.
pip3 install -U pip
android:maxLines="1"
android:inputType="text"
Add the above code to have a single line in EditText tag in your layout.
android:singleLine="true" is deprecated
This constant was deprecated in API level 3.
This attribute is deprecated. Use maxLines instead to change the layout of a static text, and use the textMultiLine flag in the inputType attribute instead for editable text views (if both singleLine and inputType are supplied, the inputType flags will override the value of singleLine).
Check profiles might be it's invalid https://developer.apple.com/account/resources/profiles/list
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
@Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
Excel 2010 saves an UTF-16/UCS-2 TSV file, if you select File > Save As > Unicode Text (.txt)
. It's (force) suffixed ".txt", which you can change to ".tsv".
If you need CSV, you can then convert the TSV file in a text editor like Notepad++, Ultra Edit, Crimson Editor etc, replacing tabs by semi-colons, commas or the like. Note that e.g. for reading into a DB table, often TSV works fine already (and it is often easier to read manually).
If you need a different code page like UTF-8, use one of the above mentioned editors for converting.
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
In the simplest terms, a Turing-complete system can solve any possible computational problem.
One of the key requirements is the scratchpad size be unbounded and that is possible to rewind to access prior writes to the scratchpad.
Thus in practice no system is Turing-complete.
Rather some systems approximate Turing-completeness by modeling unbounded memory and performing any possible computation that can fit within the system's memory.
Why all the complication?
The simple answer to the original question is just:
#include <stdio.h>
int main()
{
int x = 10;
while (x > 0)
{
printf("%d ", x);
x = x-1;
}
}
It does the same thing. I am not saying you should do it like this, but it does the same thing and would have answered the question in one post.
The x--
is just shorthand for the above, and >
is just a normal greater-than operator
. No big mystery!
There are too many people making simple things complicated nowadays ;)
I think you should avoid writing side-effecting method. Return true or false from your method and you can check these methods in unit tests.
You can't do it like this, but you can execute the entire query storing it in a variable.
For example:
DECLARE @listOfIDs NVARCHAR(MAX) =
'1,2,3'
DECLARE @query NVARCHAR(MAX) =
'Select *
From TabA
Where TabA.ID in (' + @listOfIDs + ')'
Exec (@query)
I started to get the issue today only on chrome and not safari for the same project/url for my goormide container (node.js)
After trying several suggestions above which didn't appear to work and backtracking on some code changes I made from yesterday to today which also made no difference I ended up in the chrome settings clicking:
1.Settings;
2.scroll down to bottom, select: "Advanced";
3.scroll down to bottom, select: "Restore settings to their original defaults";
That appears to have fixed the problem as I no longer get the warning/error in the console and the page displays as it should. Reading the posts above it appears the issue can occur from any number of sources so the settings reset is a potential generic fix. Cheers
// this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
// define two types of routes 1. DefaultActionApi and 2. DefaultApi as below
config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });
// decorate the controller action method with [ActionName("Default")] which need to invoked with below url
// http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
// http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
// http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
// http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
// http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller
public class DemoController : ApiController
{
// Mark the method with ActionName attribute (defined in MapRoutes)
[ActionName("Default")]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
}
public HttpResponseMessage GetAll()
{
return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
}
public HttpResponseMessage GetById()
{
return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage DemoGet()
{
return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage CustomGetDetails()
{
return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
}
}
Try this,
if(thisSession.hasOwnProperty('merchant_id')){
}
the JS Object thisSession
should be like
{
amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}
you can find the details here
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
A simple solution is to make the scope variable object. Then access the content with {{ whatever-object.whatever-property }}
. The variable is not updating because JavaScript pass Primitive type by value. Whereas Object are passed by reference which solves the problem.
When I run
git branch
, it only shows*master
, not the remaining two branches.
git branch
doesn't list test_branch
, because no such local branch exist in your local repo, yet. When cloning a repo, only one local branch (master
, here) is created and checked out in the resulting clone, irrespective of the number of branches that exist in the remote repo that you cloned from. At this stage, test_branch
only exist in your repo as a remote-tracking branch, not as a local branch.
And when I run
git checkout test-branch
I get the following error [...]
You must be using an "old" version of Git. In more recent versions (from v1.7.0-rc0 onwards),
If
<branch>
is not found but there does exist a tracking branch in exactly one remote (call it<remote>
) with a matching name, treat [git checkout <branch>
] as equivalent to$ git checkout -b <branch> --track <remote>/<branch>
Simply run
git checkout -b test_branch --track origin/test_branch
instead. Or update to a more recent version of Git.
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
These are the best and most commonly used methods for writing to and reading from files:
using System.IO;
File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it.
File.ReadAllText(sFilePathAndName);
The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.
Append text to an existing file:
private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
string sTextToAppend = txtMainUserInput.Text;
//first, check to make sure that the user entered something in the text box.
if (sTextToAppend == "" || sTextToAppend == null)
{MessageBox.Show("You did not enter any text. Please try again");}
else
{
string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string.
if (sFilePathAndName == "" || sFilePathAndName == null)
{
//MessageBox.Show("You cancalled"); //DO NOTHING
}
else
{
sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text
File.AppendAllText(sFilePathAndName, sTextToAppend);
string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1);
MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
}//end nested if/else
}//end if/else
}//end method AppendTextToExistingFile_Click
Get file name from the user via file explorer/open file dialog (you will need this to select existing files).
private string getFileNameFromUser()//returns file path\name
{
string sFileNameAndPath = "";
OpenFileDialog fd = new OpenFileDialog();
fd.Title = "Select file";
fd.Filter = "TXT files|*.txt";
fd.InitialDirectory = Environment.CurrentDirectory;
if (fd.ShowDialog() == DialogResult.OK)
{
sFileNameAndPath = (fd.FileName.ToString());
}
return sFileNameAndPath;
}//end method getFileNameFromUser
Get text from an existing file:
private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
string sFileNameAndPath = getFileNameFromUser();
txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}
According to SQL2000 help, sp_spaceused includes data and indexes.
This script should do:
CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18),
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))
EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''
-- SELECT * FROM #t ORDER BY name
-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY name
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #t
DROP TABLE #t
Jorman is a successful businessman and has 2 houses.
But others don't know that.
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator ==
behaves. So it will say that datos[0]==usuario
is false, because it only compares the addresses.
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals()
method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals
method behaves. So datos[0].equals(usuario)
will return true, because it performs a logical comparison.
It looks like Angular has support for this now.
From the latest (v1.2.0) docs for $routeProvider.when(path, route)
:
path
can contain optional named groups with a question mark (:name?
)
Of course it is right what you say at the beginning, and C logical operator &&
and ||
are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in other ways
#include <stdio.h>
int main(void) // as std wants
{
int i, j;
// init both i and j; condition, we suppose && is the "original"
// intention; update i and j
for(i=0, j=2; j>=0 && i<=5; i++, j--)
{
printf("%d ", i+j);
}
return 0;
}
The best plain English explanation comes from using an analogy:
Your PHP example is a web service by that definition, because the output could be consumed by another program. But in reality, HTML screen-scraping is not a reliable or maintainable way of producing web services.
<style name="TextAppearance.App.TextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">@color/red</item>
<item name="android:textSize">14sp</item>
</style>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColorHint="@color/gray" //support 23.0.0
app:hintTextAppearance="@style/TextAppearence.App.TextInputLayout" >
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint" />
</android.support.design.widget.TextInputLayout>
Since no one mention: In C#, an array is a list. MyClass[]
and List<MyClass>
both implement IList<MyClass>
. (e.g. void Foo(IList<int> foo)
can be called like Foo(new[] { 1, 2, 3 })
or Foo(new List<int> { 1, 2, 3 })
)
So, if you are writing a method that accepts a List<MyClass>
as an argument, but uses only subset of features, you may want to declare as IList<MyClass>
instead for callers' convenience.
Details:
Another category method you could use:
- (NSArray *) filteredArrayUsingBlock:(BOOL (^)(id obj))block {
NSIndexSet *const filteredIndexes = [self indexesOfObjectsPassingTest:^BOOL (id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
return block(obj);
}];
return [self objectsAtIndexes:filteredIndexes];
}
try
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
[CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [smalldatetime] NOT NULL
)
PS I think a smalldatetime is good enough. You may decide differently.
Can you not do this at the "moment of impact" ?
In Sql Server, this is common:
Update dbo.MyTable
Set
ColA = @SomeValue ,
UpdateDS = CURRENT_TIMESTAMP
Where...........
Sql Server has a "timestamp" datatype.
But it may not be what you think.
Here is a reference:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Here is a little RowVersion (synonym for timestamp) example:
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Maybe a complete working example:
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS
BEGIN
Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where
triggerInsertedTable.Name = myAlias.Name
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Matching on the "Name" value is probably not wise.
Try this more mainstream example with a SurrogateKey
DROP TABLE [dbo].[Names]
GO
CREATE TABLE [dbo].[Names]
(
SurrogateKey int not null Primary Key Identity (1001,1),
[Name] [nvarchar](64) NOT NULL,
RowVers rowversion ,
[CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
[UpdateTS] [datetime] NOT NULL
)
GO
CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS
BEGIN
UPDATE dbo.Names
SET UpdateTS = CURRENT_TIMESTAMP
From dbo.Names myAlias
WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)
END
GO
INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */
select * , ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]
require(reshape2)
T <- melt(df, id = c("A"))
T <- dcast(T, A ~ variable, sum)
I am not certain the exact advantages over aggregate.
Perl one-liner similar to @jonas's awk solution:
perl -ne 'print if ! $x{$_}++' file
This variation removes trailing whitespace before comparing:
perl -lne 's/\s*$//; print if ! $x{$_}++' file
This variation edits the file in-place:
perl -i -ne 'print if ! $x{$_}++' file
This variation edits the file in-place, and makes a backup file.bak
perl -i.bak -ne 'print if ! $x{$_}++' file
function trimRegex(str, regex){
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimRegex(test, /[^|]/);
console.log(test); //output: ab||cd
or
function trimChar(str, trim, req){
let regex = new RegExp('[^'+trim+']');
return str.substr(str.match(regex).index).split('').reverse().join('').substr(str.match(regex).index).split('').reverse().join('');
}
let test = '||ab||cd||';
trimChar(test, '|');
console.log(test); //output: ab||cd
I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.
class MyClass {
constructor ( arg1, arg2, arg3 )
myFunction1 () {...}
myFunction2 () {...}
myFunction3 () {...}
}
module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }
And then you get your expected behaviour.
var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )
if(isnull({uspRptMonthlyGasRevenueByGas;1.YearTotal})) = true then
"nd"
else
totext({uspRptMonthlyGasRevenueByGas;1.YearTotal},'###.00')
The above logic should be what you are looking for.
I agree with Greg that the log is the best place to start. We've experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLM\System\CurrentControlSet\Control\WMI\Security prior to starting the installation. HTH.
Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.
UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.
I've tried a select statement now with a PreparedStatement
, but it turned out that it was not faster than the Jdbc template. Maybe, as mezmo suggested, it automatically creates prepared statements.
Anyway, the reason for my sql SELECT
s being so slow was another one. In the WHERE
clause I always used the operator LIKE
, when all I wanted to do was finding an exact match. As I've found out LIKE
searches for a pattern and therefore is pretty slow.
I'm using the operator =
now and it's much faster.
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
This is similar to CommonsWare answer but with a minor tweak: android:gravity="top|start"
. Complete code example:
<EditText
android:id="@+id/EditText02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|start"
android:inputType="textMultiLine"
android:scrollHorizontally="false"
/>
The biggest advantage of NoSQL over RDBMS is Scalability.
NoSQL databases can easily scale-out to many nodes, but for RDBMS it is very hard.
Scalability not only gives you more storage space but also much higher performance since many hosts work at the same time.
try this...
var withComma = "23,3";
var withFloat = "23.3";
var compareValue = function(str){
var fixed = parseFloat(str.replace(',','.'))
if(fixed > 0){
console.log(true)
}else{
console.log(false);
}
}
compareValue(withComma);
compareValue(withFloat);
I wrote my own random number utility class just so that I would have something that functioned a bit more like Math.random() in Java. It has just two functions, and it's all made in C.
Header file:
//Random.h
void initRandomSeed(long firstSeed);
float nextRandomFloat();
Implementation file:
//Random.m
static unsigned long seed;
void initRandomSeed(long firstSeed)
{
seed = firstSeed;
}
float nextRandomFloat()
{
return (((seed= 1664525*seed + 1013904223)>>16) / (float)0x10000);
}
It's a pretty classic way of generating pseudo-randoms. In my app delegate I call:
#import "Random.h"
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
initRandomSeed( (long) [[NSDate date] timeIntervalSince1970] );
//Do other initialization junk.
}
Then later I just say:
float myRandomNumber = nextRandomFloat() * 74;
Note that this method returns a random number between 0.0f (inclusive) and 1.0f (exclusive).
SSLSHopper has some pretty thorough articles about moving between different servers.
http://www.sslshopper.com/how-to-move-or-copy-an-ssl-certificate-from-one-server-to-another.html
Just pick the relevant link at bottom of this page.
Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.
http://www.quirksmode.org/js/findpos.html Explains the best way to do it, all in all, you are on the right track you have to find the offsets and traverse up the tree of parents.
Here is a simple answer:
class Singleton {
static Singleton _instance;
Singleton._();
static Singleton get getInstance => _instance ??= Singleton._();
}
<script type="text/javascript">
function bike()
{
var data=
["b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg", "b6.jpg", "b7.jpg", "b8.jpg"];
var a;
for(a=0; a<data.length; a++)
{
document.write("<center><fieldset style='height:200px; float:left; border-radius:15px; border-width:6px;")<img src='"+data[a]+"' height='200px' width='300px'/></fieldset></center>
}
}
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
note you can only do this with Numbers and Strings
you could do...
var a, b, c; a = b = c = 0; //but why?
c++;
// c = 1, b = 0, a = 0;
To put my two cents here: on KSH, read
ing as is to a variable will work, because according to the IBM AIX documentation, KSH's read
does affects the current shell environment:
The setting of shell variables by the read command affects the current shell execution environment.
This just resulted in me spending a good few minutes figuring out why a one-liner ending with read
that I've used a zillion times before on AIX didn't work on Linux... it's because KSH does saves to the current environment and BASH doesn't!
This isn't an alternative solution; rather a suggestion for Brandon's popular answer (seeing as though I don't have enough rep to comment on that answer). If you're uploading large files; you're probably going to get a mmap malloc exception on account of having to read the file into memory to post it to your server.
You can tweak Brandon's code by replacing:
[request setHTTPBody:postbody];
With:
NSInputStream *stream = [[NSInputStream alloc] initWithData:postbody];
[request setHTTPBodyStream:stream];
With ANY operator you can search for only one value.
For example,
select * from mytable where 'Book' = ANY(pub_types);
If you want to search multiple values, you can use @> operator.
For example,
select * from mytable where pub_types @> '{"Journal", "Book"}';
You can specify in which ever order you like.
Start maven with -X option (debug) and examine the beginning of the output. There should be something like this:
...
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from c:\....\apache-maven-3.0.3\conf\settings.xml
[DEBUG] Reading user settings from c:\....\.m2\settings.xml
[DEBUG] Using local repository at C:\....\repository
...
(Original directory names are removed by me)
The following command
git clone git://github.com/username/projectname.git
worked for my needs, but I assume you want more than read-only access, right?
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
Try just --with-curl, without specifying a location, and see if it'll find it by itself.
Here's a solution (resembling the original) that works:
User = raw_input('Enter <Carriage return> only to exit: ')
while True:
#Run my program
print 'In the loop, User=%r' % (User, )
# Check if the user asked to terminate the loop.
if User == '':
break
# Give the user another chance to exit.
User = raw_input('Enter <Carriage return> only to exit: ')
Note that the code in the original question has several issues:
if
/else
is outside the while loop, so the loop will run forever.else
is missing a colon.if
clause performs a break
.Use C++ streams and restore state afterwards
This is a variation of How do I print bytes as hexadecimal? but:
main.cpp
#include <iomanip>
#include <iostream>
int main() {
int array[] = {0, 0x8, 0x10, 0x18};
constexpr size_t size = sizeof(array) / sizeof(array[0]);
// Sanity check decimal print.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
// Hex print and restore default afterwards.
std::ios cout_state(nullptr);
cout_state.copyfmt(std::cout);
std::cout << std::hex << std::setfill('0') << std::setw(2);
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
std::cout.copyfmt(cout_state);
// Check that cout state was restored.
for (size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
std::cout << std::endl;
}
Compile and run:
g++ -o main.out -std=c++11 main.cpp
./main.out
Output:
0 8 16 24
00 8 10 18
0 8 16 24
Tested on Ubuntu 16.04, GCC 6.4.0.
Yes. See Named and Optional Arguments. Note that the default value needs to be a constant, so this is OK:
public string Foo(string myParam = "default value") // constant, OK
{
}
but this is not:
public void Bar(string myParam = Foo()) // not a constant, not OK
{
}
You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script(hi.sh) with in nodejs.
hi.sh
echo "Hi There!"
node_program.js
const { exec } = require('child_process');
var yourscript = exec('sh hi.sh',
(error, stdout, stderr) => {
console.log(stdout);
console.log(stderr);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
Here, when I run the nodejs file, it will execute the shell file and the output would be:
Run
node node_program.js
output
Hi There!
You can execute any script just by mentioning the shell command or shell script in exec
callback.
Hope this helps! Happy coding :)
You can do it using this class I just made. With this class you can use the Map
object like another dictionary(including json serialization) or with the dot notation. I hope to help you:
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if kwargs:
for k, v in kwargs.iteritems():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
Usage examples:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
# Or
m['new_key'] = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']
In addition, if you want to refer to the root directory, you can use:
/
Which will refer to the root. So, let's say we're in a file that's nested within a few levels of folders and you want to go back to the main index.html:
<a href="/index.html">My Index Page</a>
Robert is spot-on with further relative path explanations.
I re-installed C::B in drive D, whereas my program files folder is in drive C
I don't know the reason , but it works :)
I believe you're using \w (word character) where you ought to be using \s (whitespace). Word characters typically consist of [A-Za-z0-9_], so that excludes your space, which then further fails to match on the optional minus sign or a digit.
you can use glob function to do this. see the example
import cv2
import glob
for img in glob.glob("path/to/folder/*.png"):
cv_img = cv2.imread(img)