This issue happened to me after adding .dae and .png files and converting .dae with XCode Editor to SceneKit scene file format (.scn).
After doing some more research I found the solution here - https://forums.developer.apple.com/thread/109951#336225
Steps to solve the issue:
I received this error after I moved from a 5s to a 6s. I recovered the new 6s from a backup of the old iPhone. Because of this on the new iPhone the old app was installed.
The old app did not show up in the 6s "Installed Apps" list! I manually deleted this old app from the 6s and everything was fine.
I had this error in Xcode 8 and Mac OS Sierra. Tried all the above solutions and none worked. This was the only one that worked for me. Open terminal, and type this in:
cd ~/Library/Developer/Xcode/DerivedData
xattr -c *
I had to delete all the provisioning profiles by following this article.
Had some issue. Resolve: go to right target -> capabilities -> for me there was issue with "In-App Purchase" and button to fix it. Off-on operation fixed issue.
FIX IDEA Hey guys so i have made an app and did not used any push notification functions but i still got an email. After checking the certificates, ids and profiles of the bundle identifier i used to create my app in apple store connect in the apple developer portal i realized that push notificiations were turned on.
What you have to do is:
go to apple developer login site where you can manage your certificates a.s.o 2. select "Certificates, IDs and Profiles" Tab on the right side 3. now select "Identifiers" 4. and the bundle id from the list to the right 5. now scroll down till you see push notification 6. turn it off 7. archive your build and reupload it to Apple Store Connect
Hope it helps!
If anyone is having this issue but is sure they have their certificates and code signing correctly set up, check the capabilities tab when you click on the project (i.e. next to build settings tab, build phases tab, etc).
In my case there were broken links for Game Center and In-App Purchases that needed fixing (by clicking the "fix me" buttons) to solve this issue.
I had the same issue was everyone else and tried all the above tricks, nothing worked. I even deleted and started fresh with a different developer account.
What worked for me in the end was
I don't know if you can enable that for a wildcard app, but after trying at least 12 different suggestions and losing a few days I hope this helps someone
If you are trying to activate iCloud syncing, you will need to enable iCloud for the AppID that is used to create the development provisioning profile (which Xcode does automatically). You'll also need to enable this for distribution profiles as well.
The tricky part is that when you refresh profiles in Xcode, this does not trigger a renewal of the profiles; they are simply re-downloaded. So in your iOS Provisioning Portal under Provisioning/Development, you'll need to check the profile that is labeled (Managed by Xcode) and delete it (Remove Selected button). Do this for ALL profiles, development & distribution, that you need to regenerate.
Now, in Xcode in the Organizer, delete provisioning profiles that you are about to replace.
Now to get new ones. If you develop for more than one team and only want to refresh a particular one, select the appropriate Team in the left pane under TEAMS, otherwise select Provisioning Profiles under LIBRARY, then select Refresh.
Finally, remove any old provisioning profiles on your device that could conflict with the new ones since profiles are never deleted automatically; newer profiles are simply added to the list.
In Xcode 5.1, if you go into Preferences -> Accounts -> View Details...
Make sure the Signing Identity status is Valid. If it says Revoked, hit the Plus button and add the appropriate signing identity: iOS Development or iOS Distribution. Xcode will replace it with a new, valid one.
[[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
[[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
used this in a function to look for an existing file and prompt before overwriting.
without mapping ? the quicker lambda solution
Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c - '0' ) );
…or same with the slower % operator
Integer.toString( num ).chars().boxed().collect( Collectors.summingInt( (c) -> c % '0' ) );
…or Unicode compliant
Integer.toString( num ).codePoints().boxed().collect( Collectors.summingInt( Character::getNumericValue ) );
#include <iostream>
using namespace std;
string getWord(istream& in)
{
int c;
string word;
// TODO: remove whitespace from begining of stream ?
while( !in.eof() )
{
c = in.get();
if( c == ' ' || c == '\t' || c == '\n' ) break;
word += c;
}
return word;
}
int main()
{
string word;
do {
word = getWord(cin);
cout << "[" << word << "]";
} while( word != "#");
return 0;
}
There are different ways but simplest would be to use the space-between see the example at the end
#container {
border: solid 1px #000;
display: flex;
flex-direction: row;
justify-content: space-between;
padding: 10px;
height: 50px;
}
.item {
width: 20%;
border: solid 1px #000;
text-align: center;
}
Anytime you're changing the headers of an HttpWebRequest
, you need to use the appropriate properties on the object itself, if they exist. If you have a plain WebRequest
, be sure to cast it to an HttpWebRequest
first. Then Referrer
in your case can be accessed via ((HttpWebRequest)request).Referrer
, so you don't need to modify the header directly - just set the property to the right value. ContentLength
, ContentType
, UserAgent
, etc, all need to be set this way.
IMHO, this is a shortcoming on MS part...setting the headers via Headers.Add()
should automatically call the appropriate property behind the scenes, if that's what they want to do.
Very helpful blog about Databinding : https://link.medium.com/HQY2VizKO1
class FragmentBinding<out T : ViewDataBinding>(
@LayoutRes private val resId: Int
) : ReadOnlyProperty<Fragment, T> {
private var binding: T? = null
override operator fun getValue(
thisRef: Fragment,
property: KProperty<*>
): T = binding ?: createBinding(thisRef).also { binding = it }
private fun createBinding(
activity: Fragment
): T = DataBindingUtil.inflate(LayoutInflater.from(activity.context),resId,null,true)
}
Declare binding val like this in Fragment :
private val binding by FragmentBinding<FragmentLoginBinding>(R.layout.fragment_login)
Don't forget to write this in fragment
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return binding.root
}
A query (modification of https://stackoverflow.com/a/7892349/1737819) to find a custom name table size in GB. You might try this, replace 'YourTableName' with the name of your table.
SELECT
t.NAME AS TableName,
p.rows AS RowCounts,
CONVERT(DECIMAL,SUM(a.total_pages)) * 8 / 1024 / 1024 AS TotalSpaceGB,
SUM(a.used_pages) * 8 / 1024 / 1024 AS UsedSpaceGB ,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024 / 1024 AS UnusedSpaceGB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME = 'YourTable'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
UsedSpaceGB DESC, t.Name
If it is in the same directory you can use dirname $0
:
#!/bin/bash
source $(dirname $0)/incl.sh
echo "The main script"
B4i is a new development tool that creates native iOS apps. It runs on Windows. When a full compilation is required (in most cases it is not required) the project is compiled on a hosted builder. Each compilation takes about 5 seconds. B4i
You could use a SUM
(not COUNT
!) combined with a CASE
statement, like this:
SELECT SUM(CASE WHEN myColumn=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
Note: in my own test NULL
s were not an issue, though this can be environment dependent. You could handle nulls such as:
SELECT SUM(CASE WHEN ISNULL(myColumn,0)=1 THEN 1 ELSE 0 END)
FROM AD_CurrentView
From React's documentation:
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls tosetState
and calls may be batched for performance gains.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
You can use:
border-style: solid;
border-width: thin;
border-color: #FFFFFF;
You can change these as you see fit, though.
This is what helped me when I found myself in the same problem:
npm uninstall -g angular-cli @angular/cli
npm cache clean --force
npm install -g @angular/cli@latest
One liner:
for file in *.php ; do mv "$file" "_$file" ; done
Try this example
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html
Make sure the client computer has the same or higher version of the .NET framework that you built your program to.
This is the modified version that I put in my code (I'm using .Net 4.5) but I think it should work on 4.0 too.
public void AppendText(string text, Color color, bool addNewLine = false)
{
box.SuspendLayout();
box.SelectionColor = color;
box.AppendText(addNewLine
? $"{text}{Environment.NewLine}"
: text);
box.ScrollToCaret();
box.ResumeLayout();
}
Differences with original one:
In my case it was a duplicate Swift Flag
entry inside my Target's Build Settings > Other Swift Flags. I had two -Xfrontend
entries in it.
While the GC compacts the small object heap as part of an optimization strategy to eliminate memory holes, the GC never compacts the large object heap for performance reasons**(the cost of compaction is too high for large objects (greater than 85KB in size))**. Hence if you are running a program that uses many large objects in an x86 system, you might encounter OutOfMemory exceptions. If you are running that program in an x64 system, you might have a fragmented heap.
I had the same problem, tnsnames.ora
worked fine for all other tools but SQL Developer would not use it. I tried all the suggestions on the web I could find, including the solutions on the link provided here.
Nothing worked.
It turns out that the database was caching backup copies of tnsnames.ora
like tnsnames.ora.bk2
, tnsnames09042811AM4501.bak
, tnsnames.ora.bk
etc. These files were not readable by the average user.
I suspect sqldeveloper is pattern matching for the name and it was trying to read one of these backup copies and couldn't. So it just fails gracefully and shows nothing in drop down list.
The solution is to make all the files readable or delete or move the backup copies out of the Admin directory.
I have had this problem several times and it can be usually resolved with a clean and rebuild as answered by many before me. But this time this would not fix it.
I use my cordova app to build 2 seperate apps that share majority of the same codebase and it drives off the config.xml. I could not build in end up because i had a space in my id.
com.company AppName
instead of:
com.company.AppName
If anyone is in there config as regular as me. This could be your problem, I also have 3 versions of each app. Live / Demo / Test - These all have different ids.
com.company.AppName.Test
Easy mistake to make, but even easier to overlook. Spent loads of time rebuilding, checking plugins, versioning etc. Where I should have checked my config. First Stop Next Time!
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true
parameter.
Assume you have a post
object and each one can have a number of comments
:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET
request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true
.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true
:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length
).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
You can't delete a foreign key if it still references another table. First delete the reference
delete from kontakty
where id_osoby = 1;
DELETE FROM osoby
WHERE id_osoby = 1;
You cannot resize an array in java.
Once the size of array is declared, it remains fixed.
Instead you can use ArrayList
that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.
ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);
String s4 ="Test4";
ar.add(s4);
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* @author sashant
*/
public class SimpleJava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}
In C#
8.0 and later you can use [^5..]
to get the last five characters combined with a ?
operator to avoid a potential ArgumentOutOfRangeException
.
string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123
Works for Android KitKat and above (For those who want to transparent the status bar and don't manipulate the NavigationBar, because all of these answers will transparent the NavigationBar too!)
The easiest way to achieve it:
Put these 3 lines of code in the styles.xml (v19)
-> if you don't know how to have this (v19), just write them in your default styles.xml
and then use alt+enter to automatically create it:
<item name="android:windowFullscreen">false</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:fitsSystemWindows">false</item>
And now, go to your MainActivity
Class and put this Method out of onCreate in the class:
public static void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
Then put this code in the onCreate
method of the Activity:
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
//make fully Android Transparent Status bar
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
That's it!
If there are multiple ways a user might order person, you could also have multiple Comparators setup as constants somewhere. Most of the sort operations and sorted collections take a comparator as a parameter.
Ruby provides a built-in function for checking the length of a string. Say it's called s
:
if s.length <= 25
# We're OK
else
# Too long
end
This worked for me:
$this->db->where('RecordDate >=', '2018-08-17 00:00:00');
$this->db->where('RecordDate <=', '2018-10-04 05:32:56');
The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.
In Enums.NET you'd use:
string description = ((MyEnum)value).AsString(EnumFormat.Description);
I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:
string description = Enums.GetDescription((MyEnum)value);
This:
I realise the core answer was just the cast from an int
to MyEnum
, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)
No.
Equality is equality.
The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.
If you really want to test two doubles for equality, use this one:
inline bool isEqual(double x, double y)
{
return x == y;
}
Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y
is the code you want.
10.000000000000001 is not equal to 10.0, no matter what they tell you.
An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:
const double NO_DATA = -1.0;
double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);
if (myData != NO_DATA)
{
...
}
I would point out that (functionally) there's a BIG difference between cycles and/or multiple paths in the SCHEMA and the DATA. While cycles and perhaps multipaths in the DATA could certainly complicated processing and cause performance problems (cost of "properly" handling), the cost of these characteristics in the schema should be close to zero.
Since most apparent cycles in RDBs occur in hierarchical structures (org chart, part, subpart, etc.) it is unfortunate that SQL Server assumes the worst; i.e., schema cycle == data cycle. In fact, if you're using RI constraints you can't actually build a cycle in the data!
I suspect the multipath problem is similar; i.e., multiple paths in the schema don't necessarily imply multiple paths in the data, but I have less experience with the multipath problem.
Of course if SQL Server did allow cycles it'd still be subject to a depth of 32, but that's probably adequate for most cases. (Too bad that's not a database setting however!)
"Instead of Delete" triggers don't work either. The second time a table is visited, the trigger is ignored. So, if you really want to simulate a cascade you'll have to use stored procedures in the presence of cycles. The Instead-of-Delete-Trigger would work for multipath cases however.
Celko suggests a "better" way to represent hierarchies that doesn't introduce cycles, but there are tradeoffs.
I use this method:
var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);
I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
The "string to long" (strtol
) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:
#include <stdlib.h>
long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)
Since we use the decimal system, base is 10. The endpointer
argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL
instead of passing a pointer, as shown.
If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0
is always the last character of a string in C:
#include <stdlib.h>
char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string
As the man page mentions, you can use errno
to check that no errors occurred (in this case overflows or underflows).
#include <stdlib.h>
#include <errno.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
// Everything went well, print it as 'long decimal'
printf("%ld", arg);
So now we are stuck with this long
, but we often want to work with integers. To convert a long
into an int
, we should first check that the number is within the limited capacity of an int
. To do this, we add a second if-statement, and if it matches, we can just cast it.
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number
printf("%d", arg_int);
To see what happens if you don't do this check, test the code without the INT_MIN
/MAX
if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.
#include <stdio.h> // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h> // for errno
#include <limits.h> // for INT_MIN and INT_MAX
int main(int argc, char** argv) {
char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
return 1; // In main(), returning non-zero means failure
}
if (arg < INT_MIN || arg > INT_MAX) {
return 1;
}
int arg_int = arg;
// Everything went well, print it as a regular number plus a newline
printf("Your value was: %d\n", arg_int);
return 0;
}
In Bash, you can test this with:
cc code.c -o example # Compile, output to 'example'
./example $((2**31-1)) # Run it
echo "exit status: $?" # Show the return value, also called 'exit status'
Using 2**31-1
, it should print the number and 0
, because 231-1 is just in range. If you pass 2**31
instead (without -1
), it will not print the number and the exit status will be 1
.
Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc
), test whether the number is in the range that you want, etc.
No need to convert. You can apply conditions on Enums inside a switch. Like so,
public enum Operator
{
PLUS,
MINUS,
MULTIPLY,
DIVIDE
}
public double Calculate(int left, int right, Operator op)
{
switch (op)
{
case Operator.PLUS: return left + right;
case Operator.MINUS: return left - right;
case Operator.MULTIPLY: return left * right;
case Operator.DIVIDE: return left / right;
default: return 0.0;
}
}
Then, call it like this:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));
A more elegant approach to build bigrams with python’s builtin zip()
.
Simply convert the original string into a list by split()
, then pass the list once normally and once offset by one element.
string = "I really like python, it's pretty awesome."
def find_bigrams(s):
input_list = s.split(" ")
return zip(input_list, input_list[1:])
def find_ngrams(s, n):
input_list = s.split(" ")
return zip(*[input_list[i:] for i in range(n)])
find_bigrams(string)
[('I', 'really'), ('really', 'like'), ('like', 'python,'), ('python,', "it's"), ("it's", 'pretty'), ('pretty', 'awesome.')]
Missing from these answers is how to get a file dialog without a input element on the page.
The function to show the input file dialog.
function openFileDialog (accept, callback) { // this function must be called from a user
// activation event (ie an onclick event)
// Create an input element
var inputElement = document.createElement("input");
// Set its type to file
inputElement.type = "file";
// Set accept to the file types you want the user to select.
// Include both the file extension and the mime type
inputElement.accept = accept;
// set onchange event to call callback when user has selected file
inputElement.addEventListener("change", callback)
// dispatch a click event to open the file dialog
inputElement.dispatchEvent(new MouseEvent("click"));
}
NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.
NOTE
input.accept
is not used in Edge
Calling above function when user clicks an anchor element.
// wait for window to load
window.addEventListener("load", windowLoad);
// open a dialog function
function openFileDialog (accept, multy = false, callback) {
var inputElement = document.createElement("input");
inputElement.type = "file";
inputElement.accept = accept; // Note Edge does not support this attribute
if (multy) {
inputElement.multiple = multy;
}
if (typeof callback === "function") {
inputElement.addEventListener("change", callback);
}
inputElement.dispatchEvent(new MouseEvent("click"));
}
// onload event
function windowLoad () {
// add user click event to userbutton
userButton.addEventListener("click", openDialogClick);
}
// userButton click event
function openDialogClick () {
// open file dialog for text files
openFileDialog(".txt,text/plain", true, fileDialogChanged);
}
// file dialog onchange event handler
function fileDialogChanged (event) {
[...this.files].forEach(file => {
var div = document.createElement("div");
div.className = "fileList common";
div.textContent = file.name;
userSelectedFiles.appendChild(div);
});
}
_x000D_
.common {
font-family: sans-serif;
padding: 2px;
margin : 2px;
border-radius: 4px;
}
.fileList {
background: #229;
color: white;
}
#userButton {
background: #999;
color: #000;
width: 8em;
text-align: center;
cursor: pointer;
}
#userButton:hover {
background : #4A4;
color : white;
}
_x000D_
<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>
_x000D_
Warning the above snippet is written in ES6.
select (case when locate('(', LocationName) = 0
then
horse_name
else
left(LocationName, locate('(', LocationName) - 1)
end) as Country
from tblcountry;
Use grep -n
to get the line number of a match.
I don't think there's a way to get grep to start on a certain line number. For that, use sed. For example, to start at line 10 and print the line number and line for matching lines, use:
sed -n '10,$ { /regex/ { =; p; } }' file
To get only the line numbers, you could use
grep -n 'regex' | sed 's/^\([0-9]\+\):.*$/\1/'
Or you could simply use sed:
sed -n '/regex/=' file
Combining the two sed commands, you get:
sed -n '10,$ { /regex/= }' file
Please note that both the HTML5 specification of W3C and WhatWG standardize
<link rel="icon" href="/favicon.ico">
Note the value of the "rel" attribute!
The value shortcut icon
for the rel
attribute is a very old Internet Explorer specific extension and deprecated.
So please consider not using it any more and updating your files so they are standards compliant and are displayed correctly in all browsers.
You might also want to take a look at this great post: rel="shortcut icon" considered harmful
Example URL: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ
A) Don't use suggested unsafe PATHINFO
:
pathinfo($url)['dirname'] 'http://example.com/myfolder'
pathinfo($url)['basename'] 'sympony.mp3?a=1&b=2#XYZ' // <------- BAD !!
pathinfo($url)['extension'] 'mp3?a=1&b=2#XYZ' // <------- BAD !!
pathinfo($url)['filename'] 'sympony'
B) Use PARSE_URL:
parse_url($url)['scheme'] 'http'
parse_url($url)['host'] 'example.com'
parse_url($url)['path'] '/myfolder/sympony.mp3'
parse_url($url)['query'] 'aa=1&bb=2'
parse_url($url)['fragment'] 'XYZ'
BONUS: View all native PHP examples
I solved this issue with simple lines of code as the android documentation explains.
(https://developer.android.com/guide/components/intents-common.html#Email)
The most important is the flag: it is ACTION_SENDTO
, and not ACTION_SEND
The other important line is
intent.setData(Uri.parse("mailto:")); ***// only email apps should handle this***
By the way, if you send an empty Extra
, the if()
at the end won't work and the app won't launch the email client.
According to Android documentation. If you want to ensure that your intent is handled only by an email app (and not other text messaging or social apps), then use the ACTION_SENDTO
action and include the "mailto:
" data scheme. For example:
public void composeEmail(String[] addresses, String subject) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
In MySQL, "Group By
" uses an extra step: filesort
. I realize DISTINCT
is faster than GROUP BY
, and that was a surprise.
In case you are using JQuery 2.x then please add the following in the
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge;" />
</head>
<body>
...
</body>
</html>
This worked for me.
I did this by going to setting>Keyboard Shortcuts then in the section where it give a search bar type focus terminal and select the option. It will ask to type the combination which you want to set for this action. DO it. As for editor focus type" editor focus" in the search bar and type your desired key. IF you excellently add a key . it can be removed by going to edit jason as mentioned in above comments
Another option I have googled, but contains several replace ...
SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '')
For other people coming upon this post on google. There are 2 options, either merging or rebasing your branch. Both works differently, but have similar outcomes.
The accepted answer is a rebase. This will take all the commits done to our-team
and then apply the commits done to featurex
, prompting you to merge them as needed.
One bit caveat of rebasing is that you lose/rewrite your branch history, essentially telling git that your branch did not began at commit 123abc but at commit 456cde. This will cause problems for other people working on the branch, and some remote tools will complain about it. If you are sure about what you are doing though, that's what the --force
flag is for.
What other posters are suggesting is a merge. This will take the featurex
branch, with whatever state it has and try to merge it with the current state of our-team
, prompting you to do one, big, merge commit and fix all the merge errors before pushing to our-team
. The difference is that you are applying your featurex
commits before the our-team
new commits and then fixing the differences. You also do not rewrite history, instead adding one commit to it instead of rewriting those that came before.
Both options are valid and can work in tandem. What is usually (by that I mean, if you are using widespread tools and methodology such as git-flow) done for a feature branch is to merge it into the main branch, often going through a merge-request, and solve all the conflicts that arise into one (or multiple) merge commits.
Rebasing is an interesting option, that may help you fix your branch before eventually going through a merge, and ease the pain of having to do one big merge commit.
You need to escape:
<div class="test">&times</div>
And then read the value using text() to get the unescaped value:
alert($(".test").text()); // outputs: ×
Assuming WinForms, the ForeColor property allows to change all the text in the TextBox
(not just what you're about to add):
TextBox.ForeColor = Color.Red;
To only change the color of certain words, look at RichTextBox.
where stateb is List'' bucket is a two dimensional array
statesb= IntStream.of(bucket[j-1]).boxed().collect(Collectors.toList());
with import java.util.stream.IntStream;
see https://examples.javacodegeeks.com/core-java/java8-convert-array-list-example/
$("#yourdivid textarea, #yourdivid input, #yourdivid select").attr('disabled',true);
Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.
.order_by("TableName.name desc")
Use brackets. So to look for 75%
WHERE MyCol LIKE '%75[%]%'
This is simpler than ESCAPE and common to most RDBMSes.
To read in an Unicode string and then send to HTML, I did this:
fileline.decode("utf-8").encode('ascii', 'xmlcharrefreplace')
Useful for python powered http servers.
seeing it in digital circuit domain
so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment
Execute something similar to the following command:
aws s3 cp local_folder_name s3://s3_bucket_name/local_folder_name/ --recursive
Start by turning the text into a list of lists. That will take care of the parsing part:
lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))
The rest can be done with indexed lookups:
d = dict()
key = lol[6][0] # cell A7
value = lol[6][3] # cell D7
d[key] = value # add the entry to the dictionary
...
I would consider using something like:
function GetList
{
. {
$a = new-object Collections.ArrayList
$a.Add(5)
$a.Add('next 5')
} | Out-Null
$a
}
$x = GetList
Output from $a.Add
is not returned -- that holds for all $a.Add
method calls. Otherwise you would need to prepend [void]
before each the call.
In simple cases I would go with [void]$a.Add
because it is quite clear that output will not be used and is discarded.
You can't format the Date
itself. You can only get the formatted result in String
. Use SimpleDateFormat
as mentioned by others.
Moreover, most of the getter methods in Date
are deprecated.
There are two ways. One is to aggregate:
SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'
The other is to use an array constructor:
SELECT ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name = 'aean')
I'm presuming this is for plpgsql. In that case you can assign it like this:
colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);
I suggest using DateUtils from apache.commons library.
long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );
Edit: Fixed Calendar.MILISECOND
to Calendar.MILLISECOND
With the following,
#include <iomanip>
#include <iostream>
int main()
{
std::cout << std::setfill('0') << std::setw(5) << 25;
}
the output will be
00025
setfill
is set to the space character (' '
) by default. setw
sets the width of the field to be printed, and that's it.
If you are interested in knowing how the to format output streams in general, I wrote an answer for another question, hope it is useful: Formatting C++ Console Output.
Any attribute that starts with data-
is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel
and other attributes for purposes other than their original intended purposes (rel
was often used to hold data for things like advanced tooltips).
In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).
html5doctor has a good article on the data- attribute.
Cycle 2 is another example of extensive use of the data- attribute.
It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).
Have you tried setting the scroll direction of your UICollectionViewFlowLayout to horizontal?
[yourFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
And if you want it to page like springboard does, you'll need to enable paging on your collection view like so:
[yourCollectionView setPagingEnabled:YES];
I like to use the semicolons only for the WHILE statement, and the && operator to make the loop do more than one thing...
So I always do it like this
while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done
For Windows users, run npm
commands from the Command Prompt (cmd.exe), not Node.Js (node.exe). So your "normal shell" is cmd.exe. (I agree this message can be confusing for a Windows, Node newbie.)
By the way, the Node.js Command Prompt is actually just an easy shortcut to cmd.exe.
Below is an example screenshot for installing grunt from cmd.exe:
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
I am not sure but you can try intialising handler to null in onDestroy()
Make sure that /etc/hosts.allow contains:
ssh:ALL:allow
sshd:ALL:allow
OR
ssh:localhost:allow
sshd:localhost:allow
OR - some other variant
ssh:{host1,host2,host3...}:allow
sshd{host1,host2,host3...}:allow
INSURE that the first line in the file DOES NOT begin with ALL:ALL:DENY
NOTHING will be able to communicate with the host... on any port.
var words_in_text = function (text) {
var regex = /([\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]+)/g;
return text.match(regex);
};
words_in_text('Düsseldorf, Köln, ??????, ???, ??????? !@#$');
// returns array ["Düsseldorf", "Köln", "??????", "???", "???????"]
This regex will match all words in the text of any language...
If you need to check if all the digits are number (0-9) or not,
^[0-9]+$
1425 TRUE
0142 TRUE
0 TRUE
1 TRUE
154a25 FALSE
1234=3254 FALSE
No binding support for File Upload control
https://github.com/angular/angular.js/issues/1375
<div ng-controller="form-cntlr">
<form>
<button ng-click="selectFile()">Upload Your File</button>
<input type="file" style="display:none"
id="file" name='file' onchange="angular.element(this).scope().fileNameChanged(this)" />
</form>
</div>
instead of
<input type="file" style="display:none"
id="file" name='file' ng-Change="fileNameChanged()" />
can you try
<input type="file" style="display:none"
id="file" name='file' onchange="angular.element(this).scope().fileNameChanged()" />
Note: this requires the angular application to always be in debug mode. This will not work in production code if debug mode is disabled.
and in your function changes instead of
$scope.fileNameChanged = function() {
alert("select file");
}
can you try
$scope.fileNameChanged = function() {
console.log("select file");
}
Below is one working example of file upload with drag drop file upload may be helpful http://jsfiddle.net/danielzen/utp7j/
Angular File Upload Information
URL for AngularJS File Upload in ASP.Net
http://cgeers.com/2013/05/03/angularjs-file-upload/
AngularJs native multi-file upload with progress with NodeJS
http://jasonturim.wordpress.com/2013/09/12/angularjs-native-multi-file-upload-with-progress/
ngUpload - An AngularJS Service for uploading files using iframe
Use notifyDataSetChanged()
instead notifyItem...
in this case.
This worked for me,
1. For getting Columns having at least 1 null value. (column names)
data.columns[data.isnull().any()]
2. For getting Columns with count, with having at least 1 null value.
data[data.columns[data.isnull().any()]].isnull().sum()
[Optional] 3. For getting percentage of the null count.
data[data.columns[data.isnull().any()]].isnull().sum() * 100 / data.shape[0]
A small addition to KTC's very informative main answer:
If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).
I could fix this using the following: inbetween the steps described above as
I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:
I found this info here: http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html
If you're using .NET version 3.0 or lower, you have to use XmlDocument
aka the classic DOM API. Likewise you'll find there are some other APIs which will expect this.
If you get the choice, however, I would thoroughly recommend using XDocument
aka LINQ to XML. It's much simpler to create documents and process them. For example, it's the difference between:
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
root.SetAttribute("name", "value");
XmlElement child = doc.CreateElement("child");
child.InnerText = "text node";
root.AppendChild(child);
doc.AppendChild(root);
and
XDocument doc = new XDocument(
new XElement("root",
new XAttribute("name", "value"),
new XElement("child", "text node")));
Namespaces are pretty easy to work with in LINQ to XML, unlike any other XML API I've ever seen:
XNamespace ns = "http://somewhere.com";
XElement element = new XElement(ns + "elementName");
// etc
LINQ to XML also works really well with LINQ - its construction model allows you to build elements with sequences of sub-elements really easily:
// Customers is a List<Customer>
XElement customersElement = new XElement("customers",
customers.Select(c => new XElement("customer",
new XAttribute("name", c.Name),
new XAttribute("lastSeen", c.LastOrder)
new XElement("address",
new XAttribute("town", c.Town),
new XAttribute("firstline", c.Address1),
// etc
));
It's all a lot more declarative, which fits in with the general LINQ style.
Now as Brannon mentioned, these are in-memory APIs rather than streaming ones (although XStreamingElement
supports lazy output). XmlReader
and XmlWriter
are the normal ways of streaming XML in .NET, but you can mix all the APIs to some extent. For example, you can stream a large document but use LINQ to XML by positioning an XmlReader
at the start of an element, reading an XElement
from it and processing it, then moving on to the next element etc. There are various blog posts about this technique, here's one I found with a quick search.
You can also split the element into two via HTML + JS.
HTML:
<div class='justificator'>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a
type specimen book.
</div>
JS:
function justify() {
// Query for elements search
let arr = document.querySelectorAll('.justificator');
for (let current of arr) {
let oldHeight = current.offsetHeight;
// Stores cut part
let buffer = '';
if (current.innerText.lastIndexOf(' ') >= 0) {
while (current.offsetHeight == oldHeight) {
let lastIndex = current.innerText.lastIndexOf(' ');
buffer = current.innerText.substring(lastIndex) + buffer;
current.innerText = current.innerText.substring(0, lastIndex);
}
let sibling = current.cloneNode(true);
sibling.innerText = buffer;
sibling.classList.remove('justificator');
// Center
sibling.style['text-align'] = 'center';
current.style['text-align'] = 'justify';
// For devices that do support text-align-last
current.style['text-align-last'] = 'justify';
// Insert new element after current
current.parentNode.insertBefore(sibling, current.nextSibling);
}
}
}
document.addEventListener("DOMContentLoaded", justify);
Here is an example with div and p tags
function justify() {_x000D_
// Query for elements search_x000D_
let arr = document.querySelectorAll('.justificator');_x000D_
for (let current of arr) {_x000D_
let oldHeight = current.offsetHeight;_x000D_
// Stores cut part_x000D_
let buffer = '';_x000D_
_x000D_
if (current.innerText.lastIndexOf(' ') >= 0) {_x000D_
while (current.offsetHeight == oldHeight) {_x000D_
let lastIndex = current.innerText.lastIndexOf(' ');_x000D_
buffer = current.innerText.substring(lastIndex) + buffer;_x000D_
current.innerText = current.innerText.substring(0, lastIndex);_x000D_
}_x000D_
let sibling = current.cloneNode(true);_x000D_
sibling.innerText = buffer;_x000D_
sibling.classList.remove('justificator');_x000D_
// Center_x000D_
sibling.style['text-align'] = 'center';_x000D_
// For devices that do support text-align-last_x000D_
current.style['text-align-last'] = 'justify';_x000D_
current.style['text-align'] = 'justify';_x000D_
// Insert new element after current_x000D_
current.parentNode.insertBefore(sibling, current.nextSibling);_x000D_
}_x000D_
}_x000D_
}_x000D_
justify();
_x000D_
p.justificator {_x000D_
margin-bottom: 0px;_x000D_
}_x000D_
p.justificator + p {_x000D_
margin-top: 0px;_x000D_
}
_x000D_
<div class='justificator'>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
<p class='justificator'>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p><p>Some other text</p>
_x000D_
In your php.ini
configuration file simply uncomment the extension:
;extension=pdo_mysql
(You can find your php.ini file in the php folder where your server is installed.)
make this to
extension=pdo_mysql
now you need to configure your .env file in find DB_DATABASE=
write in that database name which you used than migrate like if i used my database and database name is "abc" than i need to write there DB_DATABASE=abc
and save that .env file and run command again
php artisan migrate
so after run than you got some msg like as:
php artisan migrate
Migration table created successfully.
Another way is presented here
http://gilfster.blogspot.co.at/2006/03/debugging-stored-procedures-in-mysql.html
with custom debug mySql procedures and logging tables.
You can also just place a simple select in your code and see if it is executed.
SELECT 'Message Text' AS `Title`;
I got this idea from
http://forums.mysql.com/read.php?99,78155,78225#msg-78225
Also somebody created a template for custom debug procedures on GitHub.
See here
http://www.bluegecko.net/mysql/debugging-stored-procedures/ https://github.com/CaptTofu/Stored-procedure-debugging-routines
Was mentioned here
How to catch any exception in triggers and store procedures for mysql?
Just do one thing, We need to set the name property for the same types. for eg.
Try below:
<form>
<div id="group1">
<input type="radio" value="val1" name="group1">
<input type="radio" value="val2" name="group1">
</div>
</form>
And also we can do it in angular1,angular 2 or in jquery also.
<div *ngFor="let option of question.options; index as j">
<input type="radio" name="option{{j}}" value="option{{j}}" (click)="checkAnswer(j+1)">{{option}}
</div>
You can use Func which encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
void Method()
{
Func<string,string> inlineFunction = source =>
{
// add your functionality here
return source ;
};
// call the inline function
inlineFunction("prefix");
}
Had the same problem here but a different solution worked.
First, I tried the following, none of which worked:
Load symbols as suggested by seanlitow
Remove/Add reference to PresentationFramework and PresentationCore
The solution was to undo the last few changes I had made to my code. I had just added a couple radio buttons and event handlers for checked and unchecked events. After removing my recent changes everything compiled. I then added my exact changes back and everything compiled properly. I don't understand why this worked - only thing I can think of is a problem with my VS Solution. Anyway, if none of the other suggestions work, you might try reverting back your most recent changes. NOTE: if you close & re-open Visual Studio your undo history is lost.. so you might try this before you close VS.
Use NestedScrollView with viewport true is working good for me
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="700dp">
</android.support.constraint.ConstraintLayout>
</android.support.v4.widget.NestedScrollView>
for android x use this
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
.....other views....
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.
class NormalizeData:
def __init__(self, element):
self.element = element
def execute(self):
if isinstance(self.element, dict):
self.__iterate()
else:
return
def __iterate(self):
for key in self.element:
if isinstance(self.element[key], <ClassName>):
self.element[key] = str(self.element[key])
node = NormalizeData(self.element[key])
node.execute()
Apache HttpComponents also have an async http client now too:
/**
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0-beta4</version>
</dependency>
**/
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
public class HttpTest {
public static void main(final String[] args) throws Exception {
final CloseableHttpAsyncClient httpclient = HttpAsyncClients
.createDefault();
httpclient.start();
try {
final Future<Boolean> future = httpclient.execute(
HttpAsyncMethods.createGet("http://www.google.com/"),
new MyResponseConsumer(), null);
final Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("Request successfully executed");
} else {
System.out.println("Request failed");
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {
@Override
protected void onResponseReceived(final HttpResponse response) {
}
@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl)
throws IOException {
while (buf.hasRemaining()) {
System.out.print(buf.get());
}
}
@Override
protected void releaseResources() {
}
@Override
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}
}
}
Here is my take:
cmake_minimum_required(VERSION 3.15)
project(TryOuts LANGUAGES CXX)
find_package(Boost QUIET REQUIRED COMPONENTS program_options)
if(NOT Boost_FOUND)
message(FATAL_ERROR "Boost Not found")
endif()
add_executable(helloworld main.cpp)
target_link_libraries(helloworld PUBLIC Boost::program_options)
VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.
ctrl+k+t
in windows/ubuntu or cmd+k+t
on mac.ctrl+shift+p
in windows/ubuntu or cmd+shift+p
on mac and type color
. Select preferences: color theme
from the options, to select your favourite color.category:themes
to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs
)Edit - for manually editing colors in terminal
VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766
$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);
$response = $client->post('/save', [
'json' => [
'name' => 'John Doe'
]
]);
return $response->getBody();
You can do this:
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.Ignore());
Or, in latest version of Automapper, you simply want to tell Automapper to not validate the field
conf.CreateMap<SourceType, DestinationType>()
.ForSourceMember(x => x.SourceProperty, y => y.DoNotValidate());
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
A cool answer to other problems. If you do not want to differentiate "com.myapp.debug" and "com.myapp.release" for example !
public static boolean isAppInstalled(final Context context, final String packageName) {
final List<ApplicationInfo> appsInfo = context.getPackageManager().getInstalledApplications(0);
for (final ApplicationInfo appInfo : appsInfo) {
if (appInfo.packageName.contains(packageName)) return true;
}
return false;
}
In order to best standardise your @font-face embedded fonts across browsers try including the below inside your @font-face declaration or on your body font styling:
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
At present there looks to be no universal fix across all platforms and browser builds. As stated frequently all browsers/OS have different text rendering engines.
git diff master~20 -- pom.xml
Works if you are not in master branch too.
To add to Preston's answer, here's the complete list of the HttpContent
derived classes available in the standard library:
Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/
There's also a supposed ObjectContent
but I was unable to find it in ASP.NET Core
.
Of course, you could skip the whole HttpContent
thing all together with Microsoft.AspNet.WebApi.Client
extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:
var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
Title = "New Article Title",
Body = "New Article Body"
});
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
When using a glob pattern, a question mark represents a single character and an asterisk represents a sequence of zero or more characters:
if [[ $gg == ????grid* ]] ; then echo $gg; fi
When using a regular expression, a dot represents a single character and an asterisk represents zero or more of the preceding character. So ".*
" represents zero or more of any character, "a*
" represents zero or more "a", "[0-9]*
" represents zero or more digits. Another useful one (among many) is the plus sign which represents one or more of the preceding character. So "[a-z]+
" represents one or more lowercase alpha character (in the C locale - and some others).
if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi
Catching an exception while using a Python 'with' statement
The with statement has been available without the __future__
import since Python 2.6. You can get it as early as Python 2.5 (but at this point it's time to upgrade!) with:
from __future__ import with_statement
Here's the closest thing to correct that you have. You're almost there, but with
doesn't have an except
clause:
with open("a.txt") as f: print(f.readlines()) except: # <- with doesn't have an except clause. print('oops')
A context manager's __exit__
method, if it returns False
will reraise the error when it finishes. If it returns True
, it will suppress it. The open
builtin's __exit__
doesn't return True
, so you just need to nest it in a try, except block:
try:
with open("a.txt") as f:
print(f.readlines())
except Exception as error:
print('oops')
And standard boilerplate: don't use a bare except:
which catches BaseException
and every other possible exception and warning. Be at least as specific as Exception
, and for this error, perhaps catch IOError
. Only catch errors you're prepared to handle.
So in this case, you'd do:
>>> try:
... with open("a.txt") as f:
... print(f.readlines())
... except IOError as error:
... print('oops')
...
oops
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
tf.keras.backend.eval
is useful for evaluating small expressions.
tf.keras.backend.eval(op)
TF 1.x and TF 2.0 compatible.
Minimal Verifiable Example
from tensorflow.keras.backend import eval
m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])
eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)
This is useful because you do not have to explicitly create a Session
or InteractiveSession
.
SendRedirect()
will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher
is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect()
method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
Assuming the changes you want are at the head of the branch you want the changes from, use git checkout
for a single file :
git checkout branch_that_has_the_changes_you_want path/to/file.rb
for multiple files just daisy chain :
git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb
Use String.Equals Method
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.Equals(description, StringComparison.OrdinalIgnoreCase));
}
While working with spark in EMR I was having the same problem and setting maximizeResourceAllocation=true
did the trick; hope it helps someone. You have to set it when you create the cluster. From the EMR docs:
aws emr create-cluster --release-label emr-5.4.0 --applications Name=Spark \
--instance-type m3.xlarge --instance-count 2 --service-role EMR_DefaultRole --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole --configurations https://s3.amazonaws.com/mybucket/myfolder/myConfig.json
Where myConfig.json should say:
[
{
"Classification": "spark",
"Properties": {
"maximizeResourceAllocation": "true"
}
}
]
Dokan looks like a FUSE and sshfs implementation for Windows. If it works as expected and advertised, it would do exactly what you are looking for.
(Link updated and working 2015-10-15)
Maybe you have a hardware problem.
I had the same problem on my old system (AMD 1800 MHz CPU ,1GB RAM ,Windows 7 Ultimate) ,until I changed the 2x 512 MB RAM to 2x 1GB RAM. Haven't had any problems since. Also other (minor) problems disappeared. Guess those two 512 MB modules didn't like each other that much ,because 2x 512 MB + 1GB or 1x 512 MB + 2x 1GB didn't work properly either.
About performance:
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = "Hi " + i + "; Hi to you " + i*2;
}
long end = System.currentTimeMillis();
System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
start = System.currentTimeMillis();
for(int i = 0; i < 1000000; i++){
String s = String.format("Hi %s; Hi to you %s",i, + i*2);
}
end = System.currentTimeMillis();
System.out.println("Format = " + ((end - start)) + " millisecond");
}
The timing results are as follows:
Therefore, concatenation is much faster than String.format.
Change it to:
std::string s;
std::string* pS = &s;
myfunc(pS);
EDIT:
This is called ref-to-pointer
and you cannot pass temporary address as a reference to function. ( unless it is const reference
).
Though, I have shown std::string* pS = &s;
(pointer to a local variable), its typical usage would be :
when you want the callee to change the pointer itself, not the object to which it points. For example, a function that allocates memory and assigns the address of the memory block it allocated to its argument must take a reference to a pointer, or a pointer to pointer:
void myfunc(string*& val)
{
//val is valid even after function call
val = new std::string("Test");
}
You probably already know about $(document).ready(...). What you need is a preloading mechanism; something that fetches data (text or images or whatever) before showing it off. This can make a site feel much more professional.
Take a look at jQuery.Preload (there are others). jQuery.Preload has several ways of triggering preloading, and also provides callback functionality (when the image is preloaded, then show it). I have used it heavily, and it works great.
Here's how easy it is to get started with jQuery.Preload:
$(function() {
// First get the preload fetches under way
$.preload(["images/button-background.png", "images/button-highlight.png"]);
// Then do anything else that you would normally do here
doSomeStuff();
});
you cannot assign null to a var type.
If you assign null the compiler cannot find the variable you wanted in var place.
throws error: Cannot assign <null> to an implicitly-typed local variable
you can try this:
var dummy =(string)null;
Here compiler can find the type you want so no problem
You can assign some empty values.
var dummy = string.Empty;
or
var dummy = 0;
Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).
git checkout -b temp_branch HEAD~2
Then squash commit the other branch in this new branch:
git merge branch_with_two_commits --squash
That will bring in the changes but not commit them. So just commit them and you're done.
git commit -m "my message"
Now you can merge this new topic branch back into your main branch.
Check in many folders :
Folder_1 and folder_2 are name of folders, from which we have to select files.
$format is required format.
<?php
$arr = array("folder_1","folder_2");
$format = ".csv";
for($x=0;$x<count($arr);$x++){
$mm = $arr[$x];
foreach (glob("$mm/*$format") as $filename) {
echo "$filename size " . filesize($filename) . "<br>";
}
}
?>
Just a small correction to the first answer in this thread.
Even for Stack, you need to create new object with generics if you are using Stack from java util packages.
Right usage:
Stack<Integer> s = new Stack<Integer>();
Stack<String> s1 = new Stack<String>();
s.push(7);
s.push(50);
s1.push("string");
s1.push("stack");
if used otherwise, as mentioned in above post, which is:
/*
Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);
*/
Although this code works fine, has unsafe or unchecked operations which results in error.
As mentioned several times here
-webkit-appearance:none;
also removes the arrows, which is not what you want in most cases.
An easy workaround I found is to simply use select2 instead of select. You can re-style a select2 element as well, and most importantly, select2 looks the same on Windows, Android, iOS and Mac.
I also had a very similar issue with a very similar error message. My issue was that the database could not be connected to. In our case, we have mirrored databases and the connection string did not specify the Failover Partner. So when the database couldn't connect, it never went to the mirror and was throwing this error. Once I specified the Failover Partner in the connection string for my datasource, it resolved the issue.
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA <> 'x' AND columbB <> 'y'";
I'd suggest using the diamond operator (<>) in favor of != as the first one is valid SQL and the second one is a MySQL addition.
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
swift 3.0
self.uiTextView.layer.borderWidth = 0.5
self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor
I guess you are using Rails 4. If so, the needed parameters must be marked as required.
You might want to do it like this:
class UsersController < ApplicationController
def create
@user = User.new(user_params)
# ...
end
private
def user_params
params.require(:user).permit(:username, :email, :password, :salt, :encrypted_password)
end
end
Use .toInt()
for int .toFloat()
for float and .toDouble()
for double
The quick answer: switch off AutoSize.
The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.
Basically what you need to do in OnPaint is:
You will also need to set the ResizeRedraw style flag in the constructor.
Python has nothing built-in to support this. Do you really need to optimize it so much as I don't think that appending will add that much overhead.
However, you can do something like l = [None] * 1000
.
Alternatively, you could use a generator.
for those that just want to get rid of the default selected grey background put this line of code in your cellForRowAtIndexPath func:
yourCell.selectionStyle = .None
demo change type of field mid from string to mongo objectId using mongoose
Post.find({}, {mid: 1,_id:1}).exec(function (err, doc) {
doc.map((item, key) => {
Post.findByIdAndUpdate({_id:item._id},{$set:{mid: mongoose.Types.ObjectId(item.mid)}}).exec((err,res)=>{
if(err) throw err;
reply(res);
});
});
});
Mongo ObjectId is just another example of such styles as
Number, string, boolean that hope the answer will help someone else.
If the goal is to delete the objects a
and b
themselves (which appears to be the case), forming the list [a, b]
is not helpful. Instead, one should keep a list of strings used as the names of those objects. These allow one to delete the objects in a loop, by accessing the globals()
dictionary.
c = ['a', 'b']
# create and work with a and b
for i in c:
del globals()[i]
Add:
allow_url_fopen=1
in your php.ini
file. If you are using shared hosting, create one first.
Starting OracleServiceHari where 'HARI' is the SID, worked for me.
Others facing same problem may check status of the service.
This is something you really need to do server-side as each user's local time format differs, not to mention each browser behaves different.
Html Date inputs value should be in this format: yyyy-mm-dd otherwise it will not show a value.
ASP CLASSIC , OR VBSCRIPT:
current_year = DatePart("yyyy",date)
current_month = DatePart("m",date)
current_day = DatePart("d",date)
IF current_month < 10 THEN
current_month = "0"¤t_month
END IF
IF current_day < 10 THEN
current_day = "0"¤t_day
END IF
get_date = current_year&"-"¤t_month&"-"¤t_day
Response.Write get_date
Output of today's date : 2019-02-08
Then in your html:
<input type="date" value="<% =get_date %>"
PHP
just use this:
<input type="date" value="<?= date("Y-m-d"); ?>">
For me it was occurring in a .net project and turned out to be something to do with my Visual Studio installation. I downloaded and installed the latest .net core sdk separately and then reinstalled VS and it worked.
This website contains a much cleaner solution, it leaves pip intact as-well and one can easily switch between 3.5 and 3.6 and then whenever 3.7 is released.
http://ubuntuhandbook.org/index.php/2017/07/install-python-3-6-1-in-ubuntu-16-04-lts/
A short summary:
sudo apt-get install python python-pip python3 python3-pip
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.5 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 2
Then
$ pip -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)
Then to select python 3.6 run
sudo update-alternatives --config python3
and select '2'. Then
$ pip3 -V
pip 8.1.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
To update pip select the desired version and
pip3 install --upgrade pip
$ pip3 -V
pip 9.0.1 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Tested on Ubuntu 16.04.
See here - http://my.opera.com/community/forums/topic.dml?id=1319992&t=1331393279&page=1#comment11751402
Essentially:
history.pushState('data', '', 'http://your-domain/path');
You can manipulate the history object to make this work.
It only works on the same domain, but since you're satisfied with using the hash tag approach, that shouldn't matter.
Obviously would need to be cross-browser tested, but since that was posted on the Opera forum I'm safe to assume it would work in Opera, and I just tested it in Chrome and it worked fine.
I was facing this issue on a react-native project and it came after adding a splash screen activity and making it the launcher activity.
This is the change i made in my android manifest XML file on the MainActivity configuration.
<activity_x000D_
android:name=".MainActivity"_x000D_
android:label="@string/app_name"_x000D_
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
android:windowSoftInputMode="adjustResize"/>_x000D_
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
_x000D_
I added the android:exported=true
and the activity configuration looked like this.
<activity_x000D_
android:name=".MainActivity"_x000D_
android:exported="true"_x000D_
android:label="@string/app_name"_x000D_
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
android:windowSoftInputMode="adjustResize"/>_x000D_
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />_x000D_
_x000D_
The builtin command for properly indenting the code has already been mentioned (gg=G
). If you want to beautify the code, you'll need to use an external application like indent. Since %
denotes the current file in ex mode, you can use it like this:
:!indent %
Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:
Use two tables:
Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID
Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title
This has some major advantages:
First it makes development much simpler: in the three-table solution for insert and update of item
you have to lookup the Tag
table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.
Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags
for one Item
, draw a Tag-Cloud and select all items for one Tag Title.
All Tags for one Item:
3-Table:
SELECT Tag.Title
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
WHERE ItemTag.ItemID = :id
2-Table:
SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id
Tag-Cloud:
3-Table:
SELECT Tag.Title, count(*)
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
GROUP BY Tag.Title
2-Table:
SELECT Tag.Title, count(*)
FROM Tag
GROUP BY Tag.Title
Items for one Tag:
3-Table:
SELECT Item.*
FROM Item
JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
JOIN Tag ON ItemTag.TagID = Tag.TagID
WHERE Tag.Title = :title
2-Table:
SELECT Item.*
FROM Item
JOIN Tag ON Item.ItemID = Tag.ItemID
WHERE Tag.Title = :title
But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.
The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.
The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.
So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)
mysql GROUP_CONCAT
function could help https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat
SELECT ProductID, GROUP_CONCAT(DISTINCT ProductName) as Names, SUM(OrderQuantity)
FROM OrderDetails GROUP BY ProductID
This would return:
ProductID Names OrderQuantity
1001 red 5
1002 red,black 6
1003 orange 8
1004 black,orange 15
Similar idea as the one @Urs Marian here posted https://stackoverflow.com/a/38779277/906265
private void ClearBtn_Click(object sender, EventArgs e)
{
Studentpicture.Image = null;
}
UPDATE: 2017-12-16:
There are 2 simple ways to do this in Spring Boot 1.5.8.RELEASE, no need for XML.
First way: If you do not have any spacific URL pattern, you can use @Component like this: (Full code and details are here https://www.surasint.com/spring-boot-filter/)
@Component
public class ExampleFilter implements Filter{
...
}
Second way: If you want to use url patterns, you can use @WebFilter like this: (Full code and details are here https://www.surasint.com/spring-boot-filter-urlpattern/)
@WebFilter(urlPatterns = "/api/count")
public class ExampleFilter implements Filter{
...
}
But you also need to add @ServletComponentScan annotation in your @SpringBootApplication class:
@ServletComponentScan
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
...
}
Note that @Component is Spring's annotation, but @WebFilter is not. @WebFilter is Servlet 3 annotation.
Both ways, you just need basic Spring Boot dependency in pom.xml (no need for explicit tomcat embedded jasper)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<groupId>com.surasint.example</groupId>
<artifactId>spring-boot-04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
WARNING: The first way, if the Controller in Spring Boot returns to a JSP file, the request will pass the filter twice.
While, in the second way, the request will pass the filter only once.
I prefer the second way because it is more similar to default behavior in Servlet specification (https://docs.oracle.com/cd/E19879-01/819-3669/6n5sg7b0b/index.html)
You can see more test log here https://www.surasint.com/spring-boot-webfilter-instead-of-component/
I use scoop as command-liner installer for Windows... scoop rocks!
The quick answer (use PowerShell):
PS C:\Users\myuser> scoop install ruby
Longer answer:
Just searching for ruby:
PS C:\Users\myuser> scoop search ruby
'main' bucket:
jruby (9.2.7.0)
ruby (2.6.3-1)
'versions' bucket:
ruby19 (1.9.3-p551)
ruby24 (2.4.6-1)
ruby25 (2.5.5-1)
Check the installation info :
PS C:\Users\myuser> scoop info ruby
Name: ruby
Version: 2.6.3-1
Website: https://rubyinstaller.org
Manifest:
C:\Users\myuser\scoop\buckets\main\bucket\ruby.json
Installed: No
Environment: (simulated)
GEM_HOME=C:\Users\myuser\scoop\apps\ruby\current\gems
GEM_PATH=C:\Users\myuser\scoop\apps\ruby\current\gems
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\bin
PATH=%PATH%;C:\Users\myuser\scoop\apps\ruby\current\gems\bin
Output from installation:
PS C:\Users\myuser> scoop install ruby
Updating Scoop...
Updating 'extras' bucket...
Installing 'ruby' (2.6.3-1) [64bit]
rubyinstaller-2.6.3-1-x64.7z (10.3 MB) [============================= ... ===========] 100%
Checking hash of rubyinstaller-2.6.3-1-x64.7z ... ok.
Extracting rubyinstaller-2.6.3-1-x64.7z ... done.
Linking ~\scoop\apps\ruby\current => ~\scoop\apps\ruby\2.6.3-1
Persisting gems
Running post-install script...
Fetching rake-12.3.3.gem
Successfully installed rake-12.3.3
Parsing documentation for rake-12.3.3
Installing ri documentation for rake-12.3.3
Done installing documentation for rake after 1 seconds
1 gem installed
'ruby' (2.6.3-1) was installed successfully!
Notes
-----
Install MSYS2 via 'scoop install msys2' and then run 'ridk install' to install the toolchain!
'ruby' suggests installing 'msys2'.
PS C:\Users\myuser>
You can make use of java.util.Date instead of Timestamp :
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
Check this out http://www.techumber.com/2015/04/html-to-pdf-conversion-using-javascript.html
Basically you need to use html2canvas and jspdf to make it work. First you will convert your dom to image and then you will use jspdf to create pdf with the images.
EDIT: A short note on how it work. We will use two libraries to make this job done. http://html2canvas.hertzen.com/ and https://github.com/MrRio/jsPDF First we will create a dom image by using html2canvas them we will use jspdf addImage method to add that image to pdf. It seems simple but there are few bugs in jsPdf and html2cavas so you may need to change dom style temporarily. Hope this helps.
(First, I'd like to recommend this useful reference site for batch: http://ss64.com/nt/)
Then just another useful explanation: http://htipe.wordpress.com/2008/10/09/the-dp0-variable/
The %~dp0 Variable
The
%~dp0
(that’s a zero) variable when referenced within a Windows batch file will expand to the drive letter and path of that batch file.The variables
%0-%9
refer to the command line parameters of the batch file.%1-%9
refer to command line arguments after the batch file name.%0
refers to the batch file itself.If you follow the percent character (
%
) with a tilde character (~
), you can insert a modifier(s) before the parameter number to alter the way the variable is expanded. Thed
modifier expands to the drive letter and thep
modifier expands to the path of the parameter.Example: Let’s say you have a directory on
C:
calledbat_files
, and in that directory is a file calledexample.bat
. In this case,%~dp0
(combining thed
andp
modifiers) will expand toC:\bat_files\
.Check out this Microsoft article for a full explanation.
Also, check out this forum thread.
And a more clear reference from here:
%CmdCmdLine%
will return the entire command line as passed to CMD.EXE
%*
will return the remainder of the command line starting at the first command line argument (in Windows NT 4, %* also includes all leading spaces)
%~dn
will return the drive letter of %n (n can range from 0 to 9) if %n is a valid path or file name (no UNC)
%~pn
will return the directory of %n if %n is a valid path or file name (no UNC)
%~nn
will return the file name only of %n if %n is a valid file name
%~xn
will return the file extension only of %n if %n is a valid file name
%~fn
will return the fully qualified path of %n if %n is a valid file name or directory
Just found some good reference for the mysterious ~
tilde operator.
The %~
string is called percent tilde operator. You can find it in situations like: %~0
.
The :~
string is called colon tilde operator. You can find it like %SOME_VAR:~0,-1%
.
%1-%9
refer to the command line args. If they are not valid path values, %~dp1
- %~dp9
will all expand to the same value as %~dp0
. But if they are valid path values, they will expand to their own driver/path value.
For example: (batch.bat)
@echo off
@echo ~dp0= %~dp0
@echo ~dp1= %~dp1
@echo ~dp2= %~dp2
@echo on
Run 1:
D:\Workbench>batch arg1 arg2
~dp0= D:\Workbench\
~dp1= D:\Workbench\
~dp2= D:\Workbench\
Run 2:
D:\Workbench>batch c:\123\a.exe e:\abc\b.exe
~dp0= D:\Workbench\
~dp1= c:\123\
~dp2= e:\abc\
Have a look at using FileInfo.Name Property
something like
string[] files = Directory.GetFiles(dir);
for (int iFile = 0; iFile < files.Length; iFile++)
string fn = new FileInfo(files[iFile]).Name;
Also have a look at using DirectoryInfo Class and FileInfo Class
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
By searching all python-distutils related package:
apt-cache search x
I get python3-distutils-extra - enhancements to the Python3 build system
Then just try:
sudo apt-get install python3-distutils-extra
You can get the introduction of the article in Wikipedia by querying pages such as https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=java. You just need to parse the json file and the result is plain text which has been cleaned including removing links and references.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
With all due respect to our unknown (yahoo) poster, I look at code like that and just die a little inside. Alphabet soup is just so insanely difficult to debug. A single typo anywhere in there can really ruin your whole day. Sadly, this particular example lacked variables with underscores. It's so much more fun when we have a_b-c_d*e_f-g_h. Especially when using a font where _ and - have the same pixel length.
Taking up Suvesh Pratapa on his suggestion, I note:
Given 3x3 matrix:
y0x0 y0x1 y0x2
y1x0 y1x1 y1x2
y2x0 y2x1 y2x2
Declared as double matrix [/*Y=*/3] [/*X=*/3];
(A) When taking a minor of a 3x3 array, we have 4 values of interest. The lower X/Y index is always 0 or 1. The higher X/Y index is always 1 or 2. Always! Therefore:
double determinantOfMinor( int theRowHeightY,
int theColumnWidthX,
const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
int x1 = theColumnWidthX == 0 ? 1 : 0; /* always either 0 or 1 */
int x2 = theColumnWidthX == 2 ? 1 : 2; /* always either 1 or 2 */
int y1 = theRowHeightY == 0 ? 1 : 0; /* always either 0 or 1 */
int y2 = theRowHeightY == 2 ? 1 : 2; /* always either 1 or 2 */
return ( theMatrix [y1] [x1] * theMatrix [y2] [x2] )
- ( theMatrix [y1] [x2] * theMatrix [y2] [x1] );
}
(B) Determinant is now: (Note the minus sign!)
double determinant( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
return ( theMatrix [0] [0] * determinantOfMinor( 0, 0, theMatrix ) )
- ( theMatrix [0] [1] * determinantOfMinor( 0, 1, theMatrix ) )
+ ( theMatrix [0] [2] * determinantOfMinor( 0, 2, theMatrix ) );
}
(C) And the inverse is now:
bool inverse( const double theMatrix [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
double det = determinant( theMatrix );
/* Arbitrary for now. This should be something nicer... */
if ( ABS(det) < 1e-2 )
{
memset( theOutput, 0, sizeof theOutput );
return false;
}
double oneOverDeterminant = 1.0 / det;
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
/* Rule is inverse = 1/det * minor of the TRANSPOSE matrix. *
* Note (y,x) becomes (x,y) INTENTIONALLY here! */
theOutput [y] [x]
= determinantOfMinor( x, y, theMatrix ) * oneOverDeterminant;
/* (y0,x1) (y1,x0) (y1,x2) and (y2,x1) all need to be negated. */
if( 1 == ((x + y) % 2) )
theOutput [y] [x] = - theOutput [y] [x];
}
return true;
}
And round it out with a little lower-quality testing code:
void printMatrix( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
{
cout << "[ ";
for ( int x = 0; x < 3; x ++ )
cout << theMatrix [y] [x] << " ";
cout << "]" << endl;
}
cout << endl;
}
void matrixMultiply( const double theMatrixA [/*Y=*/3] [/*X=*/3],
const double theMatrixB [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
theOutput [y] [x] = 0;
for ( int i = 0; i < 3; i ++ )
theOutput [y] [x] += theMatrixA [y] [i] * theMatrixB [i] [x];
}
}
int
main(int argc, char **argv)
{
if ( argc > 1 )
SRANDOM( atoi( argv[1] ) );
double m[3][3] = { { RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) } };
double o[3][3], mm[3][3];
if ( argc <= 2 )
cout << fixed << setprecision(3);
printMatrix(m);
cout << endl << endl;
SHOW( determinant(m) );
cout << endl << endl;
BOUT( inverse(m, o) );
printMatrix(m);
printMatrix(o);
cout << endl << endl;
matrixMultiply (m, o, mm );
printMatrix(m);
printMatrix(o);
printMatrix(mm);
cout << endl << endl;
}
You may also want to detect very large determinants as round-off errors will affect your accuracy!
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
You can do this with array_keys and count.
$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));
Output:
3
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
<div class="col-md-12">
<p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
<button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
Ver Pedido
</button>
</p>
</div>
A scriptless, CSS-only experimental approach with image pre-loadingBONUS! and which only works in Firefox:
<style>
a.zoom .full { display: none; }
a.zoom:active .thumb { display: none; }
a.zoom:active .full { display: inline; }
</style>
<a class="zoom" href="#">
<img class="thumb" src="thumbnail.png"/>
<img class="full" src="fullsize.png"/>
</a>
Shows the thumbnail by default. Shows the full size image while the mouse button is clicked and held down. Goes back to the thumbnail as soon as the button is released. I'm in no way suggesting that this method be used; it's just a demo of a CSS-only approach that [very] partially solves the problem. With some z-index + relative position tweaks, it could work in other browsers too.
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
def filter_out_colors(elements):
colors = ['red', 'green']
result = []
for element in elements:
if element in colors:
continue # skip the element
# You can do whatever here
result.append(element)
return result
>>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
['lemon', 'orange', 'pear']
You can use radius but it will not work on IE: border-radius: 5px 5px;
.
Another alternative is to use capturing sub-expressions with the regular expression functions regmatches
and regexec
.
# the original example
x <- 'hello stackoverflow'
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))
This returns the entire string, the first character, and the "popped" result in a list of length 1.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x))))
. That is, it contains the super set of the desired elements as well as the full string.
Adding sapply
will allow this method to work for a character vector of length > 1.
# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))
This returns a list with the matched full string as the first element and the matching subexpressions captured by ()
as the following elements. So in the regular expression '(^.)(.*)'
, (^.)
matches the first character and (.*)
matches the remaining characters.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
[[2]]
[1] "right back" "r" "ight back"
[[3]]
[1] "at yah" "a" "t yah"
Now, we can use the trusty sapply
+ [
method to pull out the desired substrings.
myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back" "t yah"
SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995
For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.
I replaced the studio64.exe.vmoptions with the following code.
# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html
-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=
-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio
MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.
So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!
Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:
You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW())
.
You do INSERT INTO table (dateCreated) VALUES (?)
, and specify the current time from your application code.
CASE #1
MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.
So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.
CASE #2
It depends on what type of value you pass as ?
. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.
The most efficient way to do this (believe it or not) is to make two variables and write a for
loop.
Remove the data attribute as you are not POSTING
anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor
and use @Url.Action
rather than a static string:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
Not sure what you table structure is like but see below.
public NamePriceModel[] AllProducts()
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts
.Where(x => x.Status == 1)
.Select(x => new NamePriceModel {
Name = x.Name,
Id = x.Id,
Price = x.Price
})
.OrderBy(x => x.Id)
.ToArray();
}
}
catch
{
return null;
}
}
This would return an array of type anonymous with the members you require.
Update:
Create a new class.
public class NamePriceModel
{
public string Name {get; set;}
public decimal? Price {get; set;}
public int Id {get; set;}
}
I've modified the query above to return this as well and you should change your method from returning string[]
to returning NamePriceModel[]
.
i = 20
"%x" % i #=> "14"
Try this function, it's similar to your code but it's a dynamic range.
def unique(a):
k=0
while k < len(a):
if a[k] in a[k+1:]:
a.pop(k)
else:
k=k+1
return a
You can add a style.css
, import this file after the bootstrap.css
to override this code.
For example:
/* bootstrap.css */
* {
font-size: 14px;
line-height: 1.428;
}
/* style.css */
* {
font-size: 16px;
line-height: 2;
}
Don't change bootstrap.css
directly for better maintenance of code.
You should set async = false in head. Use post/get instead of ajax.
jQuery.ajaxSetup({ async: false });
$.post({
url: 'api.php',
data: 'id1=' + q + '',
dataType: 'json',
success: function (data) {
id = data[0];
vname = data[1];
}
});
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
Try adding use PDO;
after your namespace or just before your class or at the top of your PHP
file.
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
You can use each
for objects too and not just for arrays:
var obj = {
foo: "bar",
baz: "quux"
};
jQuery.each(obj, function(name, value) {
alert(name + ": " + value);
});
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
You can simply write:
val mutableList = mutableListOf<Kolory>()
This is the most idiomatic way.
Alternative ways are
val mutableList : MutableList<Kolory> = arrayListOf()
or
val mutableList : MutableList<Kolory> = ArrayList()
This is exploiting the fact that java types like ArrayList
are implicitly implementing the type MutableList
via a compiler trick.
I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e
li { display: list-item;}
With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.
You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.
If the variable inside the double quote PHP take time to parse variable.
Check out this Single quotes or double quotes for variable concatenation?
This is another example Is there a performance benefit single quote vs double quote in php?
I did not understand why this answer in above link get upvoted and why this answer got downvote.
As I said same thing.
You can look at here as well
The strict equivalent of the java int
is long int
in C.
Edit:
If int32_t
is defined, then it is the equivalent in terms of precision. long int
guarantee the precision of the java int
, because it is guarantee to be at least 32 bits in size.
Webdriver doesn't contain an API to do it. See issue 141 from Selenium tracker for more info. The title of the issue says that it's about response headers but it was decided that Selenium won't contain API for request headers in scope of this issue. Several issues about adding API to set request headers have been marked as duplicates: first, second, third.
Here are a couple of possibilities that I can propose:
I'd go with option 3 in most of cases. It's not hard.
Note that Ghostdriver has an API for it but it's not supported by other drivers.
jQuery $.extend(obj1, obj2)
would merge 2 objects for you, but you should really be using an array.
var alertsObj = {
1: {app:'helloworld','message'},
2: {app:'helloagain',message:'another message'}
};
var alertArr = [
{app:'helloworld','message'},
{app:'helloagain',message:'another message'}
];
var newAlert = {app:'new',message:'message'};
$.extend(alertsObj, newAlert);
alertArr.push(newAlert);
We have a no code past the 80th character column that is controversial in our C++ development team. Liked and code review enforced by some; Despised by others.
Also, we have a very controversial C++ throw(), throw(...) specification standard. Religiously used by some and demonized by others. Both camps cite discussions and experts to enforce their respective positions.
Explanation internal working on this error
You are getting this error because after instantiation the container is trying to assign same object to both classes as class name is same irrespective of different packages......thats why error says non compatible bean definition of same name ..
Actually how it works internally is--->>>>.
pkg test1; …. @RestController class Test{}
pkg test2; …. @RestController class Test{}
First container will get class Test and @RestController indicates it to instantiate as…test = new Test(); and it won’t instantiate twice After instantiating container will provide a reference variable test(same as class name) to both the classes and while it provide test reference To second class it gets non compatible bean definition of same name ……
Solution—>>>>
Assign a refrence name to both rest controller so that container won’t instantiate with default name and instantiate saperately for both classes irrespective Of same name
For example——>>>
pkg test1; …. @RestController(“test1”) class Test{}
pkg test2; …. @RestController(“test2”) class Test{}
Note:The same will work with @Controller,@Service,@Repository etc..
Note: if you are creating reference variable at class level then you can also annotate it with @Qualifier("specific refrence name") for example @Autowired @Qualifier("test1") Test test;
Go with this
body {
padding:0px;
margin:0px;
}
I'm pretty certain that ports only have a part in tcp and udp. So it's exactly the same even if you use a new IP protocol
If you have an array of keys that you want to use then use array_combine
Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:
$list = array_combine($keys, array_values($list));
List will now be array('a' => 'blabla 1', ...) etc.
You have to use array_values
to extract just the values from the array and not the old, numeric, keys.
That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:
foreach ($list as $k => $v) {
unset ($list[$k]);
$new_key = *some logic here*
$list[$new_key] = $v;
}
I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.
I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!
-Sam
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
By this you can get any index in *ngFor
loop in ANGULAR ...
<ul>
<li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
<div *ngIf="first">
// write your code...
</div>
<div *ngIf="last">
// write your code...
</div>
</li>
</ul>
We can use these alias in *ngFor
index
: number
: let i = index
to get all index of object.first
: boolean
: let first = first
to get first index of object.last
: boolean
: let last = last
to get last index of object.odd
: boolean
: let odd = odd
to get odd index of object.even
: boolean
: let even = even
to get even index of object.PHP has a built-in function file_get_contents(), which reads the content of a file into a string.
<?php
//Get the file
$content = file_get_contents("http://example.com/image.jpg");
//Store in the filesystem. $fp = fopen("/location/to/save/image.jpg", "w"); fwrite($fp, $content); fclose($fp); ?> If you wish to store the file in a database, simply use the $content variable and don't save the file to disk.
Try this query
select
*,
Days = datediff(dd,0,DateDif),
Hours = datepart(hour,DateDif),
Minutes = datepart(minute,DateDif),
Seconds = datepart(second,DateDif),
MS = datepart(ms,DateDif)
from
(select
DateDif = EndDate-StartDate,
aa.*
from
( -- Test Data
Select
StartDate = convert(datetime,'20090213 02:44:37.923'),
EndDate = convert(datetime,'20090715 13:24:45.837')) aa
) a
Output
DateDif StartDate EndDate Days Hours Minutes Seconds MS
----------------------- ----------------------- ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913 2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 152 10 40 7 913
(1 row(s) affected)
There is a plugin to check if an element is focused: http://plugins.jquery.com/project/focused
$('input').each(function(){
if ($(this) == $.focused()) {
$(this).addClass('focused');
}
})
Because Xcode subsumes the CLI tools if installed first, I use the following hybrid which has been validated on 10.12 and 10.14. I expect it works on a lot of other versions:
installed=$(pkgutil --pkg-info=com.apple.pkg.CLTools_Executables 2>/dev/null || pkgutil --pkg-info=com.apple.pkg.Xcode)
Salt with awk
to taste for branching logic.
Of course xcode-select -p
handles the variations with a really short command but fails to give the detailed package, version, and installation date metadata.
Rather than dragging Boost into the equation, you could keep your string (temporarily) as a char[]
and use sprintf()
.
But of course if you're using Boost anyway, it's really not too much of an issue.
<html>
<head>
<script type="text/javascript">
function test(){
var map= {'m1': 12,'m2': 13,'m3': 14,'m4': 15}
alert(map['m3']);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="test()"/>
</body>
</html>
You can do this using jQuery's .scrollTop()
and .offset()
method
Check out my sample and this jsFiddle Demonstration
$(function() {
$(document).scrollTop( $("#header").offset().top );
});
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
There needs to be some type of backend framework to send the email. This can be done via PHP/ASP.NET, or with the local mail client. If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.
Here is what worked for me:
<input type="submit" style="margin-left: 50%">
If you only add margin, without the left part, it will center the submit button into the middle of your entire page, making it difficult to find and rendering your form incomplete for people who don't have the patience to find a submit button lol. margin-left centers it within the same line, so it's not further down your page than you intended. You can also use pixels instead of percentage if you just want to indent the submit button a bit and not all the way halfway across the page.