sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
in scrollview make height and width 0 add Top_toBottomOfand Bottom_toTopOf constraints that's it.
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
Try to understand through this below function using python3
def floating_decimals(f_val, dec):
prc = "{:."+str(dec)+"f}" #first cast decimal as str
print(prc) #str format output is {:.3f}
return prc.format(f_val)
print(floating_decimals(50.54187236456456564, 3))
Output is : 50.542
Hope this helps you!
<summary>
and <details>
Using <summary>
and <details>
elements is the simplest but see browser support as current IE is not supporting it. You can polyfill though (most are jQuery-based). Do note that unsupported browser will simply show the expanded version of course, so that may be acceptable in some cases.
/* Optional styling */_x000D_
summary::-webkit-details-marker {_x000D_
color: blue;_x000D_
}_x000D_
summary:focus {_x000D_
outline-style: none;_x000D_
}
_x000D_
<details>_x000D_
<summary>Summary, caption, or legend for the content</summary>_x000D_
Content goes here._x000D_
</details>
_x000D_
See also how to style the <details>
element (HTML5 Doctor) (little bit tricky).
The :target
selector has a pretty good browser support, and it can be used to make a single collapsible element within the frame.
.details,_x000D_
.show,_x000D_
.hide:target {_x000D_
display: none;_x000D_
}_x000D_
.hide:target + .show,_x000D_
.hide:target ~ .details {_x000D_
display: block;_x000D_
}
_x000D_
<div>_x000D_
<a id="hide1" href="#hide1" class="hide">+ Summary goes here</a>_x000D_
<a id="show1" href="#show1" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<a id="hide2" href="#hide2" class="hide">+ Summary goes here</a>_x000D_
<a id="show2" href="#show2" class="show">- Summary goes here</a>_x000D_
<div class="details">_x000D_
Content goes here._x000D_
</div>_x000D_
</div>
_x000D_
If you are lost with errors like module not found there is noway other the than following method if you have used react native CLI.I had faced similar issue as a result of openning xcode project from .xcodeproj file instead of .xcworkspace. Also please note that react-native eject only for Expo project.
The only workaround to regenarate ios and android folders within a react native project is the following.
Now your problem should be solved
Answer E is correct answer. If E is not there, you will soon run out of memory (or) No correct answer.
Object should be unreachable to be eligible for GC. JVM will do multiple scans and moving objects from one generation to another generation to determine the eligibility of GC and frees the memory when the objects are not reachable.
My inquiry is this. When does one use #import and when does one use @class?
Simple answer: You #import
or #include
when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass
, struct MONStruct
, @protocol MONProtocol
).
Here are some common examples of physical dependence:
CGPoint
as an ivar or property, the compiler will need to see the declaration of CGPoint
.Sometimes if I use a @class declaration, I see a common compiler warning such as the following: "warning: receiver 'FooController' is a forward class and corresponding @interface may not exist."
The compiler's actually very lenient in this regard. It will drop hints (such as the one above), but you can trash your stack easily if you ignore them and don't #import
properly. Although it should (IMO), the compiler does not enforce this. In ARC, the compiler is more strict because it is responsible for reference counting. What happens is the compiler falls back on a default when it encounters an unknown method which you call. Every return value and parameter is assumed to be id
. Thus, you ought to eradicate every warning from your codebases because this should be considered physical dependence. This is analogous to calling a C function which is not declared. With C, parameters are assumed to be int
.
The reason you would favor forward declarations is that you can reduce your build times by factors because there is minimal dependence. With forward declarations, the compiler sees there is a name, and can correctly parse and compile the program without seeing the class declaration or all of its dependencies when there is no physical dependency. Clean builds take less time. Incremental builds take less time. Sure, you will end up spending a little more time making sure the all the headers you need are visible to every translation as a consequence, but this pays off in reduced build times quickly (assuming your project is not tiny).
If you use #import
or #include
instead, you're throwing a lot more work at the compiler than is necessary. You're also introducing complex header dependencies. You can liken this to a brute-force algorithm. When you #import
, you're dragging in tons of unnecessary information, which requires a lot of memory, disk I/O, and CPU to parse and compile the sources.
ObjC is pretty close to ideal for a C based language with regards to dependency because NSObject
types are never values -- NSObject
types are always reference counted pointers. So you can get away with incredibly fast compile times if you structure your program's dependencies appropriately and forward where possible because there is very little physical dependence required. You can also declare properties in the class extensions to further minimize dependence. That's a huge bonus for large systems -- you would know the difference it makes if you have ever developed a large C++ codebase.
Therefore, my recommendation is to use forwards where possible, and then to #import
where there is physical dependence. If you see the warning or another which implies physical dependence -- fix them all. The fix is to #import
in your implementation file.
As you build libraries, you will likely classify some interfaces as a group, in which case you would #import
that library where physical dependence is introduced (e.g. #import <AppKit/AppKit.h>
). This can introduce dependence, but the library maintainers can often handle the physical dependencies for you as needed -- if they introduce a feature, they can minimize the impact it has on your builds.
As specified in oracle official tutorial , it states that:
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
If I have an Application interacting with database using JDBC
, And I have a method that takes the argument as the int item
and double price
. The price
for corresponding item is read from database table. I simply multiply the total number of item
purchased with the price
value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG
in your database. So , and IllegalArguementException()
should be thrown in this case which would state that the price can't be negative
.
I hope that I have expressed my point clearly..
My 2 pennies:-
collection.Count(v => (v.PropertyToUpdate = newValue) == null);
Use the script console (Manage Jenkins > Script Console) and something like this script to bulk delete a job's build history https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/bulkDeleteBuilds.groovy
That script assumes you want to only delete a range of builds. To delete all builds for a given job, use this (tested):
// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
// uncomment these lines to reset the build number to 1:
//job.nextBuildNumber = 1
//job.save()
Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.
You need to use this function.
JSON.parse(yourJsonString);
And it will return the object / array that was contained within the string.
In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'
Sample JSON fetch request:
fetch(url, {
method: 'GET',
credentials: 'include'
})
.then((response) => response.json())
.then((json) => {
console.log('Gotcha');
}).catch((err) => {
console.log(err);
});
https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials
I usually try to use it like this:
This error should not happen in the managed code. This might solve the issue:
Go to Visual Studio Debugger to bypass this exception:
Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load"
Hope it will help.
I had same problem. you can't use left <
arrow in text property like as android:text="< Go back"
in your xml file. Remove any <
arrow from you xml code.
Hope It will helps you.
The new urllib3 library has a nice documentation here
In order to get your desired result you shuld follow that:
Import urllib3
from bs4 import BeautifulSoup
url = 'http://www.thefamouspeople.com/singers.php'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))
The "decode utf-8" part is optional. It worked without it when i tried, but i posted the option anyway.
Source: User Guide
It was every much frustrated. So, I got solution which works for me.
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(file.getAbsolutePath());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
});
}
});
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
I suggest create a list and append dictionary into it.
x = []
cur = db.dbname.find()
for i in cur:
x.append(i)
print(x)
Now x is a list of dictionary, you can manipulate the same in usual python way.
Use:
<Button Height="100" Width="100">
<StackPanel>
<Image Source="img.jpg" />
<TextBlock Text="Blabla" />
</StackPanel>
</Button>
It should work. But remember that you must have an image added to the resource on your project!
Here's a link which provides two other solutions without using any visited flags.
https://leetcode.com/problems/binary-tree-postorder-traversal/
This is obviously a stack-based solution due to the lack of parent pointer in the tree. (We wouldn't need a stack if there's parent pointer).
We would push the root node to the stack first. While the stack is not empty, we keep pushing the left child of the node from top of stack. If the left child does not exist, we push its right child. If it's a leaf node, we process the node and pop it off the stack.
We also use a variable to keep track of a previously-traversed node. The purpose is to determine if the traversal is descending/ascending the tree, and we can also know if it ascend from the left/right.
If we ascend the tree from the left, we wouldn't want to push its left child again to the stack and should continue ascend down the tree if its right child exists. If we ascend the tree from the right, we should process it and pop it off the stack.
We would process the node and pop it off the stack in these 3 cases:
I depends heavily on which number formats you aim to support, and how strict you want to enforce number grouping, use of whitespace and other separators etc....
Take a look at this similar question to get some ideas.
Then there is E.164 which is a numbering standard recommendation from ITU-T
There is a second parameter for the callback for collection.insert
that will return the doc or docs inserted, which should have _ids.
Try:
collection.insert(objectToInsert, function(err,docsInserted){
console.log(docsInserted);
});
and check the console to see what I mean.
Here is how you can do it with a socket on php-fpm 7
install socat
apt-get install socat
#!/bin/sh
if echo /dev/null | socat UNIX:/var/run/php/php7.0-fpm.sock - ; then
echo "$home/run/php-fpm.sock connect OK"
else
echo "$home/run/php-fpm.sock connect ERROR"
fi
You can also check if the service is running like this.
service php7.0-fpm status | grep running
It will return
Active: active (running) since Sun 2017-04-09 12:48:09 PDT; 48s ago
Add clickListener on button like this
btUpdate.setOnClickListener(onclickListener)
add this code in your activity
val onclickListener: View.OnClickListener = View.OnClickListener { view ->
when (view.id) {
R.id.btUpdate -> updateData()
}
}
best way will be to save it in a text file with csv extension:
Sub ExportToCSV()
Dim i, j As Integer
Dim Name As String
Dim pathfile As String
Dim fs As Object
Dim stream As Object
Set fs = CreateObject("Scripting.FileSystemObject")
On Error GoTo fileexists
i = 15
Name = Format(Now(), "ddmmyyHHmmss")
pathfile = "D:\1\" & Name & ".csv"
Set stream = fs.CreateTextFile(pathfile, False, True)
fileexists:
If Err.Number = 58 Then
MsgBox "File already Exists"
'Your code here
Return
End If
On Error GoTo 0
j = 1
Do Until IsEmpty(ThisWorkbook.ActiveSheet.Cells(i, 1).Value)
stream.WriteLine (ThisWorkbook.Worksheets(1).Cells(i, 1).Value & ";" & Replace(ThisWorkbook.Worksheets(1).Cells(i, 6).Value, ".", ","))
j = j + 1
i = i + 1
Loop
stream.Close
End Sub
Keep it simple...
$intArray = array ();
$strArray = explode(',', $string);
foreach ($strArray as $value)
$intArray [] = intval ($value);
Why are you looking for other ways? Looping does the job without pain. If performance is your concern, you can go with json_decode ()
. People have posted how to use that, so I am not including it here.
Note: When using == operator instead of === , your string values are automatically converted into numbers (e.g. integer or double) if they form a valid number without quotes. For example:
$str = '1';
($str == 1) // true but
($str === 1) //false
Thus, == may solve your problem, is efficient, but will break if you use === in comparisons.
You can just add the DISTINCT(ip)
, but it has to come at the start of the query. Be sure to escape PHP variables that go into the SQL string.
SELECT DISTINCT(ip), name, COUNT(name) nameCnt,
time, price, SUM(price) priceSum
FROM tablename
WHERE time >= $yesterday AND time <$today
GROUP BY ip, name
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
Use the reflect package:
Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type.
package main
import (
"fmt"
"reflect"
)
func main() {
b := true
s := ""
n := 1
f := 1.0
a := []string{"foo", "bar", "baz"}
fmt.Println(reflect.TypeOf(b))
fmt.Println(reflect.TypeOf(s))
fmt.Println(reflect.TypeOf(n))
fmt.Println(reflect.TypeOf(f))
fmt.Println(reflect.TypeOf(a))
}
Produces:
bool
string
int
float64
[]string
Example using ValueOf(i interface{}).Kind()
:
package main
import (
"fmt"
"reflect"
)
func main() {
b := true
s := ""
n := 1
f := 1.0
a := []string{"foo", "bar", "baz"}
fmt.Println(reflect.ValueOf(b).Kind())
fmt.Println(reflect.ValueOf(s).Kind())
fmt.Println(reflect.ValueOf(n).Kind())
fmt.Println(reflect.ValueOf(f).Kind())
fmt.Println(reflect.ValueOf(a).Index(0).Kind()) // For slices and strings
}
Produces:
bool
string
int
float64
string
$(window).unbind('scroll');
Even though the documentation says it will remove all event handlers if called with no arguments, it is worth giving a try explicitly unbinding it.
It worked if you used single quotes? That doesn't sound right - as far as I know, JavaScript treats single and double quotes the same (unlike some other languages like PHP and C).
You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.
As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox
Yes, you can do a 3 table join for an update statement. Here is an example :
UPDATE customer_table c
JOIN
employee_table e
ON c.city_id = e.city_id
JOIN
anyother_ table a
ON a.someID = e.someID
SET c.active = "Yes"
WHERE c.city = "New york";
I had this issue with python 3.5, anaconda 3, windows 7 32 bit. I solved it by moving my pythonX.lib and pythonX.dll files into my working directory and calling
Py_SetPythonHome(L"C:\\Path\\To\\My\\Python\\Installation");
before initialize so that it could find the headers that it needed, where my path was to "...\Anaconda3\". The extra step of calling Py_SetPythonHome was required for me or else I'd end up getting other strange errors where python import files.
One simple solution:
cond1 <- df$sub == 1 & df$day == 2
cond2 <- df$sub == 3 & df$day == 4
df <- df[!(cond1 | cond2),]
big=small=values[0]; //assigns element to be highest or lowest value
Should be AFTER
fill loop
//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
since when you declare array - it's unintialized
(store some undefined values) and so, your big
and small
after assigning would store undefined
values too.
And of course, you can use std::min_element
, std::max_element
, or std::minmax_element
from C++11
, instead of writing your loops.
Use event.key
instead of event.keyCode
!
function onEvent(event) {
if (event.key === "Enter") {
// Submit form
}
};
Try this:
Dim regDate as Date = Date.Now()
Dim strDate as String = regDate.ToString("ddMMMyyyy")
strDate will look like so: 07Feb2012
5 years too late, I know, but no-one actually answered the question:
Then, why should I use the bare repository and why not? What's the practical difference? That would not be beneficial to more people working on a project, I suppose.
What are your methods for this kind of work? Suggestions?
To quote directly from the Loeliger/MCullough book (978-1-449-31638-9, p196/7):
A bare repository might seem to be of little use, but its role is crucial: to serve as an authoritative focal point for collaborative development. Other developers
clone
andfetch
from the bare repository andpush
updates to it... if you set up a repository into which developerspush
changes, it should be bare. In effect, this is a special case of the more general best practice that a published repository should be bare.
This question has been answered sufficiently many times, but with C# 7.2 and the introduction of the Span type, there is a faster way to do this in unsafe code:
public static class StringSupport
{
private static readonly int _charSize = sizeof(char);
public static unsafe byte[] GetBytes(string str)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (str.Length == 0) return new byte[0];
fixed (char* p = str)
{
return new Span<byte>(p, str.Length * _charSize).ToArray();
}
}
public static unsafe string GetString(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
if (bytes.Length == 0) return string.Empty;
fixed (byte* p = bytes)
{
return new string(new Span<char>(p, bytes.Length / _charSize));
}
}
}
Keep in mind that the bytes represent a UTF-16 encoded string (called "Unicode" in C# land).
Some quick benchmarking shows that the above methods are roughly 5x faster than their Encoding.Unicode.GetBytes(...)/GetString(...) implementations for medium sized strings (30-50 chars), and even faster for larger strings. These methods also seem to be faster than using pointers with Marshal.Copy(..) or Buffer.MemoryCopy(...).
This simple 32 lines gist lets you identify a given stylesheet and change its styles very easily:
var styleSheet = StyleChanger("my_custom_identifier");
styleSheet.change("darkolivegreen", "blue");
List<T>.Insert(0, item);
This is similar to qntmfred's solution, but using a direct table dump. This option is slightly faster (see BCP docs):
to export:
bcp "[MyDatabase].dbo.Customer " out "Customer.bcp" -N -S localhost -T -E
to import:
bcp [MyDatabase].dbo.Customer in "Customer.bcp" -N -S localhost -T -E -b 10000
You can use the datepicker's onSelect
event.
$(".date").datepicker({
onSelect: function(dateText) {
console.log("Selected date: " + dateText + "; input's current value: " + this.value);
}
});
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
Unfortunately, onSelect
fires whenever a date is selected, even if it hasn't changed. This is a design flaw in the datepicker: It always fires onSelect
(even if nothing changed), and doesn't fire any event on the underlying input on change. (If you look in the code of that example, we're listening for changes, but they aren't being raised.) It should probably fire an event on the input when things change (possibly the usual change
event, or possibly a datepicker-specific one).
If you like, of course, you can make the change
event on the input
fire:
$(".date").datepicker({
onSelect: function() {
$(this).change();
}
});
That will fire change
on the underlying input
for any handler hooked up via jQuery. But again, it always fires it. If you want to only fire on a real change, you'll have to save the previous value (possibly via data
) and compare.
Live example:
$(".date")_x000D_
.datepicker({_x000D_
onSelect: function(dateText) {_x000D_
console.log("Selected date: " + dateText + "; input's current value: " + this.value);_x000D_
$(this).change();_x000D_
}_x000D_
})_x000D_
.on("change", function() {_x000D_
console.log("Got change event from field");_x000D_
});
_x000D_
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />_x000D_
<input type='text' class='date'>_x000D_
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
_x000D_
work for me mysql select * from (SELECT number,max(date_added) as datea FROM sms_chat group by number) as sup order by datea desc
If I'd need a mutable raw copy of a c++'s string contents, then I'd do this:
std::string str = "string";
char* chr = strdup(str.c_str());
and later:
free(chr);
So why don't I fiddle with std::vector or new[] like anyone else? Because when I need a mutable C-style raw char* string, then because I want to call C code which changes the string and C code deallocates stuff with free() and allocates with malloc() (strdup uses malloc). So if I pass my raw string to some function X written in C it might have a constraint on it's argument that it has to allocated on the heap (for example if the function might want to call realloc on the parameter). But it is highly unlikely that it would expect an argument allocated with (some user-redefined) new[]!
imho: Apache HTTP Client
usage example:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
If the keystore is PKCS12 type (.pfx
) you have to specify it with -storetype PKCS12
(line breaks added for readability):
keytool -list -v -keystore <path to keystore.pfx> \
-storepass <password> \
-storetype PKCS12
such as this kind of dataframe, there are two levels of thecolumn name:
shop_id item_id date_block_num item_cnt_day
target
0 0 30 1 31
we can use this code:
df.columns = [col[0] if col[-1]=='' else col[-1] for col in df.columns.values]
result is:
shop_id item_id date_block_num target
0 0 30 1 31
You can use rand()
together with pow()
to make this happen:
$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);
This will output a number between 100 and 999. This because 10^2 = 100 and 10^3 = 1000 and then you need to subtract it with one to get it in the desired range.
If 005 also is a valid example you'd use the following code to pad it with leading zeros:
$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
A visual for those that benefit from it.
After right-clicking the project name ("test" in this example), select "Add framework support" and check the "Maven" option.
Here's my research results:
Apple has hidden the UDID from all public APIs, starting with iOS 7. Any UDID that begins with FFFF is a fake ID. The "Send UDID" apps that previously worked can no longer be used to gather UDID for test devices. (sigh!)
The UDID is shown when a device is connected to XCode (in the organizer), and when the device is connected to iTunes (although you have to click on 'Serial Number' to get the Identifier to display.
If you need to get the UDID for a device to add to a provisioning profile, and can't do it yourself in XCode, you will have to walk them through the steps to copy/paste it from iTunes.
UPDATE -- see okiharaherbst's answer below for a script based approach to allow test users to provide you with their device UDIDs by hosting a mobileconfig file on a server
To remove dangling images please use :
docker image rm $(docker images --format "{{.ID}}" --filter "dangling=true")
Please refer to my answer here for a more detailed description : https://unix.stackexchange.com/a/445664/292327
Here's my take on this.
I'd rather not use a bash for loop if I can avoid it, as that takes time to run. If something has to loop, let it be something that was written in a lower level language than a shell script.
function array_contains { # arrayname value
local -A _arr=()
local IFS=
eval _arr=( $(eval printf '[%q]="1"\ ' "\${$1[@]}") )
return $(( 1 - 0${_arr[$2]} ))
}
This works by creating a temporary associative array, _arr
, whose indices are derived from the values of the input array. (Note that associative arrays are available in bash 4 and above, so this function won't work in earlier versions of bash.) We set $IFS
to avoid word splitting on whitespace.
The function contains no explicit loops, though internally bash steps through the input array in order to populate printf
. The printf format uses %q
to ensure that input data are escaped such that they can safely be used as array keys.
$ a=("one two" three four)
$ array_contains a three && echo BOOYA
BOOYA
$ array_contains a two && echo FAIL
$
Note that everything this function uses is a built-in to bash, so there are no external pipes dragging you down, even in the command expansion.
And if you don't like using eval
... well, you're free to use another approach. :-)
You have to send
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
to the picker view before it appears. The documentation states that the method selectedRowInComp... will give -1, thus it is possible that the picker view is in a state with no selected row. It turns out to be in that state when created.
Backspace and tab both move the cursor position. Neither is truly a 'printable' character.
Your code says:
To get the output you expect, you need printf("foo\b \tbar")
. Note the extra 'space'. That says:
Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use printf()
formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.
This little script shows one way to alter your terminal's tab rendering. Tested on Ubuntu + gnome-terminal:
#!/bin/bash
tabs -8
echo -e "\tnormal tabstop"
for x in `seq 2 10`; do
tabs $x
echo -e "\ttabstop=$x"
done
tabs -8
echo -e "\tnormal tabstop"
Also see man setterm
and regtabs
.
And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in "programming" editors and IDEs.
So in otherwords:
printf("%-8s%s", "foo", "bar"); /* this will ALWAYS output "foo bar" */
printf("foo\tbar"); /* who knows how this will be rendered */
IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).
Backspace '\b'
is a different story... it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out "ncurses", which gives you much better control over where your output goes on the terminal screen. And typically, since it's 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.
The environment variables of a process exist at runtime, and are not stored in some file or so. They are stored in the process's own memory (that's where they are found to pass on to children). But there is a virtual file in
/proc/pid/environ
This file shows all the environment variables that were passed when calling the process (unless the process overwrote that part of its memory — most programs don't). The kernel makes them visible through that virtual file. One can list them. For example to view the variables of process 3940, one can do
cat /proc/3940/environ | tr '\0' '\n'
Each variable is delimited by a binary zero from the next one. tr replaces the zero into a newline.
ACID are desirable properties of any transaction processing engine.
A DBMS is (if it is any good) a particular kind of transaction processing engine that exposes, usually to a very large extent but not quite entirely, those properties.
But other engines exist that can also expose those properties. The kind of software that used to be called "TP monitors" being a case in point (nowadays' equivalent mostly being web servers).
Such TP monitors can access resources other than a DBMS (e.g. a printer), and still guarantee ACID toward their users. As an example of what ACID might mean when a printer is involved in a transaction:
There are several ways to see HOVER STATE styles in Chrome Developer Tools.
Method 01
Method 02
With Firefox Default Developer Toll
With Firebug
Adding to what @Hitesh-sahu said you need all the VC++ redistribution packages for it to turn green. I referred to this thread from wampserver forum. You can install this little tool (check_vcredist) from the tools section here which will check if all the needed dependencies are installed (see attached image) and it will also provide links to missing ones. If you are using x64 version of Windows like I do and your wampserver does not turn green even after installing all the packages then uninstall and do a fresh installation again. Hope it helps.
If you are doing it in Notepad++
[\w]+
Would give you the entire word, and you can add parenthesis to get it as a group. Example: conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs)
. I would like to move LeakyReLU
into its own line as a comment, and replace the current activation. In notepad++ this can be done using the follow find command:
([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)
and the replace command becomes:
\1\2'relu'\4 \n # \1 = LeakyReLU\(alpha=a\)\(\1\)
The spaces is to keep the right formatting in my code. :)
The return value for main
indicates how the program exited. Normal exit is represented by a 0 return value from main
. Abnormal exit is signaled by a non-zero return, but there is no standard for how non-zero codes are interpreted. As noted by others, void main()
is prohibited by the C++ standard and should not be used. The valid C++ main
signatures are:
int main()
and
int main(int argc, char* argv[])
which is equivalent to
int main(int argc, char** argv)
It is also worth noting that in C++, int main()
can be left without a return-statement, at which point it defaults to returning 0. This is also true with a C99 program. Whether return 0;
should be omitted or not is open to debate. The range of valid C program main signatures is much greater.
Efficiency is not an issue with the main
function. It can only be entered and left once (marking the program's start and termination) according to the C++ standard. For C, re-entering main()
is allowed, but should be avoided.
There is a (somewhat) related question on StackOverflow:
Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeeze
d or sliced into a 2D array.
More generally, the reason for the Exception
TypeError: Invalid dimensions for image data
is shown here: matplotlib.pyplot.imshow()
needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!
You can easily check this with (these checks are done by imshow
, this function is only meant to give a more specific message in case it's not a valid input):
from __future__ import print_function
import numpy as np
def valid_imshow_data(data):
data = np.asarray(data)
if data.ndim == 2:
return True
elif data.ndim == 3:
if 3 <= data.shape[2] <= 4:
return True
else:
print('The "data" has 3 dimensions but the last dimension '
'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
''.format(data.shape[2]))
return False
else:
print('To visualize an image the data must be 2 dimensional or '
'3 dimensional, not "{}".'
''.format(data.ndim))
return False
In your case:
>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False
The np.asarray
is what is done internally by matplotlib.pyplot.imshow
so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list
) it's necessary.
In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()
import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0) # or axis=1
plt.imshow(a)
plt.show()
or just use something that accepts 1D arrays like plot
:
a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()
Just discovered that :
next(iter(myList), 5)
iter(l)
returns an iterator on myList
, next()
consumes the first element of the iterator, and raises a StopIteration
error except if called with a default value, which is the case here, the second argument, 5
This only works when you want the 1st element, which is the case in your example, but not in the text of you question, so...
Additionally, it does not need to create temporary lists in memory and it works for any kind of iterable, even if it does not have a name (see Xiong Chiamiov's comment on gruszczy's answer)
nums = range(10)
for i in range(0, len(nums)-1, 2):
print nums[i]
Kinda dirty but it works.
require 'json'
hash = JSON.parse string
work with the hash and do what you want to do.
Swift - I wrote a class that inherited UITextView and I added a UILabel as a subview to act as a placeholder.
import UIKit
@IBDesignable
class HintedTextView: UITextView {
@IBInspectable var hintText: String = "hintText" {
didSet{
hintLabel.text = hintText
}
}
private lazy var hintLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFontOfSize(16)
label.textColor = UIColor.lightGrayColor()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
private func setupView() {
translatesAutoresizingMaskIntoConstraints = false
delegate = self
font = UIFont.systemFontOfSize(16)
addSubview(hintLabel)
NSLayoutConstraint.activateConstraints([
hintLabel.leftAnchor.constraintEqualToAnchor(leftAnchor, constant: 4),
hintLabel.rightAnchor.constraintEqualToAnchor(rightAnchor, constant: 8),
hintLabel.topAnchor.constraintEqualToAnchor(topAnchor, constant: 4),
hintLabel.heightAnchor.constraintEqualToConstant(30)
])
}
override func layoutSubviews() {
super.layoutSubviews()
setupView()
}
}
URIs came about from the need to identify resources on the Web, and other Internet resources such as electronic mailboxes in a uniform and coherent way. So, one can introduce a new type of widget: URIs to identify widget resources or use tel: URIs to have web links cause telephone calls to be made when invoked.
Some URIs provide information to locate a resource (such as a DNS host name and a path on that machine), while some are used as pure resource names. The URL is reserved for identifiers that are resource locators, including 'http' URLs such as http://stackoverflow.com, which identifies the web page at the given path on the host. Another example is 'mailto' URLs, such as mailto:[email protected], which identifies the mailbox at the given address.
URNs are URIs that are used as pure resource names rather than locators. For example, the URI: mid:[email protected] is a URN that identifies the email message containing it in its 'Message-Id' field. The URI serves to distinguish that message from any other email message. But it does not itself provide the message's address in any store.
Font Awesome seems to be working fine for me in my android app. I did the following:
fontawesome-webfont.ttf
into my assests folderCreated an entry in strings.xml for each icon. Eg for a heart:
<string name="icon_heart"></string>
Referenced said entry in the view of my xml layout:
<Button
android:id="@+id/like"
style="?android:attr/buttonStyleSmall"
...
android:text="@string/icon_heart" />
Loaded the font in my onCreate method and set it for the appropriate Views:
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
...
Button button = (Button)findViewById( R.id.like );
button.setTypeface(font);
public void Method()
{
if(something)
{
//some code
if(!something2)
{
return;
}
}
// The code i want to go if the second if is true
}
Find the C file and Makefile implementation in below to meet your requirements
foo.c
main ()
{
int a = MAKE_DEFINE;
printf ("MAKE_DEFINE value:%d\n", a);
}
Makefile
all:
gcc -DMAKE_DEFINE=11 foo.c
@Html.Raw(Json.Encode(object)) can be used to convert the View Modal Object to JSON
Clarification:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.
Original answer:
Incredibly, this is now possible purely in CSS3.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).
Don't you just love CSS3?
CodePen Example:
Sources:
Just to cover one more case when I was getting the same error and the reason was using in instead of of in iterator
Wrong way let file in files
Correct way let file of files
As Marc says, you run it exactly like you would from the command line. See Creating SQL Server Agent Jobs on MSDN.
simply write:
if(values > 0){
//positive
}
else{
//negative
}
If you are using Microsoft Drivers 3.1, 3.0, and 2.0.
Please check your PHP version already install with IIS.
Use this script to check the php version:
<?php echo phpinfo(); ?>
OR
If you have installed PHP Manager in IIS using web platform Installer you can check the version from it.
Then:
If you are using new PHP version (5.6) please download Drivers from here
For PHP version Lower than 5.6 - please download Drivers from here
Then use the PHP Manager to add that downloaded drivers into php config
file.You can do it as shown below (browse the files and press OK).
Then Restart the IIS Server
If this method not work please change the php version and try to run your php script.
Tip:Change the php version
to lower and try to understand what happened.then you can download relevant drivers.
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
Use trim($source)
before $s[$source]
.
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
Here's a version, again using the cross product logic, written in Clojure.
(defn is-left? [line point]
(let [[[x1 y1] [x2 y2]] (sort line)
[x-pt y-pt] point]
(> (* (- x2 x1) (- y-pt y1)) (* (- y2 y1) (- x-pt x1)))))
Example usage:
(is-left? [[-3 -1] [3 1]] [0 10])
true
Which is to say that the point (0, 10) is to the left of the line determined by (-3, -1) and (3, 1).
NOTE: This implementation solves a problem that none of the others (so far) does! Order matters when giving the points that determine the line. I.e., it's a "directed line", in a certain sense. So with the above code, this invocation also produces the result of true
:
(is-left? [[3 1] [-3 -1]] [0 10])
true
That's because of this snippet of code:
(sort line)
Finally, as with the other cross product based solutions, this solution returns a boolean, and does not give a third result for collinearity. But it will give a result that makes sense, e.g.:
(is-left? [[1 1] [3 1]] [10 1])
false
Look into using the ToString()
method with a specified format.
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name']
after your javascript was executed.
Regards
In Java 8:
Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));
Reverse order:
Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));
When ArrayList is declared and initialized using the default constructor, memory space for 10 elements is created.
NO. When ArrayList is initialized, memory allocation is made for an empty array. Memory allocation for default capacity (10) is made only upon addition of first element to ArrayList.
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == EMPTY_ELEMENTDATA will be expanded to
* DEFAULT_CAPACITY when the first element is added.
*/
private transient Object[] elementData;
P.S. Don't have enough reputation to comment on question, so I am putting this as an answer as nobody pointed out this incorrect assumption earlier.
Install
npm i graph-fs
Use
const {Node} = require("graph-fs");
const directory = new Node("/path/to/directory");
directory.clear(); // <--
My preference is to use const whenever I can, which, as mentioned in previous answers, is limited to literal expressions or something that does not require evaluation.
If I hit up against that limitation, then I fallback to static readonly, with one caveat. I would generally use a public static property with a getter and a backing private static readonly field as Marc mentions here.
If you don't want your new column to be of type IDENTITY
(auto-increment), or you want to be specific about the order in which your rows are numbered, you can add a column of type INT NULL
and then populate it like this. In my example, the new column is called MyNewColumn and the existing primary key column for the table is called MyPrimaryKey.
UPDATE MyTable
SET MyTable.MyNewColumn = AutoTable.AutoNum
FROM
(
SELECT MyPrimaryKey,
ROW_NUMBER() OVER (ORDER BY SomeColumn, SomeOtherColumn) AS AutoNum
FROM MyTable
) AutoTable
WHERE MyTable.MyPrimaryKey = AutoTable.MyPrimaryKey
This works in SQL Sever 2005 and later, i.e. versions that support ROW_NUMBER()
If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog"
to, say, 6 characters without cutting off any word).
If this is the case, you can try something like the following:
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract
//Trim and re-trim only when necessary (prevent re-trim when string is shorted than maxLength, it causes last word cut)
if(yourString.length > trimmedString.length){
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word and
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
}
Sometimes the problem might be with hardcoded VS version in .csproj file. If you have in your csproj something like this:
[...]\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets"
You should check if the number is correct (the reason it's wrong can be the project was created with another version of Visual Studio). If it's wrong, replace it with your current version of build tools OR use the VS variable:
[...]\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets"
If you're using Ubuntu then use the following:
sudo chown -R ubuntu /var/www/html
sudo chmod -R 755 /var/www/html
You need to set the thumbnail class to position relative then the post-content to absolute.
Check this fiddle
.post-content {
top:0;
left:0;
position: absolute;
}
.thumbnail{
position:relative;
}
Giving it top and left 0 will make it appear in the top left corner.
In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.
Use Entry.insert
. For example:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()
Or use textvariable
option:
try:
from tkinter import * # Python 3.x
except Import Error:
from Tkinter import * # Python 2.x
root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()
For anyone getting this using ServiceStack backend; add "Authorization" to allowed headers in the Cors plugin:
Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization"));
The export default {...}
construction is just a shortcut for something like this:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { foo(); bar() }
}
export default funcs
It must become obvious now that there are no foo
, bar
or baz
functions in the module's scope. But there is an object named funcs
(though in reality it has no name) that contains these functions as its properties and which will become the module's default export.
So, to fix your code, re-write it without using the shortcut and refer to foo
and bar
as properties of funcs
:
const funcs = {
foo() { console.log('foo') },
bar() { console.log('bar') },
baz() { funcs.foo(); funcs.bar() } // here is the fix
}
export default funcs
Another option is to use this
keyword to refer to funcs
object without having to declare it explicitly, as @pawel has pointed out.
Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:
function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }
export default {foo, bar, baz}
And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:
// util.js
export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }
export default {foo, bar, baz}
// a.js, using default export
import util from './util'
util.foo()
// b.js, using named exports
import {bar} from './util'
bar()
Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util'
to get all named exports in one object.
I solved the issue by adding this import
More info
from past.builtins import xrange
You need to update the execution permission for gradlew
Locally: chmod +x gradlew
Git:
git update-index --chmod=+x gradlew
git add .
git commit -m "Changing permission of gradlew"
git push
You should see:
mode change 100644 => 100755 gradlew
Right click on the folder where you put your main class then click on Build Path
--> Use as Source Folder
.
Finally run your main file as java application. Hope this problem will be solved.
I've made an alias git squash-all
.
Example usage: git squash-all "a brand new start"
.
[alias]
squash-all = "!f(){ git reset $(git commit-tree HEAD^{tree} -m \"${1:-A new start}\");};f"
Note: the optional message is for commit message, if omitted, it will default to "A new start".
Or you can create the alias with the following command:
git config --global alias.squash-all '!f(){ git reset $(git commit-tree HEAD^{tree} -m "${1:-A new start}");};f'
git reset $(git commit-tree HEAD^{tree} -m "A new start")
Here, the commit message "A new start
" is just an example, feel free to use your own language.
No need to squash, use git commit-tree
to create an orphan commit and go with it.
create a single commit via git commit-tree
What git commit-tree HEAD^{tree} -m "A new start"
does is:
Creates a new commit object based on the provided tree object and emits the new commit object id on stdout. The log message is read from the standard input, unless -m or -F options are given.
The expression HEAD^{tree}
means the tree object corresponding to HEAD
, namely the tip of your current branch. see Tree-Objects and Commit-Objects.
Then git reset
simply reset the current branch to the newly created
commit object.
This way, nothing in the workspace is touched, nor there's need for rebase/squash, which makes it really fast. And the time needed is irrelevant to the repository size or history depth.
This is useful to create the "initial commit" in a new project using another repository as the template/archetype/seed/skeleton. For example:
cd my-new-project
git init
git fetch --depth=1 -n https://github.com/toolbear/panda.git
git reset --hard $(git commit-tree FETCH_HEAD^{tree} -m "initial commit")
This avoids adding the template repo as a remote (origin
or otherwise) and collapses the template repo's history into your initial commit.
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
This occurs when declared (non-pure) virtual functions are missing bodies. In your class definition, something like:
virtual void foo();
Should be defined (inline or in a linked source file):
virtual void foo() {}
Or declared pure virtual:
virtual void foo() = 0;
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
The only one reason why you get some error like that, it's because your node version is not compatible with your node-sass version.
So, make sure to checkout the documentation at here: https://www.npmjs.com/package/node-sass
Or this image below will be help you, what the node version can use the node-sass version.
For an example, if you're using node version 12 on your windows ("maybe"), then you should have to install the node-sass version 4.12.
npm install [email protected]
Yeah, like that. So now you only need to install the node-sass version recommended by the node-sass team with the nodes installed on your computer.
'RESTless' is a term not often used.
You can define 'RESTless' as any system that is not RESTful. For that it is enough to not have one characteristic that is required for a RESTful system.
Most systems are RESTless by this definition because they don't implement HATEOAS.
With Git 2.25 (Q1 2020), you can modify it.
See "Git submodule url changed" and the new command
git submodule set-url [--] <path> <newurl>
Original answer (May 2009, ten years ago)
Actually, a patch has been submitted in April 2009 to clarify gitmodule
role.
So now the gitmodule documentation does not yet include:
The
.gitmodules
file, located in the top-level directory of a git working tree, is a text file with a syntax matching the requirements -of linkgit:git-config1.
[NEW]:
As this file is managed by Git, it tracks the +records of a project's submodules.
Information stored in this file is used as a hint to prime the authoritative version of the record stored in the project configuration file.
User specific record changes (e.g. to account for differences in submodule URLs due to networking situations) should be made to the configuration file, while record changes to be propagated (e.g. +due to a relocation of the submodule source) should be made to this file.
That pretty much confirm Jim's answer.
If you follow this git submodule tutorial, you see you need a "git submodule init
" to add the submodule repository URLs to .git/config.
"git submodule sync
" has been added in August 2008 precisely to make that task easier when URL changes (especially if the number of submodules is important).
The associate script with that command is straightforward enough:
module_list "$@" |
while read mode sha1 stage path
do
name=$(module_name "$path")
url=$(git config -f .gitmodules --get submodule."$name".url)
if test -e "$path"/.git
then
(
unset GIT_DIR
cd "$path"
remote=$(get_default_remote)
say "Synchronizing submodule url for '$name'"
git config remote."$remote".url "$url"
)
fi
done
The goal remains: git config remote."$remote".url "$url"
Like Jonathan suggested, using textView.setTextTypeface
works, I just used it in an app a few seconds ago.
textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.
I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:
<asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink>
The easiest solution I found was to simply put that in your fragment :
androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NavController navController = Navigation.findNavController(getActivity(),
R.id.nav_host_fragment);
navController.navigate(R.id.action_position_to_destination);
}
});
Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.
There are several ways to synchronize access to a static variable.
Use a synchronized static method. This synchronizes on the class object.
public class Test {
private static int count = 0;
public static synchronized void incrementCount() {
count++;
}
}
Explicitly synchronize on the class object.
public class Test {
private static int count = 0;
public void incrementCount() {
synchronized (Test.class) {
count++;
}
}
}
Synchronize on some other static object.
public class Test {
private static int count = 0;
private static final Object countLock = new Object();
public void incrementCount() {
synchronized (countLock) {
count++;
}
}
}
Method 3 is the best in many cases because the lock object is not exposed outside of your class.
I know this is an old question, but I shall post my answer for posterity...
It depends on the system that you are building and the particular business rules in place.
I am building a moderate to large scale CRM in MongoDb, C# (Backend API), and Angular (Frontend web app) and found ObjectId utterly terrible for use in Angular Routing for selecting particular entities. Same with API Controller routing.
The suggestion above worked perfectly for my project.
db.contacts.insert({
"id":db.contacts.find().Count()+1,
"name":"John Doe",
"emails":[
"[email protected]",
"[email protected]"
],
"phone":"555111322",
"status":"Active"
});
The reason it is perfect for my case, but not all cases is that as the above comment states, if you delete 3 records from the collection, you will get collisions.
My business rules state that due to our in house SLA's, we are not allowed to delete correspondence data or clients records for longer than the potential lifespan of the application I'm writing, and therefor, I simply mark records with an enum "Status" which is either "Active" or "Deleted". You can delete something from the UI, and it will say "Contact has been deleted" but all the application has done is change the status of the contact to "Deleted" and when the app calls the respository for a list of contacts, I filter out deleted records before pushing the data to the client app.
Therefore, db.collection.find().count() + 1 is a perfect solution for me...
It won't work for everyone, but if you will not be deleting data, it works fine.
background:url(directoryName/imageName.extention) bottom left no-repeat;
background-color: red;
I fixed this by checking Delete all existing files prior to publish
in Visual Studio:
String.contains
works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.
Note that String.contains
does not check for word boundary; it simply checks for substring.
Regex is more powerful than String.contains
, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.
Use String.matches
with the following regex:
"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"
The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):
(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*
The \b
checks for word boundary, so that you don't get a match for restores store products
. Note that stores 3store_product
is also rejected, since digit and _
are considered part of a word, but I doubt this case appear in natural text.
Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product
will not match the regex above, since you are searching for the word store
without s
.
.
normally match any character except a number of new line characters. (?s)
at the beginning makes .
matches any character without exception (thanks to Tim Pietzcker for pointing this out).
myBook.Saved = true;
myBook.SaveCopyAs(xlsFileName);
myBook.Close(null, null, null);
myExcel.Workbooks.Close();
myExcel.Quit();
There are methods like WriteAllText
in the File
class for common operations on files.
Use the MapPath
method to get the physical path for a file in your web application.
File.WriteAllText(Server.MapPath("~/data.txt"), TextBox1.Text);
If you want iterate about a list of key-value-pairs (as you wrote in the comment), then a List or an array should be better. First combine your keys and values:
public class Pair
{
public Class1 key;
public Class2 value;
public Pair(Class1 key, Class2 value)
{
this.key = key;
this.value = value;
}
}
Replace Class1 and Class2 with the types you want to use for keys and values.
Now you can put them into an array or a list and iterate over them:
Pair[] pairs = new Pair[10];
...
for (Pair pair : pairs)
{
...
}
In my case charset, datatype every thing was correct. After investigation I found that in parent table there was no index on foreign key column. Once added problem got solved.
hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar
use this:
bytesRead = responseStream.ReadAsync(buffer, 0, Length).Result;
If you're willing to run X applications as well - use xpra together with "screen".
Use the Python list insert() method. Usage:
#Syntax
The syntax for the insert() method -
list.insert(index, obj)
#Parameters
#Return Value This method does not return any value, but it inserts the given element at the given index.
Example:
a = [1,2,4,5]
a.insert(2,3)
print(a)
Returns [1, 2, 3, 4, 5]
just use this as a middleware
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Methods', '*');
return $response;
}
}
and register the middleware in your kernel file on this path app/Http/Kernel.php
in which group that you prefer and everything will be fine
You can try this code (requires jQuery):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#foo').keyup(function(e) {
var v = $('#foo').val();
$('#debug').val(v);
})
});
</script>
</head>
<body>
<form>
<input type="text" id="foo" value="bar"><br>
<textarea id="debug"></textarea>
</form>
</body>
</html>
Another base R
option could be gl()
:
gl(5, 3)
Where the output is a factor:
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5
If integers are needed, you can convert it:
as.numeric(gl(5, 3))
[1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Constraints in SQL are the rules defined for the data in a table. Constraints also limit the types of data that go into the table. If new data does not abide by these rules the action is aborted.
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY';
You can view all constraints by using select * from information_schema.table_constraints;
(This will produce a lot of table data).
You can also use this for MySQL:
show create table tableName;
just use this simple code :
NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];
since nsset doesn't allow duplicate values and all objects returns an array
If you're looking to also get the port number out of the request you'll need to access it through the Request.Host
property for AspNet Core.
The Request.Host
property is not simply a string but, instead, an object that holds both the host domain and the port number. If the port number is specifically written out in the URL (i.e. "https://example.com:8080/path/to/resource"
), then calling Request.Host
will give you the host domain and the port number like so: "example.com:8080"
.
If you only want the value for the host domain or only want the value for the port number then you can access those properties individually (i.e. Request.Host.Host
or Request.Host.Port
).
MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.
https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns
What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)
I needed one application to run on multiple subdomains. So in bootstrap/app.php
I added something like:
$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);
I had this error because I was testing my app to perform a certain action in the future. In other words, I had a different time on my test device, therefore, the certificate would not allow me to build.
Apparently, my certificate expires in a few days...
The easiest way is just wait for some element which will appear on loaded page.
If you would like to click on some button already after page is loaded you could use await and click:
await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;
You may want to read this document in matplotlib
's documentation, titled:
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
You can iterate over keys by calling map.keySet()
, or iterate over the entries by calling map.entrySet()
. Iterating over entries will probably be faster.
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
List<String> list = entry.getValue();
// Do things with the list
}
If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap
.
By the way, I'd recommend changing the declared type of the map to <String, List<String>>
. Always best to declare types in terms of the interface rather than the implementation.
function run() {
window.setTimeout(
"run()",
1000
);
}
Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:
public function up()
{
// Create the table
Schema::create('users', function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('password', 64);
$table->boolean('verified');
$table->string('token', 255);
$table->timestamps();
});
// Insert some stuff
DB::table('users')->insert(
array(
'email' => '[email protected]',
'verified' => true
)
);
}
Use the json
module to produce JSON output:
import json
with open(outputfilename, 'wb') as outfile:
json.dump(row, outfile)
This writes the JSON result directly to the file (replacing any previous content if the file already existed).
If you need the JSON result string in Python itself, use json.dumps()
(added s
, for 'string'):
json_string = json.dumps(row)
The L
is just Python syntax for a long integer value; the json
library knows how to handle those values, no L
will be written.
Demo string output:
>>> import json
>>> row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
>>> json.dumps(row)
'[1, [0.1, 0.2], [[1234, 1], [134, 2]]]'
I just came up with this method which may be hardware intensive but it is working:
You can replace all characters which match the regex by an empty string.
This is a oneliner:
notMatched = re.sub(regex, "", string)
I used this because I was forced to use a very complex regex and couldn't figure out how to invert every part of it within a reasonable amount of time.
This will only return you the string result, not any match objects!
There are multiple ways. You may use this too.
echo "Your string here"| tr ' ' '\n' | tail -n1
> here
Obviously, the blank space input for tr command should be replaced with the delimiter you need.
Try adding JSON.stringify(result)
to convert the JS Object into a JSON string.
From your code I can see you are logging the result in error
which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).
Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.
If I remember correctly, window.location.reload()
reloads the current page with POST data, while window.location.href=window.location.href
does not include the POST data.
As noted by @W3Max in the comments below, window.location.href=window.location.href
will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload()
in this case.
Also, as noted by @Mic below, window.location.reload()
takes an additional argument skipCache
so that with using window.location.reload(true)
the browser will skip the cache and reload the page from the server. window.location.reload(false)
will do the opposite, and load the page from cache if possible.
Partially. The text is inserted, but the warning is still generated.
I found a discussion that indicated the text needed to be preceded with 'E', as such:
insert into EscapeTest (text) values (E'This is the first part \n And this is the second');
This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.
As such:
insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');
I just modified your code. It works fine in my system. See if this helps
class round{
public static void main(String args[]){
double a = 123.13698;
double roundOff = Math.round(a*100)/100.00;
System.out.println(roundOff);
}
}
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
Application.Exit();
}
}
}
--Kotlin Version
package com.ps.salestrackingapp.Services
import android.app.Service
import android.content.Context
import android.content.Intent
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.os.IBinder
import android.util.Log
class LocationService : Service() {
private var mLocationManager: LocationManager? = null
var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))
class LocationListener(provider: String) : android.location.LocationListener {
internal var mLastLocation: Location
init {
Log.e(TAG, "LocationListener $provider")
mLastLocation = Location(provider)
}
override fun onLocationChanged(location: Location) {
Log.e(TAG, "onLocationChanged: $location")
mLastLocation.set(location)
Log.v("LastLocation", mLastLocation.latitude.toString() +" " + mLastLocation.longitude.toString())
}
override fun onProviderDisabled(provider: String) {
Log.e(TAG, "onProviderDisabled: $provider")
}
override fun onProviderEnabled(provider: String) {
Log.e(TAG, "onProviderEnabled: $provider")
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
Log.e(TAG, "onStatusChanged: $provider")
}
}
override fun onBind(arg0: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand")
super.onStartCommand(intent, flags, startId)
return Service.START_STICKY
}
override fun onCreate() {
Log.e(TAG, "onCreate")
initializeLocationManager()
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[1])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "network provider does not exist, " + ex.message)
}
try {
mLocationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
mLocationListeners[0])
} catch (ex: java.lang.SecurityException) {
Log.i(TAG, "fail to request location update, ignore", ex)
} catch (ex: IllegalArgumentException) {
Log.d(TAG, "gps provider does not exist " + ex.message)
}
}
override fun onDestroy() {
Log.e(TAG, "onDestroy")
super.onDestroy()
if (mLocationManager != null) {
for (i in mLocationListeners.indices) {
try {
mLocationManager!!.removeUpdates(mLocationListeners[i])
} catch (ex: Exception) {
Log.i(TAG, "fail to remove location listners, ignore", ex)
}
}
}
}
private fun initializeLocationManager() {
Log.e(TAG, "initializeLocationManager")
if (mLocationManager == null) {
mLocationManager = applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
}
companion object {
private val TAG = "BOOMBOOMTESTGPS"
private val LOCATION_INTERVAL = 1000
private val LOCATION_DISTANCE = 0f
}
}
Another way to select all cells within a range, as long as the data is contiguous, is to use Range("A1", Range("A1").End(xlDown).End(xlToRight)).Select
.
or you can use c# string interpolation like this (feature available in C# 6.0)
var value = "1, 2, 3";
var output = $" foo {{{value}}}";
"instance to an application" means nothing.
"object" and "instance" are the same thing. There is a "class" that defines structure, and instances of that class (obtained with new ClassName()
). For example there is the class Car
, and there are instance with different properties like mileage, max speed, horse-power, brand, etc.
Reference is, in the Java context, a variable* - it is something pointing to an object/instance. For example, String s = null;
- s
is a reference, that currently references no instance, but can reference an instance of the String
class.
*Jon Skeet made a note about the difference between a variable and a reference. See his comment. It is an important distinction about how Java works when you invoke a method - pass-by-value.
The value of s is a reference. It's very important to distinguish between variables and values, and objects and references.
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
You can execute this in 2 simple statements:
row.names(samp) <- samp$names
samp[1] <- NULL
In JavaScript using Associative array:
this:
function getItemPricing(customer, item) {
switch (customer.type) {
// VIPs are awesome. Give them 50% off.
case 'VIP':
return item.price * item.quantity * 0.50;
// Preferred customers are no VIPs, but they still get 25% off.
case 'Preferred':
return item.price * item.quantity * 0.75;
// No discount for other customers.
case 'Regular':
case
default:
return item.price * item.quantity;
}
}
becomes this:
function getItemPricing(customer, item) {
var pricing = {
'VIP': function(item) {
return item.price * item.quantity * 0.50;
},
'Preferred': function(item) {
if (item.price <= 100.0)
return item.price * item.quantity * 0.75;
// Else
return item.price * item.quantity;
},
'Regular': function(item) {
return item.price * item.quantity;
}
};
if (pricing[customer.type])
return pricing[customer.type](item);
else
return pricing.Regular(item);
}
Instance: instance means just creating a reference(copy).
object: means when memory location is associated with the object (is a run-time entity of the class) by using the new operator.
In simple words, Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.
This error means that remote repository has had other commits and has paced ahead of your local branch.
I try doing a git pull followed by a git push. If their are No conflicting changes, git pull gets the latest code to my local branch while keeping my changes intact.
Then a git push pushes my changes to the master branch.
A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
On my Mobo (ASRock A320M-HD with Ryzen 3 2200G) I have to:
SR-IOV support: enabled
IOMMU: enabled
SVM: enabled
On the OS enable Hyper V.
If Perl is an option, you can try this:
perl -lne 'print $1 if /(regex)/' file
To implement case-insensitive matching, add the i
modifier
perl -lne 'print $1 if /(regex)/i' file
To print everything AFTER the match:
perl -lne 'if ($found){print} else{if (/regex(.*)/){print $1; $found++}}' textfile
To print the match and everything after the match:
perl -lne 'if ($found){print} else{if (/(regex.*)/){print $1; $found++}}' textfile
Swift 4.2
let closure = { [weak self] (_ parameter:Int) in
guard let self = self else { return }
self.method(parameter)
}
Create an XML-file in a res/drawable
folder. For instance, "btn_image.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_state_1"
android:state_pressed="true"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_2"
android:state_pressed="true"
android:state_selected="false"/>
<item android:drawable="@drawable/bg_state_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_deselected"/>
</selector>
You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".
In any of those files you can write something like:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ccdd00"/>
<corners android:radius="5dp"/>
</shape>
Create in a layout file an ImageView or ImageButton with the following attributes:
<ImageView
android:id="@+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:adjustViewBounds="true"
android:background="@drawable/btn_image"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/star"/>
Later in code:
image.setSelected(!image.isSelected());
You can always take the CTE, (Common Tabular Expression), approach.
;WITH updateCTE AS
(
SELECT ID, TITLE
FROM HOLD_TABLE
WHERE ID = 101
)
UPDATE updateCTE
SET TITLE = 'TEST';
Place all files need to copied in a separate folder, for ease place them in c drive.
Open Command Prompt - windows>type cmd>select command prompt.
You can see the default directory pointing - Ex : C:[Folder_Name]>. Change the directory to point to the folder which you have placed files to be copied, using ' cd [Folder_Name] ' command.
After pointing to directory - type 'dir' which shows all the files present in folder, just to make sure everything at place.
Now type : 'copy *.txt [newfile_name].txt' and press enter.
Done!
All the text in individual files will be copied to [newfile_name].txt
I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.
Example code:
import { useRef } from 'react'
function Component() {
const inputRef = useRef()
return (
<input ref={inputRef} />
<div
onScroll={() => {
const { offsetTop } = inputRef.current
...
}}
>
)
}
I had the same problem in some browser to access to my SSL site. I have found that I had to give to fireFox the right proxy (FireFox was accessing directly to internet).
Depending of the lan configuration (Tunneling, filtering, proxy redirection), the "direct access to internet" mode for FireFox throws this error.
One of the first things that you should check is that the SQL Server (MSSQLSERVER) is started. You can go to the Services Console (services.msc) and look for SQL Server (MSSQLSERVER) to see that it is started. If not, then start the service.
You could also do this through an elevated command prompt by typing net start mssqlserver
.
If the application you are generating the scripts from is a .NET application, you may want to look into using SMO (Sql Management Objects). Reference this SQL Team link on how to use SMO to script objects.
background-repeat:no-repeat;
background-position:center center;
Does not vertically center the background image when using a html 4.01 'STRICT' doctype.
Adding:
background-attachment: fixed;
Should fix the problem
(So Alexander is right)
There's a difference between an empty string ""
and an undefined variable. You should be checking whether or not theHref contains a defined string, rather than its lenght:
if(theHref){
// ---
}
If you still want to check for the length, then do this:
if(theHref && theHref.length){
// ...
}
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';
to get table counts
SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';
this also works
USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
Here is the one liner i use, from terminal, to test the content of yml file(s):
$ ruby -r yaml -r pp -e 'pp YAML.load_file("/Users/za/project/application.yml")'
{"logging"=>
{"path"=>"/var/logs/",
"file"=>"TacoCloud.log",
"level"=>
{"root"=>"WARN", "org"=>{"springframework"=>{"security"=>"DEBUG"}}}}}
To get current host name :-
select @@hostname;
show variables where Variable_name like '%host%';
To get hosts for all incoming requests :-
select host from information_schema.processlist;
Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.
However, mysql document mention this :-
resolveip google.com.sg
docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html
Had the same problem. Solved as given below. Use command :
sudo tail -f /var/log/messages|grep -i mysql
to check if SELinux policy is causing the issue. If so, first check if SELinux policy is enabled using command #sestatus
. If it shows enabled, then disable it.
To disable:
# vi /etc/sysconfig/selinux
sestatus
and it should show "disabled"Uninstall and reinstall mysql. It should be working.
I encountered this problem on my laptop. I found the solution for this problem.
Then do this
5 lines in coffeescript
array = ['/img/movie1.png','/img/movie2.png','/img/movie3.png']
$(document).ready ->
for index, image of array
img[index] = new Image()
img[index].src = image
Check that your mysql has not reached maximum connections, or is not in some sort of booting loop as happens quite often if the settings are incorrect in my.cnf.
Use ps aux | grep mysql to check if the PID is changing.
sub domain is part of the domain, it's like subletting a room of an apartment. A records has to be setup on the dns for the domain e.g
mydomain.com has IP 123.456.789.999 and hosted with Godaddy. Now to get the sub domain
anothersite.mydomain.com
of which the site is actually on another server then
login to Godaddy and add an A record dnsimple anothersite.mydomain.com and point the IP to the other server 98.22.11.11
And that's it.
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
Simply with native html & css :
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text */
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
/* Fade in tooltip */
opacity: 0;
transition: opacity 0.3s;
}
/* Tooltip arrow */
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
Here is the source of the example from w3schools
'In' a string, you cant. Strings are immutable. You can easily create a second string with:
String second = first.replaceFirst("(.)(.)", "$2$1");
Create a small function and use it anywhere
public SqlConnection con = "Your connection string";
public void gridviewUpdate()
{
con.Open();
string select = "SELECT * from table_name";
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataSet ds = new DataSet();
da.Fill(ds, "table_name");
datagridview.DataSource = ds;
datagridview.DataMember = "table_name";
con.Close();
}
Something like this would work.
def relative_time(start_time)
diff_seconds = Time.now - start_time
case diff_seconds
when 0 .. 59
puts "#{diff_seconds} seconds ago"
when 60 .. (3600-1)
puts "#{diff_seconds/60} minutes ago"
when 3600 .. (3600*24-1)
puts "#{diff_seconds/3600} hours ago"
when (3600*24) .. (3600*24*30)
puts "#{diff_seconds/(3600*24)} days ago"
else
puts start_time.strftime("%m/%d/%Y")
end
end
Try this:
Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")
Unfortunately the code found online was VB.NET not VBA.
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
In my case I solved the problem by establishing a valid column number when applying the order
property inside the script where you configure the data table.
var table = $('#mytable').DataTable({
.
.
.
order: [[ 1, "desc" ]],
See here.
iterator.nextIndex()
would provide index of element that would be returned by subsequent call to next()
.
If you hide the overflow and there is a long word, you risk loosing that word, so you could go one step further and use the "word-wrap" css attribute.
http://msdn.microsoft.com/en-us/library/ms531186(VS.85).aspx
OAuth is a protocol with which a 3-party app can access your data stored in another website without your account and password. For a more official definition, refer to the Wiki or specification.
Here is a use case demo:
I login to LinkedIn and want to connect some friends who are in my Gmail contacts. LinkedIn supports this. It will request a secure resource (my gmail contact list) from gmail. So I click this button:
A web page pops up, and it shows the Gmail login page, when I enter my account and password:
Gmail then shows a consent page where I click "Accept":
Now LinkedIn can access my contacts in Gmail:
Below is a flowchart of the example above:
Step 1: LinkedIn requests a token from Gmail's Authorization Server.
Step 2: The Gmail authorization server authenticates the resource owner and shows the user the consent page. (the user needs to login to Gmail if they are not already logged-in)
Step 3: User grants the request for LinkedIn to access the Gmail data.
Step 4: the Gmail authorization server responds back with an access token.
Step 5: LinkedIn calls the Gmail API with this access token.
Step 6: The Gmail resource server returns your contacts if the access token is valid. (The token will be verified by the Gmail resource server)
You can get more from details about OAuth here.
SELECT CONCAT(isnull(`affiliate_name`,''),'-',isnull(`model`,''),'-',isnull(`ip`,''),'-',isnull(`os_type`,''),'-',isnull(`os_version`,'')) AS device_name
FROM devices
If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.
java -jar myapp.jar --debug
You can also specify debug=true in your application.properties.
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.
Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
This issue happens if this project is being used by another project. Make sure you copy the app setting keys to the parent project's app.config or web.config.
I found an article under the above topic.There by I could take the full code .I will mention it.
Here are steps mentioned in the article:
Add embedded/result/ at the end of the JSFiddle URL you wanna grab.
Show the frame or the frame’s source code: right-click anywhere in the page and view the frame in a new tab or the source right-away (requires Firefox).
Finally, save the page in your preferred format (MHT, HTML, TXT, etc.) and voilà!
also you can find it : https://sirusdark.wordpress.com/2014/04/10/how-to-save-and-download-jsfiddle-code/
$('input[type=submit]').on('click', validate);
function validate() {
var password1 = $("#password1").val();
var password2 = $("#password2").val();
if(password1 == password2) {
$("#validate-status").text("valid");
}
else {
$("#validate-status").text("invalid");
}
}
Logic is to check on keyup if the value in both fields match or not.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
I have the same error, please go to
xampp\phpMyAdmin\libraries\config.default.php
Look for : $cfg['ExecTimeLimit'] = 600;
You can change '600' to any higher value, like '6000'.
Maximum execution time in seconds is (0 for no limit).
This will fix your error.
Add your style here:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
Then in the page:
<asp:Table CssClass=NewStyleExampleClass runat="server" >