There are two ways to delete a stash:
$ git stash drop <stash_id>
. $ git stash clear
.Use both of them with caution, it maybe is difficult to revert the once deleted stashes.
Here is the reference article.
possibly not so many answers so thinking to share my code which can help someone
from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date
spark = SparkSession.builder.appName("Python Spark SQL basic example")\
.config("spark.some.config.option", "some-value").getOrCreate()
df = spark.createDataFrame([('2019-06-22',)], ['t'])
df1 = df.select(to_date(df.t, 'yyyy-MM-dd').alias('dt'))
print df1
print df1.show()
output
DataFrame[dt: date]
+----------+
| dt|
+----------+
|2019-06-22|
+----------+
the above code to convert to date if you want to convert datetime then use to_timestamp. let me know if you have any doubt.
This expression should do what you want to achieve.
dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))
I have a Linux Lite 3.8 (It bases on Ubuntu 16.04 LTS) and a path change in the following file (with root privileges) with restart has helped.
/etc/profile.d/jdk.sh
On Ubuntu systems, use the following locations:
System-wide persistent variables in the format of JAVA_PATH=/usr/local/java
store in
/etc/environment
System-wide persistent variables that reference variables such as
export PATH="$JAVA_PATH:$PATH"
store in
/etc/.bashrc
User specific persistent variables in the format of PATH DEFAULT=/usr/bin:usr/local/bin
store in
~/.pam_environment
For more details on #2, check this Ask Ubuntu answer. NOTE: #3 is the Ubuntu recommendation but may have security concerns in the real world.
I would suggest concat when dealing with 2 strings, and || when those strings are more than 2:
select concat(a,b)
from dual
or
select 'a'||'b'||'c'||'d'
from dual
For those trying to make the connection between SNR and a normal random variable generated by numpy:
[1] , where it's important to keep in mind that P is average power.
Or in dB:
[2]
In this case, we already have a signal and we want to generate noise to give us a desired SNR.
While noise can come in different flavors depending on what you are modeling, a good start (especially for this radio telescope example) is Additive White Gaussian Noise (AWGN). As stated in the previous answers, to model AWGN you need to add a zero-mean gaussian random variable to your original signal. The variance of that random variable will affect the average noise power.
For a Gaussian random variable X, the average power , also known as the second moment, is
[3]
So for white noise, and the average power is then equal to the variance .
When modeling this in python, you can either
1. Calculate variance based on a desired SNR and a set of existing measurements, which would work if you expect your measurements to have fairly consistent amplitude values.
2. Alternatively, you could set noise power to a known level to match something like receiver noise. Receiver noise could be measured by pointing the telescope into free space and calculating average power.
Either way, it's important to make sure that you add noise to your signal and take averages in the linear space and not in dB units.
Here's some code to generate a signal and plot voltage, power in Watts, and power in dB:
# Signal Generation
# matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(1, 100, 1000)
x_volts = 10*np.sin(t/(2*np.pi))
plt.subplot(3,1,1)
plt.plot(t, x_volts)
plt.title('Signal')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
x_watts = x_volts ** 2
plt.subplot(3,1,2)
plt.plot(t, x_watts)
plt.title('Signal Power')
plt.ylabel('Power (W)')
plt.xlabel('Time (s)')
plt.show()
x_db = 10 * np.log10(x_watts)
plt.subplot(3,1,3)
plt.plot(t, x_db)
plt.title('Signal Power in dB')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
Here's an example for adding AWGN based on a desired SNR:
# Adding noise using target SNR
# Set a target SNR
target_snr_db = 20
# Calculate signal power and convert to dB
sig_avg_watts = np.mean(x_watts)
sig_avg_db = 10 * np.log10(sig_avg_watts)
# Calculate noise according to [2] then convert to watts
noise_avg_db = sig_avg_db - target_snr_db
noise_avg_watts = 10 ** (noise_avg_db / 10)
# Generate an sample of white noise
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(noise_avg_watts), len(x_watts))
# Noise up the original signal
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise (dB)')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
And here's an example for adding AWGN based on a known noise power:
# Adding noise using a target noise power
# Set a target channel noise power to something very noisy
target_noise_db = 10
# Convert to linear Watt units
target_noise_watts = 10 ** (target_noise_db / 10)
# Generate noise samples
mean_noise = 0
noise_volts = np.random.normal(mean_noise, np.sqrt(target_noise_watts), len(x_watts))
# Noise up the original signal (again) and plot
y_volts = x_volts + noise_volts
# Plot signal with noise
plt.subplot(2,1,1)
plt.plot(t, y_volts)
plt.title('Signal with noise')
plt.ylabel('Voltage (V)')
plt.xlabel('Time (s)')
plt.show()
# Plot in dB
y_watts = y_volts ** 2
y_db = 10 * np.log10(y_watts)
plt.subplot(2,1,2)
plt.plot(t, 10* np.log10(y_volts**2))
plt.title('Signal with noise')
plt.ylabel('Power (dB)')
plt.xlabel('Time (s)')
plt.show()
This is only true if you're iterating through an array; what if you were iterating through a different kind of collection that has no notion of accessing by index? In the array case, the easiest way to retain the index is to simply use a vanilla for loop.
On Fedora 24: For Python 3.x
sudo dnf install postgresql-devel python3-devel
sudo dnf install redhat-rpm-config
Activate your Virtual Environment:
pip install psycopg2
Just remove the break. since it is already inside first if it will not execute else. It will exit anyway.
Here's an alternate solution, without using dblink
.
Suppose B represents the source database and A represents the target database: Then,
Copy table from source DB to target DB:
pg_dump -t <source_table> <source_db> | psql <target_db>
Open psql prompt, connect to target_db, and use a simple insert
:
psql
# \c <target_db>;
# INSERT INTO <target_table>(id, x, y) SELECT id, x, y FROM <source_table>;
At the end, delete the copy of source_table that you created in target_table.
# DROP TABLE <source_table>;
When using the 'mat-form-field' MatInputModule needs to be imported also
import {
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatListModule ,
MatStepperModule,
MatInputModule
} from '@angular/material';
Simplest solution:
Convert array to list and you can get position of an element.
List<String> abcd = Arrays.asList(yourArray);
int i = abcd.indexOf("abcd");
Other solution, you can iterator array:
int position = 0;
for (String obj : yourArray) {
if (obj.equals("abcd") {
return position;
}
position += 1;
}
//OR
for (int i = 0; i < yourArray.length; i++) {
if (obj.equals("abcd") {
return i;
}
}
You must analyse the actual HTML output, for the hint.
By giving the path like this means "from current location", on the other hand if you start with a /
that would mean "from the context".
I use Laravel quite a bit and I simply do not believe the numbers it tells me because end-to-end rendering as measured by my browser shows LOWER total time from request to ready.
Further, I get slightly higher numbers on my machine at work, which does execute the page noticeably faster than my machine at home.
I don't know how those numbers are getting calculated, but they are not corroborated by observation, or browser tools like Firebug...
Laravel is not actually all that slow, especially when optimized. It is memory-hungry however. Even a heavy CMS like Drupal which is very slow, appears to have about 1/3rd the memory footprint of a bare bones Laravel request.
Thus to run Laravel in production, I would deploy to memory-optimized servers before CPU-optimized servers.
Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up to 100 iOS devices.
It currently only works for the built in system frameworks. If you use #import
like apple still do importing the UIKit
framework in the app delegate it is replaced (if modules is on and its recognised as a system framework) and the compiler will remap it to be a module import and not an import of the header files anyway.
So leaving the #import
will be just the same as its converted to a module import where possible anyway
List<string> includedWords = new List<string>() { "a", "b", "c" };
bool string_contains_words = includedWords.Exists(o => s.Contains(o));
the free way would be to use dotfuscator from within visual studio, otherwise youd have to go out and buy an obfuscator like Postbuild (http://www.xenocode.com/Landing/Obfuscation.aspx)
Easiest solution:
app.disable('etag');
Alternate solution here if you want more control:
You can use names
directly in the read_csv
names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None
Cov = pd.read_csv("path/to/file.txt",
sep='\t',
names=["Sequence", "Start", "End", "Coverage"])
char *str = (char*) malloc(50 * sizeof(char));
strcpy(str, " some random string (<50 chars) ");
while(*str == ' ' || *str == '\t' || *str == '\n')
str++;
int len = strlen(str);
while(len >= 0 &&
(str[len - 1] == ' ' || str[len - 1] == '\t' || *str == '\n')
{
*(str + len - 1) = '\0';
len--;
}
printf(":%s:\n", str);
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
A method taking a delegate can provide multiple values to the caller. This borrows from my answer here and uses a little bit from Hadas's accepted answer.
delegate void ValuesDelegate(int upVotes, int comments);
void GetMultipleValues(ValuesDelegate callback)
{
callback(1, 2);
}
Callers provide a lambda (or a named function) and intellisense helps by copying the variable names from the delegate.
GetMultipleValues((upVotes, comments) =>
{
Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
});
Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):
public static bool SendAnSMSMessage(string message)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
var serializer = new Newtonsoft.Json.JsonSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
serializer.Serialize(tw,
new {method= "send",
@params = new string[]{
"IPutAGuidHere",
"[email protected]",
"MyTenDigitNumberWasHere",
message
}});
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
return true;
}
}
Maven Micro-Tip: Get sources and Javadocs
When you're using Maven in an IDE you often find the need for your IDE to resolve source code and Javadocs for your library dependencies. There's an easy way to accomplish that goal.
mvn dependency:sources mvn dependency:resolve -Dclassifier=javadoc
The first command will attempt to download source code for each of the dependencies in your pom file.
The second command will attempt to download the Javadocs.
Maven is at the mercy of the library packagers here. So some of them won't have source code packaged and many of them won't have Javadocs.
In case you have a lot of dependencies it might also be a good idea to use inclusions/exclusions to get specific artifacts, the following command will for example only download the sources for the dependency with a specific artifactId:
mvn dependency:sources -DincludeArtifactIds=guava
Source: http://tedwise.com/2010/01/27/maven-micro-tip-get-sources-and-javadocs/
Documentation: https://maven.apache.org/plugins/maven-dependency-plugin/sources-mojo.html
First, you have to run below codes in Anaconda prompt
,
conda create -n py27 python=2.7 #for version 2.7
activate py27
conda create -n py36 python=3.6 #for version 3.6
activate py36
Then, you have to open Anaconda navigator
and,
The button might say "install" instead of Launch. After the installation, which takes a few moments, It will be ready to launch.
Thank you, @cloudscomputes and @Francisco Camargo.
Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach
List<String> strings = new ArrayList<String>();
because it's hide the implementation detail from user. You precisely
List<String> strings = new ArrayList<String>();
it's generic approach and this specialized approach
ArrayList<String> strings = new ArrayList<String>();
For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces
Here's a quick jQuery example that adds a click event to each "li" tag, and then retrieves the class attribute for the clicked element. Hope it helps.
$("li").click(function() {
var myClass = $(this).attr("class");
alert(myClass);
});
Equally, you don't have to wrap the object in jQuery:
$("li").click(function() {
var myClass = this.className;
alert(myClass);
});
And in newer browsers you can get the full list of class names:
$("li").click(function() {
var myClasses = this.classList;
alert(myClasses.length + " " + myClasses[0]);
});
You can emulate classList
in older browsers using myClass.split(/\s+/);
I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException
is thrown when the Scanner reaches the endOfFile
, where it is not going to affect our data.
Here, I've placed my code in try block
and catch block
handles the exception
. You can also leave it empty, if you don't want to perform any task.
For the above question, because you are using file.next()
both in the condition and in the while loop you can handle the exception as
while(!file.next().equals(treasure)){
try{
file.next(); //stack trace error here
}catch(NoSuchElementException e) { }
}
This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.
Here is a SUPER SIMPLE implementation/example of a FSM using just "if-else"s which avoids all of the above subclassing answers (taken from Using Finite State Machines for Pattern Matching in Java, where he is looking for a string which ends with "@" followed by numbers followed by "#"--see state graph here):
public static void main(String[] args) {
String s = "A1@312#";
String digits = "0123456789";
int state = 0;
for (int ind = 0; ind < s.length(); ind++) {
if (state == 0) {
if (s.charAt(ind) == '@')
state = 1;
} else {
boolean isNumber = digits.indexOf(s.charAt(ind)) != -1;
if (state == 1) {
if (isNumber)
state = 2;
else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 2) {
if (s.charAt(ind) == '#') {
state = 3;
} else if (isNumber) {
state = 2;
} else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 3) {
if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
}
}
} //end for loop
if (state == 3)
System.out.println("It matches");
else
System.out.println("It does not match");
}
P.S: Does not answer your question directly, but shows you how to implement a FSM very easily in Java.
If you have only one level and you use bootstrap 3 add pull-right
to the ul
element
<ul class="dropdown-menu pull-right" role="menu">
Here is a single class copy/paste solution:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;
public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {
private String hint;
private boolean hideOnFocus;
private Color color;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
repaint();
}
private void repaint() {
if(getComponent() != null) {
getComponent().repaint();
}
}
public boolean isHideOnFocus() {
return hideOnFocus;
}
public void setHideOnFocus(boolean hideOnFocus) {
this.hideOnFocus = hideOnFocus;
repaint();
}
public String getHint() {
return hint;
}
public void setHint(String hint) {
this.hint = hint;
repaint();
}
public HintTextFieldUI(String hint) {
this(hint,false);
}
public HintTextFieldUI(String hint, boolean hideOnFocus) {
this(hint,hideOnFocus, null);
}
public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
this.hint = hint;
this.hideOnFocus = hideOnFocus;
this.color = color;
}
@Override
protected void paintSafely(Graphics g) {
super.paintSafely(g);
JTextComponent comp = getComponent();
if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
if(color != null) {
g.setColor(color);
} else {
g.setColor(comp.getForeground().brighter().brighter().brighter());
}
int padding = (comp.getHeight() - comp.getFont().getSize())/2;
g.drawString(hint, 2, comp.getHeight()-padding-1);
}
}
@Override
public void focusGained(FocusEvent e) {
if(hideOnFocus) repaint();
}
@Override
public void focusLost(FocusEvent e) {
if(hideOnFocus) repaint();
}
@Override
protected void installListeners() {
super.installListeners();
getComponent().addFocusListener(this);
}
@Override
protected void uninstallListeners() {
super.uninstallListeners();
getComponent().removeFocusListener(this);
}
}
Use it like this:
TextField field = new JTextField();
field.setUI(new HintTextFieldUI("Search", true));
Note that it is happening in protected void paintSafely(Graphics g)
.
I changed the package name while coding an update so that I could debug it on my device via Eclipse, without deleting the old version that was installed. Without reverting the package name I was using when trying to reinstall, I got this same error. Using the same package name the reinstall was successful.
Summary: If you only want to create a few columns, use df[['new_col1','new_col2']] = df[['data1','data2']].apply( function_of_your_choosing(x), axis=1)
For this solution, the number of new columns you are creating must be equal to the number columns you use as input to the .apply() function. If you want to do something else, have a look at the other answers.
Details Let's say you have two-column dataframe. The first column is a person's height when they are 10; the second is said person's height when they are 20.
Suppose you need to calculate both the mean of each person's heights and sum of each person's heights. That's two values per each row.
You could do this via the following, soon-to-be-applied function:
def mean_and_sum(x):
"""
Calculates the mean and sum of two heights.
Parameters:
:x -- the values in the row this function is applied to. Could also work on a list or a tuple.
"""
sum=x[0]+x[1]
mean=sum/2
return [mean,sum]
You might use this function like so:
df[['height_at_age_10','height_at_age_20']].apply(mean_and_sum(x),axis=1)
(To be clear: this apply function takes in the values from each row in the subsetted dataframe and returns a list.)
However, if you do this:
df['Mean_&_Sum'] = df[['height_at_age_10','height_at_age_20']].apply(mean_and_sum(x),axis=1)
you'll create 1 new column that contains the [mean,sum] lists, which you'd presumably want to avoid, because that would require another Lambda/Apply.
Instead, you want to break out each value into its own column. To do this, you can create two columns at once:
df[['Mean','Sum']] = df[['height_at_age_10','height_at_age_20']]
.apply(mean_and_sum(x),axis=1)
Oh My Goodness! Look at the size of my temporary table space! Or... how to shrink temporary tablespaces in Oracle.
Yes I ran a query to see how big my temporary tablespace is:
SQL> SELECT tablespace_name, file_name, bytes
2 FROM dba_temp_files WHERE tablespace_name like 'TEMP%';
TABLESPACE_NAME FILE_NAME BYTES
----------------- -------------------------------- --------------
TEMP /the/full/path/to/temp01.dbf 13,917,200,000
The first question you have to ask is why the temporary tablespace is so large. You may know the answer to this off the top of your head. It may be due to a large query that you just run with a sort that was a mistake (I have done that more than once.) It may be due to some other exceptional circumstance. If that is the case then all you need to do to clean up is to shrink the temporary tablespace and move on in life.
But what if you don't know? Before you decide to shrink you may need to do some investigation into the causes of the large tablespace. If this happens on a regular basis then it is possible that your database just needs that much space.
The dynamic performance view
V$TEMPSEG_USAGE
can be very useful in determining the cause.
Maybe you just don't care about the cause and you just need to shrink it. This is your third day on the job. The data in the database is only 200MiB if data and the temporary tablespace is 13GiB - Just shrink it and move on. If it grows again then we will look into the cause. In the mean time I am out of space on that disk volume and I just need the space back.
Let's take a look at shrinking it. It will depend a little on what version
of Oracle you are running and how the temporary tablespace was set up.
Oracle will do it's best to keep you from making any horrendous mistakes
so we will just try the commands and if they don't work we will shrink
in a new way.
First let's try to shrink the datafile. If we can do that then we get back the space and we can worry about why it grew tomorrow.
SQL>
SQL> alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M;
alter database tempfile '/the/full/path/to/temp01.dbf' resize 256M
*
ERROR at line 1:
ORA-03297: file contains used data beyond requested RESIZE value
Depending on the error message you may want to try this with different sizes that are smaller than the current site of the file. I have had limited success with this. Oracle will only shrink the file if the temporary tablespace is at the head of the file and if it is smaller than the size you specify. Some old Oracle documentation (they corrected this) said that you could issue the command and the error message would tell you what size you could shrink to. By the time I started working as a DBA this was not true. You just had to guess and re-run the command a bunch of times and see if it worked.
Alright. That didn't work. How about this.
SQL> alter tablespace YOUR_TEMP_TABLESPACE_NAME shrink space keep 256M;
If you are in 11g (Maybee in 10g too) this is it! If it works you may want to go back to the previous command and give it some more tries.
But what if that fails. If the temporary tablespace is the default temporary that was set up when the database was installed then you may need to do a lot more work. At this point I usually re-evaluate if I really need that space back. After all disk space only costs $X.XX a GiB. Usually I don't want to make changes like this during production hours. That means working at 2AM AGAIN! (Not that I really object to working at 2AM - it is just that... Well I like to sleep too. And my wife likes to have me at home at 2AM... not roaming the downtown streets at 4AM trying to remember where I parked my car 3 hours earlier. I have heard of that "telecommuting" thing. I just worry that I will get half way through and then my internet connectivity will fail - then I have to rush downtown to fix it all before folks show up in the morning to use the database.)
Ok... Back to the serious stuff... If the temporary tablespace you want to shrink is your default temporary tablespace, you will have to first create a new temporary tablespace, set it as the default temporary tablespace then drop your old default temporary tablespace and recreate it. Afterwords drop the second temporary table created.
SQL> CREATE TEMPORARY TABLESPACE temp2
2 TEMPFILE '/the/full/path/to/temp2_01.dbf' SIZE 5M REUSE
3 AUTOEXTEND ON NEXT 1M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp2;
Database altered.
SQL> DROP TABLESPACE temp INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
SQL> CREATE TEMPORARY TABLESPACE temp
2 TEMPFILE '/the/full/path/to/temp01.dbf' SIZE 256M REUSE
3 AUTOEXTEND ON NEXT 128M MAXSIZE unlimited
4 EXTENT MANAGEMENT LOCAL UNIFORM SIZE 1M;
Tablespace created.
SQL> ALTER DATABASE DEFAULT TEMPORARY TABLESPACE temp;
Database altered.
SQL> DROP TABLESPACE temp2 INCLUDING CONTENTS AND DATAFILES;
Tablespace dropped.
Hopefully one of these things will help!
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
I bet for sure, that this is because you didn't close the running instance of the program before trying to re-compile it.
Generally, ld.exe
returns 1 when it can't access required files. This usually includes
Access denied
)The program looks completely fine, so the second point should not hit. In usual cases, it's impossible for ld
to fail to open the object file (unless you have a faulty drive and a dirty filesystem), so the first point is also nearly impossible.
Now we get to the third point. Note that Windows not allow writing to a file when it's in use, so the running instance of your program prevents ld.exe
from writing the new linked program to it.
So next time be sure to close running programs before compiling.
I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:
var count = 1;
(function ($) {
$.event.special.destroyed_proxy = {
remove: function (o) {
$(this).trigger('destroyed');
}
}
})(jQuery)
$('.remove').on('click', function () {
$(this).parent().remove();
});
$('li').on('destroyed_proxy destroyed', function () {
console.log('Element removed');
if (count > 2) {
$('li').off('destroyed');
console.log('unbinded');
}
count++;
});
Here is a fiddle
If you don't mind using a third party library, with cyclops-react, a library I contribute to, you can use the FluentFunctions API to write
Function<String, Integer> standardFn = FluentFunctions.ofChecked(this::myMethod);
ofChecked takes a jOO? CheckedFunction and returns the reference softened back to a standard (unchecked) JDK java.util.function.Function.
Alternatively you can keep working with the captured function via the FluentFunctions api!
For example to execute your method, retrying it up to 5 times and logging it's status you can write
FluentFunctions.ofChecked(this::myMethod)
.log(s->log.debug(s),e->log.error(e,e.getMessage())
.try(5,1000)
.apply("my param");
There is no .NET framework support for IMAP. You'll need to use some 3rd party component.
Try https://www.limilabs.com/mail, it's very affordable and easy to use, it also supports SSL:
using(Imap imap = new Imap())
{
imap.ConnectSSL("imap.company.com");
imap.Login("user", "password");
imap.SelectInbox();
List<long> uids = imap.SearchFlag(Flag.Unseen);
foreach (long uid in uids)
{
string eml = imap.GetMessageByUID(uid);
IMail message = new MailBuilder()
.CreateFromEml(eml);
Console.WriteLine(message.Subject);
Console.WriteLine(message.TextDataString);
}
imap.Close(true);
}
Please note that this is a commercial product I've created.
You can download it here: https://www.limilabs.com/mail.
I've found a solution that does the check before calling fitBounds
so you don't zoom in and suddenly zoom out
var bounds = new google.maps.LatLngBounds();
// extend bounds with each point
var minLatSpan = 0.001;
if (bounds.toSpan().lat() > minLatSpan) {
gmap.fitBounds(bounds);
} else {
gmap.setCenter(bounds.getCenter());
gmap.setZoom(16);
}
You'll have to play around with the minLatSpan variable a bit to get it where you want. It will vary based on both zoom-level and the dimensions of the map canvas.
You could also use longitude instead of latitude
You cannot exactly get a list of commands started with nohup
but you can see them along with your other processes by using the command ps x
. Commands started with nohup
will have a question mark in the TTY column.
Using just awk you could do (I also shortened some of your piping):
strings -a libAddressDoctor5.so | awk '/EngineVersion/ { if(NR==2) { gsub("\"",""); print $2 } }'
I can't verify it for you because I don't know your exact input, but the following works:
echo "Blah EngineVersion=\"123\"" | awk '/EngineVersion/ { gsub("\"",""); print $2 }'
See also this question on removing single quotes.
You can set the width like this :
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
Just Add AjaxControlToolkit.dll to your Reference folder.
On your Project Solution
Right Click on Reference Folder > Add Reference > browse AjaxControlToolkit.dll .
Then build.
Regards
One way to do it must be if (typeof myObj.prop1 != "undefined") {...}
class Timer
{
private $startTime = null;
public function __construct($showSeconds = true)
{
$this->startTime = microtime(true);
echo 'Working - please wait...' . PHP_EOL;
}
public function __destruct()
{
$endTime = microtime(true);
$time = $endTime - $this->startTime;
$hours = (int)($time / 60 / 60);
$minutes = (int)($time / 60) - $hours * 60;
$seconds = (int)$time - $hours * 60 * 60 - $minutes * 60;
$timeShow = ($hours == 0 ? "00" : $hours) . ":" . ($minutes == 0 ? "00" : ($minutes < 10 ? "0" . $minutes : $minutes)) . ":" . ($seconds == 0 ? "00" : ($seconds < 10 ? "0" . $seconds : $seconds));
echo 'Job finished in ' . $timeShow . PHP_EOL;
}
}
$t = new Timer(); // echoes "Working, please wait.."
[some operations]
unset($t); // echoes "Job finished in h:m:s"
Dictionary is a key value pair. Catch Key by
dic["cat"]
and assign its value like
dic["cat"] = 5
If the dataframes DO NOT all have the same columns try the following:
df = pd.DataFrame.from_dict(map(dict,df_list))
Sure, you can put your constants into a separate module. For example:
const.py:
A = 12
B = 'abc'
C = 1.2
main.py:
import const
print const.A, const.B, const.C
Note that as declared above, A
, B
and C
are variables, i.e. can be changed at run time.
With the release of Android 2.3 (Gingerbread), you can now use the android.hardware.Camera
class to get the number of cameras, information about a specific camera, and get a reference to a specific Camera
. Check out the new Camera
APIs here.
:e $MYGVIMRC
Enter:set guifont=
Tab Enter.The command in step 6 will insert the contents of the :
special register
which contains the last ex-mode command used. Here that will be the command
from step 4, which has the properly formatted font name thanks to the tab
completion of the value previously set using the GUI dialog.
This isn't exactly intuitive, but you cannot Redim(VB6 Ref) an array if you dimmed it with dimensions. Exact quote from linked page is:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).
In other words, instead of dim invoices(10,0)
You should use
Dim invoices()
Redim invoices(10,0)
Then when you ReDim, you'll need to use Redim Preserve (10,row)
Warning: When Redimensioning multi-dimensional arrays, if you want to preserve your values, you can only increase the last dimension. I.E. Redim Preserve (11,row)
or even (11,0)
would fail.
After reading Paul's answer, I went on digging for more information on https://dev.mysql.com/doc/refman/5.7/en/query-log.html
I found a really useful code by a person. Here's the summary of the context.
(Note: The following code is not mine)
This script is an example to keep the table clean which will help you to reduce your table size. As after a day, there will be about 180k queries of log. ( in a file, it would be 30MB per day)
You need to add an additional column (event_unix) and then you can use this script to keep the log clean... it will update the timestamp into a Unix-timestamp, delete the logs older than 1 day and then update the event_time into Timestamp from event_unix... sounds a bit confusing, but it's working great.
Commands for the new column:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
ALTER TABLE `general_log_temp`
ADD COLUMN `event_unix` int(10) NOT NULL AFTER `event_time`;
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Cleanup script:
SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
UPDATE general_log_temp SET event_unix = UNIX_TIMESTAMP(event_time);
DELETE FROM `general_log_temp` WHERE `event_unix` < UNIX_TIMESTAMP(NOW()) - 86400;
UPDATE general_log_temp SET event_time = FROM_UNIXTIME(event_unix);
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';
Credit goes to Sebastian Kaiser (Original writer of the code).
Hope someone will find it useful as I did.
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
See also: mySQL manual on UPDATE
I needed to add my views dynamically/programmatically, so adding an extra view would have been cumbersome. My view height was WRAP_CONTENT, so I couldn't use the rectangle solution. I found a blog-post here about extending TextView, overriding onDraw() and painting in the line, so I implemented that and it works well. See my code below:
public class NoteTextView extends TextView {
public NoteTextView(Context context) {
super(context);
}
private Paint paint = new Paint();
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.parseColor("#F00000FF"));
paint.setStrokeWidth(0);
paint.setStyle(Paint.Style.FILL);
canvas.drawLine(0, 0, 0, getHeight(), paint);
}
}
I needed a vertical line on the left, but the drawline parameters are drawLine(startX, startY, stopX, stopY, paint)
so you can draw any straight line in any direction across the view.
Then in my activity I have
NoteTextView note = new NoteTextView(this);
Hope this helps.
Promise.all
with using modern async/await
approach
const promise1 = //...
const promise2 = //...
const data = await Promise.all([promise1, promise2])
const dataFromPromise1 = data[0]
const dataFromPromise2 = data[1]
Here is my solution. I think it is simpler. It only expands the view but can easy be extended.
public class WidthExpandAnimation extends Animation
{
int _targetWidth;
View _view;
public WidthExpandAnimation(View view)
{
_view = view;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
if (interpolatedTime < 1.f)
{
int newWidth = (int) (_targetWidth * interpolatedTime);
_view.layout(_view.getLeft(), _view.getTop(),
_view.getLeft() + newWidth, _view.getBottom());
}
else
_view.requestLayout();
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight)
{
super.initialize(width, height, parentWidth, parentHeight);
_targetWidth = width;
}
@Override
public boolean willChangeBounds() {
return true;
}
}
It seems you want to save your class instances across sessions, and using pickle
is a decent way to do this. However, there's a package called klepto
that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto
is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.
Note that It works for dynamically added class attributes, which pickle cannot do...
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>>
>>> db['banana'] = banana
>>> db.dump()
>>>
Then we restart…
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>>
>>> db['banana'].color
'yellow'
>>>
Klepto
works on python2 and python3.
Get the code here: https://github.com/uqfoundation
JButton
has a model which answers these question:
isArmed()
, isPressed()
, isRollOVer()
etc. Hence you can ask the model for the answer you are seeking:
if(jButton1.getModel().isPressed())
System.out.println("the button is pressed");
Solution for Kotlin (Android 3.3, Kotlin 1.3.20)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
supportActionBar!!.elevation = 0f
}
Use this query to get Schema, Table, Column,Type, max_length, is_nullable
SELECT QUOTENAME(SCHEMA_NAME(tb.[schema_id])) AS 'Schema'
,QUOTENAME(OBJECT_NAME(tb.[OBJECT_ID])) AS 'Table'
,C.NAME as 'Column'
,T.name AS 'Type'
,C.max_length
,C.is_nullable
FROM SYS.COLUMNS C INNER JOIN SYS.TABLES tb ON tb.[object_id] = C.[object_id]
INNER JOIN SYS.TYPES T ON C.system_type_id = T.user_type_id
WHERE tb.[is_ms_shipped] = 0
ORDER BY tb.[Name]
In IE I just use a class "normal_ol" for styling an ol list and made some modifications shown below:
previous code: ol.normal_ol { float:left; padding:0 0 0 25px; margin:0; width:500px;} ol.normal_ol li{ font:normal 13px/20px Arial; color:#4D4E53; float:left; width:100%;}
modified code: ol.normal_ol { float:left; padding:0 0 0 25px; margin:0;} ol.normal_ol li{ font:normal 13px/20px Arial; color:#4D4E53; }
You could use git remote like:
git fetch origin
and then setup a local branch to track the remote branch like below:
git branch --track [local-branch-name] origin/remote-branch-name
You would now have the contents of the remote github branch in local-branch-name.
You could switch to that local-branch-name and start work:
git checkout [local-branch-name]
I have found the answer to my question.
client.DefaultRequestHeaders.Add("X-Version","1");
That should add a custom header to your request
When a dictionary is enumerated, it will yield KeyValuePair<TKey,TValue>
objects... so you just need to specify "Value" and "Key" for DataTextField
and DataValueField
respectively, to select the Value/Key properties.
Thanks to Joe's comment, I reread the question to get these the right way round. Normally I'd expect the "key" in the dictionary to be the text that's displayed, and the "value" to be the value fetched. Your sample code uses them the other way round though. Unless you really need them to be this way, you might want to consider writing your code as:
list.Add(cul.DisplayName, cod);
(And then changing the binding to use "Key" for DataTextField
and "Value" for DataValueField
, of course.)
In fact, I'd suggest that as it seems you really do want a list rather than a dictionary, you might want to reconsider using a dictionary in the first place. You could just use a List<KeyValuePair<string, string>>
:
string[] languageCodsList = service.LanguagesAvailable();
var list = new List<KeyValuePair<string, string>>();
foreach (string cod in languageCodsList)
{
CultureInfo cul = new CultureInfo(cod);
list.Add(new KeyValuePair<string, string>(cul.DisplayName, cod));
}
Alternatively, use a list of plain CultureInfo
values. LINQ makes this really easy:
var cultures = service.LanguagesAvailable()
.Select(language => new CultureInfo(language));
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();
If you're not using LINQ, you can still use a normal foreach loop:
List<CultureInfo> cultures = new List<CultureInfo>();
foreach (string cod in service.LanguagesAvailable())
{
cultures.Add(new CultureInfo(cod));
}
languageList.DataTextField = "DisplayName";
languageList.DataValueField = "Name";
languageList.DataSource = cultures;
languageList.DataBind();
best way I know
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = "Do you really want to leave this page?"
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
This command works perfectly. I have 8GB ram in my laptop, So I set size=8192. It is all about ram and also you need set file name. I run npm run build command that's why I used build.js.
node --expose-gc --max-old-space-size=8192 node_modules/react-scripts/scripts/build.js
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
In addition, if you want to use MacVim (or GVim) as $VISUAL
or $EDITOR
, you should be aware that by default MacVim will fork a new process from the parent, resulting in the MacVim return value not reaching the parent process. This may confuse other applications, but Git seems to check the status of a temporary commit message file, which bypasses this limitation. In general, it is a good practice to export VISUAL='mvim -f'
to ensure MacVim will not fork a new process when called, which should give you what you want when using it with your shell environment.
I'm not sure why the simplest way has been ignored/omitted in the answers above:
SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02
SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08
I prefer the second one because whichever language you speak, you will understand what date it is!
Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.
I got this error while connecting to Amazon RDS. I checked the server status 50% of CPU usage while it was a development server and no one is using it.
It was working before, and nothing in the connection configuration has changed. Rebooting the server fixed the issue for me.
@Kunigami: I think you may be mistaken about Guava's newArrayList
method. It does not check whether the Iterable is a List type and simply return the given List as-is. It always creates a new list:
@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<E>(Collections2.cast(elements))
: newArrayList(elements.iterator());
}
The method below returns only the files with certain extension (eg: file with .txt but not .txt1)
public static IEnumerable<string> GetFilesByExtension(string directoryPath, string extension, SearchOption searchOption)
{
return
Directory.EnumerateFiles(directoryPath, "*" + extension, searchOption)
.Where(x => string.Equals(Path.GetExtension(x), extension, StringComparison.InvariantCultureIgnoreCase));
}
input = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
output = []
for item in input:
items = item.split(',')
output.append([items[0], int(items[1]), int(items[2])])
Extending the contains function you linked to:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
if(a[i].search(regex) > -1){
return i;
}
}
return -1;
}
Then you call the function with an array of strings and a regex, in your case to look for height:
containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)
You could additionally also return the index where height was found:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
int pos = a[i].search(regex);
if(pos > -1){
return [i, pos];
}
}
return null;
}
You can customize Facebook share dialog box by using asynchronous JavaScript SDK provided by Facebook and setting up its parameter values
Have a look at the following code:
<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'URL which you would like to share ',
picture: ‘URL of the image which is going to appear as thumbnail image in share dialogbox’,
caption: 'Caption like which appear as title of the dialog box',
description: 'Small description of the post',
message: ''
}
);
});
});
</script>
Before copying and pasting the below code you must first initialize the SDK and set up jQuery library. Please click here to know a step by step how to set information on the same.
This is the safer way:
var elements = document.getElementsByClassName("myclass");
for (var i = 0; i < elements.length; i++) myFunction(elements[i]);
Rhomobile Rhodes (http://rhomobile.com/products/rhodes) is very similar in approach to PhoneGap, but is the only framework with:
PHP's string length is limited by the way strings are represented in PHP; memory does not have anything to do with it.
According to phpinternalsbook.com, strings are stored in struct { char *val; int len; } and since the maximum size of an int in C is 4 bytes, this effectively limits the maximum string size to 2GB.
I use this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Update 2018:
This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC
on server and client.
2018-07-31T11:56:48Z
- ISO string can be parsed using new Date("2018-07-31T11:56:48Z")
and obtained from a Date
object
using dateObject.toISOString()
1533038208000
- milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date
object
using dateObject.getTime()
As explained in short C# (but also for other language compilers as well, like Java)
There is a predefined implicit conversion from short to int, long, float, double, or decimal.
You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:
short x = 5, y = 12;
The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.
short z = x + y; // Error: no conversion from int to short
To fix this problem, use a cast:
short z = (short)(x + y); // OK: explicit conversion
It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:
int m = x + y;
long n = x + y;
A good follow-up question is:
"why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default" ?
A first answer can be found in:
Classifying and Formally Verifying Integer Constant Folding
The Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated. This is an important property of Java as this programming language has been designed to be used in distributed applications on the Internet. A Java program is required to produce the same result independently of the target machine executing it.
In contrast, C (and the majority of widely-used imperative and object-oriented programming languages) is more sloppy and leaves many important characteristics open. The intention behind this inaccurate language specification is clear. The same C programs are supposed to run on a 16-bit, 32-bit, or even 64-bit architecture by instantiating the integer arithmetics of the source programs with the arithmetic operations built-in in the target processor. This leads to much more e?cient code because it can use the available machine operations directly. As long as the integer computations deal only with numbers being “sufficiently small”, no inconsistencies will arise.
In this sense, the C integer arithmetic is a placeholder which is not defined exactly by the programming language specification but is only completely instantiated by determining the target machine.
Java precisely defines how integers are represented and how integer arithmetic is to be computed.
Java Integers
--------------------------
Signed | Unsigned
--------------------------
long (64-bit) |
int (32-bit) |
short (16-bit) | char (16-bit)
byte (8-bit) |
Char is the only unsigned integer type. Its values represent Unicode characters, from
\u0000
to\uffff
, i.e. from 0 to 216-1.If an integer operator has an operand of type long, then the other operand is also converted to type long. Otherwise the operation is performed on operands of type int, if necessary shorter operands are converted into int. The conversion rules are exactly specified.
[From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)
Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH,
Fakultät für Informatik,
Universität Karlsruhe
Karlsruhe, Germany]
Had peno's version optimised a bit. The increase in performance is perceptible.
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
Good cocoa function:
-(BOOL) NSStringIsValidEmail:(NSString *)checkString
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:checkString];
}
Discussion on Lax vs. Strict - http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
And because categories are just better, you could also add an interface:
@interface NSString (emailValidation)
- (BOOL)isValidEmail;
@end
Implement
@implementation NSString (emailValidation)
-(BOOL)isValidEmail
{
BOOL stricterFilter = NO; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
NSString *stricterFilterString = @"^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$";
NSString *laxString = @"^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$";
NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
return [emailTest evaluateWithObject:self];
}
@end
And then utilize:
if([@"[email protected]" isValidEmail]) { /* True */ }
if([@"InvalidEmail@notreallyemailbecausenosuffix" isValidEmail]) { /* False */ }
Use character classes: [ \t]
You can use
<?php the_category(', '); ?>
which would output them in a comma separated list.
You can also do the same for tags as well:
<?php the_tags('<em>:</em>', ', ', ''); ?>
Just a little comment from my side since the OBJECT_ID
doesn't work for me. It always returns that
`#tempTable doesn't exist
..even though it does exist. I just found it's stored with different name (postfixed by _
underscores) like so :
#tempTable________
This works well for me:
IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#tempTable%') BEGIN
DROP TABLE #tempTable;
END;
You need to specify the domain:
$('.button1').click(function() {
window.location = 'www.example.com/index.php?id=' + this.id;
});
Someone wrote...
I just set all files that end in ".sh" to open with Terminal. It works fine and you don't have to change the name of each shell script you want to run.
get_template_directory_uri();
This function will help you retrieve theme directory URI, and can be used with your images, your example below:
<img src="<?php echo get_template_directory_uri(); ?>/images/mindset.jpg" />
You should use dynamic
object to resolve combobox item in run-time.
comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new { Text = "Text", Value = "Value" });
(comboBox.SelectedItem as dynamic).Value
Incrementing a variable can be done like that:
_my_counter=$[$_my_counter + 1]
Counting the number of occurrence of a pattern in a column can be done with grep
grep -cE "^([^ ]* ){2}US"
-c
count
([^ ]* )
To detect a colonne
{2}
the colonne number
US
your pattern
I tried everything and nothing worked so here is another solution that finally worked (for me).
I had to check Enable Java EE configuration
under Preferences -> Maven -> Jave EE configuration
After that you can check that more entries were added in Deployment assemblies
of the project settings.
Looking at the Eclipse plugin docs I found some useful tasks that rebuilt my classpath and updated the required dependencies.
gradle cleanEclipse
to clean the Eclipse configuration completely. If this doesn;t work you may try more specific tasks:
gradle cleanEclipseProject
to remove the .project filegradle cleanEclipseClasspath
to empty the project's classpathgradle eclipse
to rebuild the Eclipse configurationFor me upgrading gradle version and plugin to the latest version did the trick.
You forgot to put z as an bind variable.
The following EXECUTE command runs a PL/SQL statement that references a stored procedure:
SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')
Note that the value returned by the stored procedure is being return into :Z
Try:
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"
Your alias firstlast is not available in the where clause of the query unless you do the query as a sub-select.
To check whether some number n is in the inclusive range denoted by the two number a and b you do either
if a <= n <= b:
print "yes"
else:
print "no"
use the replace >=
and <=
with >
and <
to check whether n
is in the exclusive range denoted by a
and b
(i.e. a
and b
are not themselves members of the range).
Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.
Step1. Install bulma package using npm
npm install --save bulma
Step2. Open angular.json and update following code
...
"styles": [
"node_modules/bulma/css/bulma.css",
"src/styles.scss"
],
...
That's it.
To easily expose Bulma’s tools, add stylePreprocessorOptions to angular.json.
...
"styles": [
"src/styles.scss",
"node_modules/bulma/css/bulma.css"
],
"stylePreprocessorOptions": {
"includePaths": [
"node_modules",
"node_modules/bulma/sass/utilities"
]
},
...
The approved answer from George Claghorn worked great for simply inserting text at the cursor position. If the user had selected text though, and you want that text to be replaced (the default experience with most text), you need to make a small change when setting the 'back' variable.
Also, if you don't need to support older versions of IE, modern versions support textarea.selectionStart, so you can take out all of the browser detection, and IE-specific code.
Here is a simplified version that works for Chrome and IE11 at least, and handles replacing selected text.
function insertAtCaret(areaId, text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var caretPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0, caretPos);
var back = (txtarea.value).substring(txtarea.selectionEnd, txtarea.value.length);
txtarea.value = front + text + back;
caretPos = caretPos + text.length;
txtarea.selectionStart = caretPos;
txtarea.selectionEnd = caretPos;
txtarea.focus();
txtarea.scrollTop = scrollPos;
}
Visually select the text and type:
ggVG
!tee >(pbcopy)
Which I find nicer than:
ggVG
:w !pbcopy
Since it doesn't flash up a prompt: "Press ENTER or type command to continue"
onCreate()
When we create DataBase at a first time (i.e Database is not exists) onCreate()
create database with version which is passed in
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
onCreate()
method is creating the tables you’ve defined and executing any other code you’ve written. However, this method will only be called if the SQLite file is missing in your app’s data directory (/data/data/your.apps.classpath/databases
).
This method will not be called if you’ve changed your code and relaunched in the emulator. If you want onCreate()
to run you need to use adb to delete the SQLite database file.
onUpgrade()
SQLiteOpenHelper
should call the super constructor.onUpgrade()
method will only be called when the version integer is larger than the current version running in the app.onUpgrade()
method to be called, you need to increment the version number in your code.In the model, write the below code;
public $timestamps = false;
This would work.
Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
without site name
{{Storage::url($photoLink)}}
if you want to add site name to it example to append on api JSON felids
public function getPhotoFullLinkAttribute()
{
return env('APP_URL', false).Storage::url($this->attributes['avatar']) ;
}
You can redirect the output to /dev/null
. For more info regarding /dev/null read this link.
You can hide the output of a comand in the following ways :
echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done.";
Redirect the standard output to /dev/null
, but not the standard error. This will show the errors occurring during the installation, for example if yum
cannot find a package.
echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";
While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null
.
To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...
So, applied to your dataframe:
In [1]: a[a['c2'] == 1].index[0] In [2]: a[a['c1'] > 7].index[0]
Out[1]: 0 Out[2]: 4
Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]
In [3]: a[a['c2'] >= 7].index[1] In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]
Out[3]: 4 Out[4]: 3
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag
wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
Use --format option
git tag -l --format='%(tag) %(subject)'
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
Use XmlDocument.Load()
method to load XML from your file. Then use XmlDocument.InnerXml
property to get XML string.
XmlDocument doc = new XmlDocument();
doc.Load("path to your file");
string xmlcontents = doc.InnerXml;
I often use the following:
c := b
if a > b {
c = a
}
basically the same as @Not_a_Golfer's but using type inference.
According to Collections Framework Overview you have two balanced tree implementations:
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
if anyone want to add a value inside loop then you can use this its working 100%
{% set ftotal= {'total': 0} %}
{%- for pe in payment_entry -%}
{% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %}
{%- endfor -%}
{{ftotal.total}}
output = 5
I think i'am late for the party but when you use a wildfly, you can add an default-encoding to the standalone.xml. Just search in the standalone.xml for
<servlet-container name="default">
and add encoding like this:
<servlet-container name="default" default-encoding="UTF-8">
Looks like @mixin
and @include
are not needed for a simple case like this.
One can just do:
.myclass {
font-weight: bold;
font-size: 90px;
}
.myotherclass {
@extend .myclass;
color: #000000;
}
This is a very simple solution, but it works for me:
<!--TEXT-AREA-->_x000D_
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>_x000D_
_x000D_
<!--JAVASCRIPT-->_x000D_
<script type="text/javascript">_x000D_
function setHeight(fieldId){_x000D_
document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';_x000D_
}_x000D_
setHeight('textBox1');_x000D_
</script>
_x000D_
rows, cols = x,y # your values
grid = Array.new(rows) { Array.new(cols) }
As for accessing elements, this article is pretty good for step by step way to encapsulate an array in the way you want:
GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.
Hiding the cursor can be done with ShowCursor().
>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>
However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!
NOTE: This is exactly what OP said they did. (But didn't show code for.) I show the details here, so that you can compare it to the accepted answer. My point is that OP's original instinct was, IMHO, better than the answer he accepted.
Given how highly upvoted the accepted answer is, I'd like to point out the "naive" answer to one-time initialization of static methods, is hardly more code than that implementation of Singleton -- and has an essential advantage.
final class MyClass {
public static function someMethod1() {
MyClass::init();
// whatever
}
public static function someMethod2() {
MyClass::init();
// whatever
}
private static $didInit = false;
private static function init() {
if (!self::$didInit) {
self::$didInit = true;
// one-time init code.
}
}
// private, so can't create an instance.
private function __construct() {
// Nothing to do - there are no instances.
}
}
The advantage of this approach, is that you get to call with the straightforward static function syntax:
MyClass::someMethod1();
Contrast it to the calls required by the accepted answer:
MyClass::getInstance->someMethod1();
As a general principle, it is best to pay the coding price once, when you code a class, to keep callers simpler.
If you are NOT using PHP 7.4's opcode.cache
, then use Victor Nicollet's answer. Simple. No extra coding required. No "advanced" coding to understand. (I recommend including FrancescoMM's comment, to make sure "init" will never execute twice.) See Szczepan's explanation of why Victor's technique won't work with opcode.cache
.
If you ARE using opcode.cache
, then AFAIK my answer is as clean as you can get. The cost is simply adding the line MyClass::init();
at start of every public method. NOTE: If you want public properties, code them as a get
/ set
pair of methods, so that you have a place to add that init
call.
(Private members do NOT need that init
call, as they are not reachable from the outside - so some public method has already been called, by the time execution reaches the private member.)
Not that I know of, unless you select from INFORMATION_SCHEMA
, as others have mentioned.
However, the SHOW
command is pretty flexible,
E.g.:
SHOW tables like '%s%'
What you need is to have a controller that responds to the url first which then renders your jsp. See this link for a solution.
Just in case anyone else stumbles upon this that was doing a database first implementation like me.
I made a change by extending the ApplicationUser
class, adding a new field to the AspNetUsers
table, and then had this error on startup.
I was able to resolve this by deleting the record created in the __MigrationHistory
table (there was only one record there) I assume EF decided that I needed to update my database using the migration tool - but I had already done this manually myself.
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
The Series class has a pandas.Series.dt
accessor object with several
useful datetime attributes, including dt.days
. Access this attribute via:
timedelta_series.dt.days
You can also get the seconds
and microseconds
attributes in the same way.
Use SequenceEqual
to check for sequence equality because Equals
method checks for reference equality.
var a = ints1.SequenceEqual(ints2);
Or if you don't care about elements order use Enumerable.All
method:
var a = ints1.All(ints2.Contains);
The second version also requires another check for Count
because it would return true even if ints2
contains more elements than ints1
. So the more correct version would be something like this:
var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;
In order to check inequality just reverse the result of All
method:
var a = !ints1.All(ints2.Contains)
The problem here was a typo error in the password used, which was not easily identified due to the characters / letters used in the password.
Queue
is an interface in java, you could not do that.
try:
Queue<Integer> Q = new LinkedList<Integer>();
Branches are made of wood and grow from the trunk of the tree. Tags are made of paper (derivative of wood) and hang like Christmas Ornaments from various places in the tree.
Your project is the tree, and your feature that will be added to the project will grow on a branch. The answer is branch.
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
var regex = new RegExp("^[A-Za-z0-9? ,_-]+$");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
in the regExp [A-Za-z0-9?spaceHere,_-]
there is a literal space after the question mark '?'. This matches space. Others like /^[-\w\s]+$/
and /^[a-z\d\-_\s]+$/i
were not working for me.
NONE of these answers work for situations where the value name contains spaces, dots, or other characters that are reserved in PowerShell. In that case you have to wrap the name in double quotes as per http://blog.danskingdom.com/accessing-powershell-variables-with-periods-in-their-name/ - for example:
PS> Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
14.0 : C:\Program Files (x86)\Microsoft Visual Studio 14.0\
12.0 : C:\Program Files (x86)\Microsoft Visual Studio 12.0\
11.0 : C:\Program Files (x86)\Microsoft Visual Studio 11.0\
15.0 : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\V
S7
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS
PSChildName : VS7
PSProvider : Microsoft.PowerShell.Core\Registry
If you want to access any of the 14.0, 12.0, 11.0, 15.0 values, the solution from the accepted answer will not work - you will get no output:
PS> (Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7 -Name 15.0).15.0
PS>
What does work is quoting the value name, which you should probably be doing anyway for safety:
PS> (Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7" -Name "15.0")."15.0"
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS>
Thus, the accepted answer should be modified as such:
PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"
PS> $value = "15.0"
PS> (Get-ItemProperty -Path $key -Name $value).$value
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS>
This works in PowerShell 2.0 through 5.0 (although you should probably be using Get-ItemPropertyValue
in v5).
You are using an adjacent sibling selector (+
) when the elements are not siblings. The label is the parent of the input, not it's sibling.
CSS has no way to select an element based on it's descendents (nor anything that follows it).
You'll need to look to JavaScript to solve this.
Alternatively, rearrange your markup:
<input id="foo"><label for="foo">…</label>
You can use the Membership Operator isCase() which is another groovy way:
assert Date.isCase(new Date())
Very, very rarely.
I did it only for one very very specific known cases. For example, java.lang.UnsatisfiedLinkError could be throw if two independence ClassLoader load same DLL. (I agree that I should move the JAR to a shared classloader)
But most common case is that you needed logging in order to know what happened when user come to complain. You want a message or a popup to user, rather then silently dead.
Even programmer in C/C++, they pop an error and tell something people don't understand before it exit (e.g. memory failure).
Probably a little late to post my answer here but still I'll post, it might benefit someone though,
I had faced the same problem,
The main reason being that I created the virtualenv as a "root" user But later was trying to activate it using another user.
chmod won't work as you're not the owner of the file, hence the alternative is to use chown (to change the ownership)
For e.g. :
If you have your virtualenv created at /home/abc/ENV
Then CD to /home/abc
and run the command : chown -Rv [user-to-whom-you want-change-ownership] [folder/filename whose ownership needs to be changed]
In this example the commands would be : chown -Rv abc ENV
After the ownership is successfully changed you can simply run source /ENV/bin/./activate and your should be able to activate the virtualenv correctly.
I wrote an article of when to use an abstract class and when to use an interface. There is a lot more of a difference between them other than "one IS-A... and one CAN-DO...". To me, those are canned answers. I mention a few reasons when to use either of them. Hope it helps.
alt text http://img183.imageshack.us/img183/1350/pizzasv6.png
The parent directory of an included file would be
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php
then by calling /file/index.php
getcwd() is /var/www/html/folder
__DIR__ is /var/www/html/folder/inc
so dirname(__DIR__) is /var/www/html/folder
but what we want is /var/www/html which is dirname(getcwd())
A simple solution is using the scalers offered by the sklearn.preprocessing library.
scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)
The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()
Without favouring any particular naming choice, remember that a git repo can be cloned into any root directory of your choice:
git clone https://github.com/user/repo.git myDir
Here repo.git
would be cloned into the myDir
directory.
So even if your naming convention for a public repo ended up to be slightly incorrect, it would still be possible to fix it on the client side.
That is why, in a distributed environment where any client can do whatever he/she wants, there isn't really a naming convention for Git repo.
(except to reserve "xxx.git
" for bare form of the repo 'xxx
')
There might be naming convention for REST service (similar to "Are there any naming convention guidelines for REST APIs?"), but that is a separate issue.
In Swift 4 it works like below
collectionView.setContentOffset(CGPoint.zero, animated: true)
This page explains it pretty well.
As a numeric
the allowable range that can be stored in that field is -10^38 +1
to 10^38 - 1
.
The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.
The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.
So the range that can be stored in this particular field is -(10^18 - 1)
to (10^18 - 1)
Or -999999999999999999
to 999999999999999999
Integers only
var a = {"apples": 3, "oranges": 4, "bananas": 42};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
array_keys.push(key);
array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);
you must have record in table or array record in database.
example:
SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);
Creating a data.table
with key=V1
automatically does this for you. Using Stephan's data foo
> require(data.table)
> foo.dt <- data.table(foo, key="V1")
> foo.dt
V1 V2
1: 1 349
2: 1 393
3: 1 392
4: 2 94
5: 3 49
6: 3 32
7: 4 459
I just had same issue when I installed the oracle 11g and then creating the database.
I don't even know that the listener has to create manually. Hence, I open Net Configuration Assistant and manually create the listener.
And I can connect the database that I created locally through sql developer.
I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.
window.addEventListener('scroll', function (evt) {
// This value is your scroll distance from the top
var distance_from_top = document.body.scrollTop;
// The user has scrolled to the tippy top of the page. Set appropriate style.
if (distance_from_top === 0) {
}
// The user has scrolled down the page.
if(distance_from_top > 0) {
}
});
I still had a dark grey line after attempting the other answers. I had to add the following two lines to make everything "invisible" in terms of row lines between cells.
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.separatorColor = [UIColor clearColor];
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.util.Base64;
import java.util.Base64.Encoder;
/**
*
* @author shivshankar pal
*
* this code is working properly. doing proper encription and decription
note:- it will work only with jdk8
*
*
*/
public class TDes {
private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,
0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };
private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00 };
public static String encode(String args) {
System.out.println("plain data==> " + args);
byte[] encoding;
try {
encoding = Base64.getEncoder().encode(args.getBytes("UTF-8"));
System.out.println("Base64.encodeBase64==>" + new String(encoding));
byte[] str5 = des3EncodeCBC(key, keyiv, encoding);
System.out.println("des3EncodeCBC==> " + new String(str5));
byte[] encoding1 = Base64.getEncoder().encode(str5);
System.out.println("Base64.encodeBase64==> " + new String(encoding1));
return new String(encoding1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String decode(String args) {
try {
System.out.println("encrypted data==>" + new String(args.getBytes("UTF-8")));
byte[] decode = Base64.getDecoder().decode(args.getBytes("UTF-8"));
System.out.println("Base64.decodeBase64(main encription)==>" + new String(decode));
byte[] str6 = des3DecodeCBC(key, keyiv, decode);
System.out.println("des3DecodeCBC==>" + new String(str6));
String data=new String(str6);
byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes("UTF-8"));
System.out.println("plaintext==> " + new String(decode1));
return new String(decode1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "u mistaken in try block";
}
private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(key);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/ CBC/NoPadding");//PKCS5Padding NoPadding
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bout = cipher.doFinal(data);
return bout;
} catch (Exception e) {
System.out.println("methods qualified name" + e);
}
return null;
}
}
If your data set is too large first select required rows by Select(). it will stop further looping.
DataRow[] selected = table.Select("Product_id = 2")
Then loop through subset and update
foreach (DataRow row in selected)
{
row["Product_price"] = "<new price>";
}
use "Studio3T for MongoDB" that have Export and Import tools by click on database , collections or specific collection download link : https://studio3t.com/download/
If the resource is showing and is a view, you can also capture it. Like a screenshot:
View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
This actually grabs the whole layout but you can alter as you wish.
In straight Javascript you could do something similar to the following:
var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
var e = form.elements[i];
kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");
In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.
you must write single quotes then double quotes then dot before name of field and after like that
mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");
Avoid SELECT *
in your main query.
Avoid duplicate columns: the JOIN
condition ensures One.One_Name
and two.One_Name
will be equal therefore you don't need to return both in the SELECT
clause.
Avoid duplicate column names: rename One.ID
and Two.ID
using 'aliases'.
Add an ORDER BY
clause using the column names ('alises' where applicable) from the SELECT
clause.
Suggested re-write:
SELECT T1.ID AS One_ID, T1.One_Name,
T2.ID AS Two_ID, T2.Two_name
FROM One AS T1
INNER JOIN two AS T2
ON T1.One_Name = T2.One_Name
ORDER
BY One_ID;
does your proxy require you to authenticate? because if it does, you might want you configure your proxy like this.
placeholder names. username is a placeholder for your actual username. password is a placeholder for your actual password. proxy.company.com is a placeholder for your actualy proxy *port" is your actualy port the proxy goes through. its usualy 8080
npm config set proxy "http://username:[email protected]:port"
npm config set https-proxy "http://username:[email protected]:port"
Better use Uri.IsWellFormedUriString(string uriString, UriKind uriKind)
. http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
Example :-
if(Uri.IsWellFormedUriString(slct.Text,UriKind.Absolute))
{
Uri uri = new Uri(slct.Text);
if (DeleteFileOnServer(uri))
{
nn.BalloonTipText = slct.Text + " has been deleted.";
nn.ShowBalloonTip(30);
}
}
A different approach would be to using multi-dimensional arrays:
var driversCounter = [
["one", 1],
["two", 2],
["three", 3],
["four", 4],
["five", 5]
]
and access the value by driverCounter[k][j], where j=0,1 in the case.
Add it in a drop down list by:
var dd = document.getElementById('your_dropdown_element');
for(i=0;i<driversCounter.length-1;i++)
{
dd.options.add(opt);
opt.text = driversCounter[i][0];
opt.value = driversCounter[i][1];
}
Python's sets (and dictionaries) will iterate and print out in some order, but exactly what that order will be is arbitrary, and not guaranteed to remain the same after additions and removals.
Here's an example of a set changing order after a lot of values are added and then removed:
>>> s = set([1,6,8])
>>> print(s)
{8, 1, 6}
>>> s.update(range(10,100000))
>>> for v in range(10, 100000):
s.remove(v)
>>> print(s)
{1, 6, 8}
This is implementation dependent though, and so you should not rely upon it.
strToLower's return type should be char*
not char
(or it should return nothing at all, since it doesn't re-allocate the string)
Without using alias.
df1.join(df2, df1.id == df2.id).select(df1["*"],df2["other"])
Running .html files as php stopped working all of a sudden in my .htaccess file.
Godaddy support had me change it to:
AddHandler application/x-httpd-lsphp .html
Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:
@if (!string.IsNullOrWhiteSpace(text))
{
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
<p>@line</p>
}
}
(remove empty entries is optional)
On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
You can use Coil library to load svg. Just add these lines in build.gradle
// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")
Then Add an extension function
fun AppCompatImageView.loadSvg(url: String) {
val imageLoader = ImageLoader.Builder(this.context)
.componentRegistry { add(SvgDecoder([email protected])) }
.build()
val request = ImageRequest.Builder(this.context)
.crossfade(true)
.crossfade(500)
.data(url)
.target(this)
.build()
imageLoader.enqueue(request)
}
Then call this method in your activity or fragment
your_image_view.loadSvg("your_file_name.svg")
There's a better way to handle it using Native MongoDB code in Mongoose.
exports.getUsers = function(req, res, next) {
var usersProjection = {
__v: false,
_id: false
};
User.find({}, usersProjection, function (err, users) {
if (err) return next(err);
res.json(users);
});
}
http://docs.mongodb.org/manual/reference/method/db.collection.find/
Note:
var usersProjection
The list of objects listed here will not be returned / printed.
I think the answer is pretty simple (unless I'm missing something?)
SELECT
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
WHEN col1 > col2 THEN SUM(col3*col4)
ELSE 0
END
You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)
The memory in memcpy
cannot overlap or you risk undefined behaviour, while the memory in memmove
can overlap.
char a[16];
char b[16];
memcpy(a,b,16); // valid
memmove(a,b,16); // Also valid, but slower than memcpy.
memcpy(&a[0], &a[1],10); // Not valid since it overlaps.
memmove(&a[0], &a[1],10); // valid.
Some implementations of memcpy might still work for overlapping inputs but you cannot count of that behaviour. While memmove must allow for overlapping.
/usr/local/ssl/openssl.cnf
A path like this means the program has been compiled with either Cygwin or MSYS. If you must use this openssl
then you will need an interpreter that understands those paths, like Bash, which is provided by Cygwin or MSYS.
Another option would be to download or compile a Windows Native version of openssl
. Using that the program would instead require a path like
C:\Users\Steven\ssl\openssl.cnf
which would be better suited for the Command Prompt.
ALTER USER myuser WITH SUPERUSER;
You can read more at the Documentation
Here it is a simple 8-lines PHP function that converts a number of seconds into a human readable string including number of months for large amounts of seconds:
function seconds2human($ss) {
$s = $ss%60;
$m = floor(($ss%3600)/60);
$h = floor(($ss%86400)/3600);
$d = floor(($ss%2592000)/86400);
$M = floor($ss/2592000);
return "$M months, $d days, $h hours, $m minutes, $s seconds";
}
In my case, I had left over references to classes in a recently removed composer package. In your laravel app, check config/app.php
, particularly the providers
and aliases
properties, for references to the class specified in the error.
I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:
@{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("id", strElementId);
if (!CSSClass.IsEmpty())
{
htmlAttr.Add("class", strCSSClass);
}
}
@* ... *@
@Html.TextBox("somename", "", htmlAttr)
If this way will be useful for you i recommend to define dictionary htmlAttr
in your model so your view doesn't need any @{ }
logic blocks (be more clear).
I have used Guava Sets.difference.
The parameters are sets and not general collections, but a handy way to create sets from any collection (with unique items) is Guava ImmutableSet.copyOf(Iterable).
(I first posted this on a related/dupe question, but I'm copying it here too since I feel it is a good option that is so far missing.)
private void CopyDataTable(DataTable table){
// Create an object variable for the copy.
DataTable copyDataTable;
copyDataTable = table.Copy();
// Insert code to work with the copy.
}
Ajax Submit form with out page refresh by using jquery ajax method first include library jquery.js and jquery-form.js then create form in html:
<form action="postpage.php" method="POST" id="postForm" >
<div id="flash_success"></div>
name:
<input type="text" name="name" />
password:
<input type="password" name="pass" />
Email:
<input type="text" name="email" />
<input type="submit" name="btn" value="Submit" />
</form>
<script>
var options = {
target: '#flash_success', // your response show in this ID
beforeSubmit: callValidationFunction,
success: YourResponseFunction
};
// bind to the form's submit event
jQuery('#postForm').submit(function() {
jQuery(this).ajaxSubmit(options);
return false;
});
});
function callValidationFunction()
{
// validation code for your form HERE
}
function YourResponseFunction(responseText, statusText, xhr, $form)
{
if(responseText=='success')
{
$('#flash_success').html('Your Success Message Here!!!');
$('body,html').animate({scrollTop: 0}, 800);
}else
{
$('#flash_success').html('Error Msg Here');
}
}
</script>
datetime
:':0>8'
format:from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
':0>8'
format:"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
time
:from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
In my case this error message appeared because the package I was trying to install (storm) was not supported for Python 3.
You can solve your problem most concisely with a predicate written using anonymous method syntax:
MyClass found = list.Find(item => item.GetID() == ID);
You need to define the enum outside of the class.
public enum card_suits
{
Clubs,
Hearts,
Spades,
Diamonds
}
public class Card
{
// ...
That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.
In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)
GroupUser.where.not(user_id: me)
In Rails 3.x
GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))
To shorten the length, you could store GroupUser.arel_table
in a variable or if using inside the model GroupUser
itself e.g., in a scope
, you can use arel_table[:user_id]
instead of GroupUser.arel_table[:user_id]
Rails 4.0 syntax credit to @jbearden's answer
Plain JavaScript escaping example:
function escapeHtml(text) {
var div = document.createElement('div');
div.innerText = text;
return div.innerHTML;
}
escapeHtml("<script>alert('hi!');</script>")
// "<script>alert('hi!');</script>"
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
Content in md-dialog-content
is automatically scrollable.
You can manually set the size in the call to MdDialog.open
let dialogRef = dialog.open(MyComponent, {
height: '400px',
width: '600px',
});
Further documentation / examples for scrolling and sizing: https://material.angular.io/components/dialog/overview
Some colors should be determined by your theme. See here for theming docs: https://material.angular.io/guide/theming
If you want to override colors and such, use Elmer's technique of just adding the appropriate css.
Note that you must have the HTML 5 <!DOCTYPE html>
on your page for the size of your dialog to fit the contents correctly ( https://github.com/angular/material2/issues/2351 )
CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.
You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.
See MSDN documentation for InitialCatalog Property:
Gets or sets the name of the database associated with the connection...
This property corresponds to the "Initial Catalog" and "database" keys within the connection string...
For non-preemptive system,
waitingTime = startTime - arrivalTime
turnaroundTime = burstTime + waitingTime = finishTime- arrivalTime
startTime = Time at which the process started executing
finishTime = Time at which the process finished executing
You can keep track of the current time elapsed in the system(timeElapsed
). Assign all processors to a process in the beginning, and execute until the shortest process is done executing. Then assign this processor which is free to the next process in the queue. Do this until the queue is empty and all processes are done executing. Also, whenever a process starts executing, recored its startTime
, when finishes, record its finishTime
(both same as timeElapsed
). That way you can calculate what you need.
The only way to have multiple, separately accessible functions in a single file is to define STATIC METHODS using object-oriented programming. You'd access the function as myClass.static1()
, myClass.static2()
etc.
OOP functionality is only officially supported since R2008a, so unless you want to use the old, undocumented OOP syntax, the answer for you is no, as explained by @gnovice.
EDIT
One more way to define multiple functions inside a file that are accessible from the outside is to create a function that returns multiple function handles. In other words, you'd call your defining function as [fun1,fun2,fun3]=defineMyFunctions
, after which you could use out1=fun1(inputs)
etc.
They are not. They're exactly the same.
However, some people say that parameters are placeholders in method signatures:
public void doMethod(String s, int i) {
..
}
String s and int i are sometimes said to be parameters. The arguments are the actual values/references:
myClassReference.doMethod("someString", 25);
"someString" and 25 are sometimes said to be the arguments.
Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
If InStr(myString, "A") > 0 Then
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
Left(oldStr, InStr(oldStr, "A"))
What I usually do, is to store the full string into a variable first, like so:
<?php
$img_id = 'data:image/png;base64,iVBORw0KGgoAAAAAAAAyCAY...';
?>
Then, where I want either JS to do something with that variable:
<script type="text/javascript">
document.getElementById("img_id").backgroundImage="url('<?php echo $img_id; ?>')";
</script>
You could reference the same variable via PHP directly using something like:
<img src="<?php echo $img_id; ?>">
Works for me ;)
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
This code will return "browser" and "browserVersion"
Works on 95% of 80+ browsers
var geckobrowsers;
var browser = "";
var browserVersion = 0;
var agent = navigator.userAgent + " ";
if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("like Gecko") != -1){
geckobrowsers = agent.substring(agent.indexOf("like Gecko")+10).substring(agent.substring(agent.indexOf("like Gecko")+10).indexOf(") ")+2).replace("LG Browser", "LGBrowser").replace("360SE", "360SE/");
for(i = 0; i < 1; i++){
geckobrowsers = geckobrowsers.replace(geckobrowsers.substring(geckobrowsers.indexOf("("), geckobrowsers.indexOf(")")+1), "");
}
geckobrowsers = geckobrowsers.split(" ");
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("/") == -1)geckobrowsers[i] = "Chrome";
if(geckobrowsers[i].indexOf("/") != -1)geckobrowsers[i] = geckobrowsers[i].substring(0, geckobrowsers[i].indexOf("/"));
}
if(geckobrowsers.length < 4){
browser = geckobrowsers[0];
} else {
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("Chrome") == -1 && geckobrowsers[i].indexOf("Safari") == -1 && geckobrowsers[i].indexOf("Mobile") == -1 && geckobrowsers[i].indexOf("Version") == -1)browser = geckobrowsers[i];
}
}
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Gecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).substring(0, agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Clecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).substring(0, agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0"){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(";"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 == agent.length-1){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ")[agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ").length-1];
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 != agent.length-1){
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") != -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf("/"));
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") == -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf(" "));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(0, 6) == "Opera/"){
browser = "Opera";
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") != -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(";"));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") == -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(")"));
} else if(agent.substring(0, agent.indexOf("/")) != "Mozilla" && agent.substring(0, agent.indexOf("/")) != "Opera"){
browser = agent.substring(0, agent.indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else {
browser = agent;
}
alert(browser + " v" + browserVersion);
My solution, only need to call this method.
public static void dropColumn(SQLiteDatabase db, String tableName, String[] columnsToRemove) throws java.sql.SQLException {
List<String> updatedTableColumns = getTableColumns(db, tableName);
updatedTableColumns.removeAll(Arrays.asList(columnsToRemove));
String columnsSeperated = TextUtils.join(",", updatedTableColumns);
db.execSQL("ALTER TABLE " + tableName + " RENAME TO " + tableName + "_old;");
db.execSQL("CREATE TABLE " + tableName + " (" + columnsSeperated + ");");
db.execSQL("INSERT INTO " + tableName + "(" + columnsSeperated + ") SELECT "
+ columnsSeperated + " FROM " + tableName + "_old;");
db.execSQL("DROP TABLE " + tableName + "_old;");
}
And auxiliary method to get the columns:
public static List<String> getTableColumns(SQLiteDatabase db, String tableName) {
ArrayList<String> columns = new ArrayList<>();
String cmd = "pragma table_info(" + tableName + ");";
Cursor cur = db.rawQuery(cmd, null);
while (cur.moveToNext()) {
columns.add(cur.getString(cur.getColumnIndex("name")));
}
cur.close();
return columns;
}