I had same issue, with Latest Spring 4.1.1 onwards you need to add following jars to pom.xml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
also make sure you have following jar:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
406 Spring MVC Json, not acceptable according to the request "accept" headers
Without commit messages, only the hash:
git log --pretty=oneline | awk '{print $1}'
SELECT pid FROM planets WHERE userid is null;
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
You can insert object items to an array as this
let obj = {_x000D_
'1st': {_x000D_
name: 'stackoverflow'_x000D_
},_x000D_
'2nd': {_x000D_
name: 'stackexchange'_x000D_
}_x000D_
};_x000D_
_x000D_
let wholeArray = Object.keys(obj).map(key => obj[key]);_x000D_
_x000D_
console.log(wholeArray);
_x000D_
you should give permission on your db
grant execute on (packageName or tableName) to user;
The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.
This actually works for me:
background-color: #6DB3F2;
background-image: url('images/checked.png');
You can also drop a solid shadow and set the background image:
background-image: url('images/checked.png');
box-shadow: inset 0 0 100% #6DB3F2;
If the first option is not working for some reason and you don't want to use the box shadow you can always use a pseudo element for the image without any extra HTML:
.btn{
position: relative;
background-color: #6DB3F2;
}
.btn:before{
content: "";
display: block;
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
background-image: url('images/checked.png');
}
That's working for me, in my country on Saturday and Sunday are non-working days.
For me is important the time of @StartDate and @EndDate.
CREATE FUNCTION [dbo].[fnGetCountWorkingBusinessDays]
(
@StartDate as DATETIME,
@EndDate as DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @res int
SET @StartDate = CASE
WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN DATEADD(dd, 2, DATEDIFF(dd, 0, @StartDate))
WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN DATEADD(dd, 1, DATEDIFF(dd, 0, @StartDate))
ELSE @StartDate END
SET @EndDate = CASE
WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN DATEADD(dd, 0, DATEDIFF(dd, 0, @EndDate))
WHEN DATENAME(dw, @EndDate) = 'Sunday' THEN DATEADD(dd, -1, DATEDIFF(dd, 0, @EndDate))
ELSE @EndDate END
SET @res =
(DATEDIFF(hour, @StartDate, @EndDate) / 24)
- (DATEDIFF(wk, @StartDate, @EndDate) * 2)
SET @res = CASE WHEN @res < 0 THEN 0 ELSE @res END
RETURN @res
END
GO
The most portable way to get the hostname of the current computer in Java is as follows:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class getHostName {
public static void main(String[] args) throws UnknownHostException {
InetAddress iAddress = InetAddress.getLocalHost();
String hostName = iAddress.getHostName();
//To get the Canonical host name
String canonicalHostName = iAddress.getCanonicalHostName();
System.out.println("HostName:" + hostName);
System.out.println("Canonical Host Name:" + canonicalHostName);
}
}
The easiest way to freeze the UI would be to make the AJAX call synchronous.
Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.
Based on NeverHopeless's elegant solution:
private static readonly KeyValuePair<long, string>[] Thresholds =
{
// new KeyValuePair<long, string>(0, " Bytes"), // Don't devide by Zero!
new KeyValuePair<long, string>(1, " Byte"),
new KeyValuePair<long, string>(2, " Bytes"),
new KeyValuePair<long, string>(1024, " KB"),
new KeyValuePair<long, string>(1048576, " MB"), // Note: 1024 ^ 2 = 1026 (xor operator)
new KeyValuePair<long, string>(1073741824, " GB"),
new KeyValuePair<long, string>(1099511627776, " TB"),
new KeyValuePair<long, string>(1125899906842620, " PB"),
new KeyValuePair<long, string>(1152921504606850000, " EB"),
// These don't fit into a int64
// new KeyValuePair<long, string>(1180591620717410000000, " ZB"),
// new KeyValuePair<long, string>(1208925819614630000000000, " YB")
};
/// <summary>
/// Returns x Bytes, kB, Mb, etc...
/// </summary>
public static string ToByteSize(this long value)
{
if (value == 0) return "0 Bytes"; // zero is plural
for (int t = Thresholds.Length - 1; t > 0; t--)
if (value >= Thresholds[t].Key) return ((double)value / Thresholds[t].Key).ToString("0.00") + Thresholds[t].Value;
return "-" + ToByteSize(-value); // negative bytes (common case optimised to the end of this routine)
}
Maybe there are excessive comments, but I tend to leave them to prevent myself from making the same mistakes over on future visits...
Helping you further, where Mick Sharpe left you:
It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory
log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)
Think of n as infinitly big. What is infinite minus one? or minus two? etc.
log(inf) + log(inf) + log(inf) + ... = inf * log(inf)
And then think of inf as n.
Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.
Try with javascript function like this
Html:
<a href="javascript:void(0)" onclick="open_win()">Target</a>
Javascript:
<script>
function open_win()
{
window.open("https://www.google.co.in/");
}
</script>
I usually put an event on the view model when I need to do this and then hook it up to the Window.Close()
when binding the view model to the window
public class LoginViewModel
{
public event EventHandler OnRequestClose;
private void Login()
{
// Login logic here
OnRequestClose(this, new EventArgs());
}
}
And when creating the login window
var vm = new LoginViewModel();
var loginWindow = new LoginWindow
{
DataContext = vm
};
vm.OnRequestClose += (s, e) => loginWindow.Close();
loginWindow.ShowDialog();
For data import scripts, to replace "IF NOT EXISTS", in a way, there's a slightly awkward formulation that nevertheless works:
DO
$do$
BEGIN
PERFORM id
FROM whatever_table;
IF NOT FOUND THEN
-- INSERT stuff
END IF;
END
$do$;
Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',// leave it for port 3306
'username' => 'yourUserhere',
'password' => 'yourPassword',
'database' => 'yourDatabase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Or with the default settings:
$db['default'] = array(
'dsn' => '',
'hostname' => '127.0.0.1:8889',// leave it for port 8889
'username' => 'yourUserhere',
'password' => 'yourPassword',
'database' => 'yourDatabase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
As no answer is complete for the current way to solve this problem, I try to give instructions for a complete solution. Please comment if something is missing or could be done better.
First, there exist some libraries that want to solve the problem but they all seem outdated or are missing some features:
Further I think writing a library might not be a good/easy way to solve this problem because there is not very much to do, and what has to be done is rather changing existing code than using something completely decoupled. Therefore I composed the following instructions that should be complete.
My solution is mainly based on https://github.com/gunhansancar/ChangeLanguageExample (as already linked to by localhost). It is the best code I found to orientate at. Some remarks:
updateViews()
in each Activity to manually update all strings after changing locale (using the usual getString(id)
) which is not necessary in the approach shown belowI changed it a bit, decoupling the part which persists the chosen locale (as one might want to do that separately, as suggested below).
The solution consists of the following two steps:
Use the class LocaleHelper
, based on gunhansancar's LocaleHelper:
ListPreference
in a PreferenceFragment
with the available languages (has to be maintained when languages should be added later)import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;
import java.util.Locale;
import mypackage.SettingsFragment;
/**
* Manages setting of the app's locale.
*/
public class LocaleHelper {
public static Context onAttach(Context context) {
String locale = getPersistedLocale(context);
return setLocale(context, locale);
}
public static String getPersistedLocale(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SettingsFragment.KEY_PREF_LANGUAGE, "");
}
/**
* Set the app's locale to the one specified by the given String.
*
* @param context
* @param localeSpec a locale specification as used for Android resources (NOTE: does not
* support country and variant codes so far); the special string "system" sets
* the locale to the locale specified in system settings
* @return
*/
public static Context setLocale(Context context, String localeSpec) {
Locale locale;
if (localeSpec.equals("system")) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
locale = Resources.getSystem().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
locale = Resources.getSystem().getConfiguration().locale;
}
} else {
locale = new Locale(localeSpec);
}
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, locale);
} else {
return updateResourcesLegacy(context, locale);
}
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, Locale locale) {
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, Locale locale) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
Create a SettingsFragment
like the following:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import mypackage.LocaleHelper;
import mypackage.R;
/**
* Fragment containing the app's main settings.
*/
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_LANGUAGE = "pref_key_language";
public SettingsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_settings, container, false);
return view;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
switch (key) {
case KEY_PREF_LANGUAGE:
LocaleHelper.setLocale(getContext(), PreferenceManager.getDefaultSharedPreferences(getContext()).getString(key, ""));
getActivity().recreate(); // necessary here because this Activity is currently running and thus a recreate() in onResume() would be too late
break;
}
}
@Override
public void onResume() {
super.onResume();
// documentation requires that a reference to the listener is kept as long as it may be called, which is the case as it can only be called from this Fragment
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
Create a resource locales.xml
listing all locales with available translations in the following way (list of locale codes):
<!-- Lists available locales used for setting the locale manually.
For now only language codes (locale codes without country and variant) are supported.
Has to be in sync with "settings_language_values" in strings.xml (the entries must correspond).
-->
<resources>
<string name="system_locale" translatable="false">system</string>
<string name="default_locale" translatable="false"></string>
<string-array name="locales">
<item>@string/system_locale</item> <!-- system setting -->
<item>@string/default_locale</item> <!-- default locale -->
<item>de</item>
</string-array>
</resources>
In your PreferenceScreen
you can use the following section to let the user select the available languages:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="@string/preferences_category_general">
<ListPreference
android:key="pref_key_language"
android:title="@string/preferences_language"
android:dialogTitle="@string/preferences_language"
android:entries="@array/settings_language_values"
android:entryValues="@array/locales"
android:defaultValue="@string/system_locale"
android:summary="%s">
</ListPreference>
</PreferenceCategory>
</PreferenceScreen>
which uses the following strings from strings.xml
:
<string name="preferences_category_general">General</string>
<string name="preferences_language">Language</string>
<!-- NOTE: Has to correspond to array "locales" in locales.xml (elements in same orderwith) -->
<string-array name="settings_language_values">
<item>Default (System setting)</item>
<item>English</item>
<item>German</item>
</string-array>
Now setup each Activity to use the custom locale set. The easiest way to accomplish this is to have a common base class for all activities with the following code (where the important code is in attachBaseContext(Context base)
and onResume()
):
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import mypackage.LocaleHelper;
import mypackage.R;
/**
* {@link AppCompatActivity} with main menu in the action bar. Automatically recreates
* the activity when the locale has changed.
*/
public class MenuAppCompatActivity extends AppCompatActivity {
private String initialLocale;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialLocale = LocaleHelper.getPersistedLocale(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleHelper.onAttach(base));
}
@Override
protected void onResume() {
super.onResume();
if (initialLocale != null && !initialLocale.equals(LocaleHelper.getPersistedLocale(this))) {
recreate();
}
}
}
What it does is
attachBaseContext(Context base)
to use the locale previously persisted with LocaleHelper
Recreating an Activity does not update the title of the ActionBar (as already observed here: https://github.com/gunhansancar/ChangeLanguageExample/issues/1).
setTitle(R.string.mytitle)
in the onCreate()
method of each activity.It lets the user chose the system default locale, as well as the default locale of the app (which can be named, in this case "English").
Only language codes, no region (country) and variant codes (like fr-rCA
) are supported so far. To support full locale specifications, a parser similar to that in the Android-Languages library can be used (which supports region but no variant codes).
After installing weblogic and forms server on a Linux machine we met some problems initializing sqlplus
and tnsping
. We altered the bash_profile
in a way that the forms_home acts as the oracle home. It works fine, both commands
(sqlplus and tnsping) are executable for user oracle
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export JAVA_HOME=/mnt/software/java/jdk1.7.0_71
export ORACLE_HOME=/oracle/Middleware/Oracle_FRHome1
export PATH=$PATH:$JAVA_HOME/bin:$ORACLE_HOME/bin
export LD_LIBRARY_PATH=/oracle/Middleware/Oracle_FRHome1/lib
export FORMS_PATH=$FORMS_PATH:/oracle/Middleware/Oracle_FRHome1/forms:/oracle/Middleware/asinst_1/FormsComponent/forms:/appl/myapp:/home/oracle/myapp
myInt.ToString("D4");
I had a similar problem with eslint saying it was '..not validating any files yet', but nothing was reported in the VS Code problems console. However after upgrading VS Code to the latest version (1.32.1) and restarting, eslint started working.
# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1
#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763
#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237
#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)
#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)
#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)
Why all these complicated answers with various shell scripts? Use htop, it automatically changes the sizes and you can select which info you want shown and it works in the terminal, so it does not require a desktop. Example: htop -d8
The above answers will work, but just in case you want a different approach, try classname: https://github.com/JedWatson/classnames
You can get all the contact all those which have no number and all those which have no name from this piece of code
public void readContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY + " ASC");
ContactCount = cur.getCount();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phone = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the phone number
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
}
if (phone == "" || name == "" || name.equals(phone)) {
if (phone.equals(""))
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
if (name.equals("") || name.equals(phone))
getAllContact.add(new MissingPhoneModelClass(phone, "No Name", id));
} else {
if(TextUtils.equals(phone,null)){
getAllContact.add(new MissingPhoneModelClass("No Number", name, id));
}
else {
getAllContact.add(new MissingPhoneModelClass(phone, name, id));
}
}
}
}
}
One thing can be done you have to give the permission in the manifest for contact READ and WRITE After that you can create the model class for the list which can be use to add all the contact here is the model class
public class PhoneModelClass {
private String number;
private String name;
private String id;
private String rawId;
public PhoneModelClass(String number, String name, String id, String rawId) {
this.number = number;
this.name = name;
this.id = id;
this.rawId = rawId;
}
public PhoneModelClass(String number, String name, String id) {
this.number = number;
this.name = name;
this.id = id;
}
public String getRawId() {
return rawId;
}
public void setRawId(String rawId) {
this.rawId = rawId;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Enjoy :)
After a lot of fiddling, got it working (only tested in Webkit) using:
font-family: "HelveticaNeue-CondensedBold";
font-stretch was dropped between CSS2 and 2.1, though is back in CSS3, but is only supported in IE9 (never thought I'd be able to say that about any CSS prop!)
This works because I'm using the postscript name (find the font in Font Book, hit cmd+I), which is non-standard behaviour. It's probably worth using:
font-family: "HelveticaNeue-CondensedBold", "Helvetica Neue";
As a fallback, else other browsers might default to serif if they can't work it out.
I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
The same idea as described by others works in React as follow:
<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>
One solution is to implement an OnScrollListener
and make changes (like adding items, etc.) to the ListAdapter
at a convenient state in its onScroll
method.
The following ListActivity
shows a list of integers, starting with 40, adding items when the user scrolls to the end of the list.
public class Test extends ListActivity implements OnScrollListener {
Aleph0 adapter = new Aleph0();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(adapter);
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view,
int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
if(loadMore) {
adapter.count += visibleCount; // or any other amount
adapter.notifyDataSetChanged();
}
}
public void onScrollStateChanged(AbsListView v, int s) { }
class Aleph0 extends BaseAdapter {
int count = 40; /* starting amount */
public int getCount() { return count; }
public Object getItem(int pos) { return pos; }
public long getItemId(int pos) { return pos; }
public View getView(int pos, View v, ViewGroup p) {
TextView view = new TextView(Test.this);
view.setText("entry " + pos);
return view;
}
}
}
You should obviously use separate threads for long running actions (like loading web-data) and might want to indicate progress in the last list item (like the market or gmail apps do).
Another way to achieve the same goal: flex boxes. Make the container a column flex box, and then you have all freedom to allow some elements to have fixed-size (default behavior) or to fill-up/shrink-down to the container space (with flex-grow:1 and flex-shrink:1).
#wrap {
display:flex;
flex-direction:column;
}
.extendOrShrink {
flex-shrink:1;
flex-grow:1;
overflow:auto;
}
See https://jsfiddle.net/2Lmodwxk/ (try to extend or reduce the window to notice the effect)
Note: you may also use the shorthand property:
flex:1 1 auto;
As noticed in comments start with sent_tokenize(), because word_tokenize() works only on a single sentence. You can filter out punctuation with filter(). And if you have an unicode strings make sure that is a unicode object (not a 'str' encoded with some encoding like 'utf-8').
from nltk.tokenize import word_tokenize, sent_tokenize
text = '''It is a blue, small, and extraordinary ball. Like no other'''
tokens = [word for sent in sent_tokenize(text) for word in word_tokenize(sent)]
print filter(lambda word: word not in ',-', tokens)
Not quite a solution to the question but I thought it was worth noting the the approach I use when I have a long-living branch:
At the same time I create the branch, I also create a tag with the same name but with an -init
suffix, for example feature-branch
and feature-branch-init
.
(It is kind of bizarre that this is such a hard question to answer!)
You are specifying .fixedbutton
in your CSS (a class) and specifying the id
on the element itself.
Change your CSS to the following, which will select the id
fixedbutton
#fixedbutton {
position: fixed;
bottom: 0px;
right: 0px;
}
A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.
If T
is a type for which lteq
is defined, you can define InfiniteOr<T>
with lteq
something like this:
class InfiniteOr with type parameter T:
field the_T of type null-or-an-actual-T
isInfinite()
return this.the_T == null
getFinite():
assert(!isInfinite());
return this.the_T
lteq(that)
if that.isInfinite()
return true
if this.isInfinite()
return false
return this.getFinite().lteq(that.getFinite())
I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.
The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null
to represent infinity here, since that seems the most straightforward in Java.
If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.
There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq
) I think it's simpler to look at right-hand-side infinity first. I note that lteq
is not commutative, but add
and mul
are; maybe that is relevant.
Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.
Since the question is so popular, it may be useful to add on what to do if you want to control the type property name and its value.
The long way is to write custom JsonConverter
s to handle (de)serialization by manually checking and setting the type property.
A simpler way is to use JsonSubTypes, which handles all the boilerplate via attributes:
[JsonConverter(typeof(JsonSubtypes), "Sound")]
[JsonSubtypes.KnownSubType(typeof(Dog), "Bark")]
[JsonSubtypes.KnownSubType(typeof(Cat), "Meow")]
public class Animal
{
public virtual string Sound { get; }
public string Color { get; set; }
}
public class Dog : Animal
{
public override string Sound { get; } = "Bark";
public string Breed { get; set; }
}
public class Cat : Animal
{
public override string Sound { get; } = "Meow";
public bool Declawed { get; set; }
}
I was also facing the same issue for 2 days but now finally it is working.
Step 1 : create a php script file with this content.
<?php
echo 'username : ' . `whoami`;
phpinfo();
?>
note down the username. note down open_basedir under core section of phpinfo. also note down upload_tmp_dir under core section of phpinfo.
Here two things are important , see if upload_tmp_dir value is inside one of open_basedir directory. ( php can not upload files outside open_basedir directory ).
Step 2 : Open terminal with root access and go to upload_tmp_dir location. ( In my case "/home/admin/tmp". )
=> cd /home/admin/tmp
But it was not found in my case so I created it and added chown for php user which I get in step 1 ( In my case "admin" ).
=> mkdir /home/admin/tmp
=> chown admin /home/admin/tmp
That is all you have to do to fix the file upload problem.
The following is my solution wrapped in a function that also throws errors to manage a couple of problems with object scope and all types of possible data types passed to the function.
Here's my fiddle used to examine this problem (source)
var jill = [0];
var jack;
//"Uncaught ReferenceError: jack is not defined"
//if (typeof jack === 'undefined' || jack === null) {
//if (jack) {
//if (jack in window) {
//if (window.hasOwnP=roperty('jack')){
//if (jack in window){
function isemptyArray (arraynamed){
//cam also check argument length
if (arguments.length === 0) {
throw "No argument supplied";
}
//console.log(arguments.length, "number of arguments found");
if (typeof arraynamed !== "undefined" && arraynamed !== null) {
//console.log("found arraynamed has a value");
if ((arraynamed instanceof Array) === true){
//console.log("I'm an array");
if (arraynamed.length === 0) {
//console.log ("I'm empty");
return true;
} else {
return false;
}//end length check
} else {
//bad type
throw "Argument is not an array";
} //end type check
} else {
//bad argument
throw "Argument is invalid, check initialization";;
}//end argument check
}
try {
console.log(isemptyArray(jill));
} catch (e) {
console.log ("error caught:",e);
}
This working for me:
window.opener.location.reload()
window.close();
In this case Current tab will close and parent tab will refresh.
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
This will get the name in the ng-repeat to come up seperate in the form validation.
<td>
<input ng-model="r.QTY" class="span1" name="{{'QTY' + $index}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
</td>
But I had trouble getting it to look up in its validation message so I had to use an ng-init to get it to resolve a variable as the object key.
<td>
<input ng-model="r.QTY" class="span1" ng-init="name = 'QTY' + $index" name="{{name}}" ng-pattern="/^[\d]*\.?[\d]*$/" required/>
<span class="alert-error" ng-show="form[name].$error.pattern"><strong>Requires a number.</strong></span>
<span class="alert-error" ng-show="form[name].$error.required"><strong>*Required</strong></span>
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
Take a look at the server logs!
I had been with this for hours. The awful Tomcat servlet is not very helpful neither but if you can see the stacktrace that should be enough.
For instance, I read the following error message there:
As you can see, the message was pretty clear and easy to fix :-)
One possibility is when installed sql server data tools Bi, while sql server was already set up.
Solution:- 1.Just Repair the sql server with the set up instance
if solution does not work , than its worth your time meddling with services.msc
var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text
this is just a modification of Karsten's code
function include_all_php($folder){
foreach (glob("{$folder}/*.php") as $filename)
{
include $filename;
}
}
include_all_php("my_classes");
For those using force directed graphs in D3 v4/v5, the size
method doesn't exist any more. Something like the following worked for me (based on this github issue):
simulation
.force("center", d3.forceCenter(width / 2, height / 2))
.force("x", d3.forceX(width / 2))
.force("y", d3.forceY(height / 2))
.alpha(0.1).restart();
Just add another join:
SELECT dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id,
images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
Easiest way:
param_a = 1
param_b = 2
result = param_a === param_b ? 'Same!' : 'Not same!'
since param_a
is not equal to param_b
then the result
's value will be Not same!
SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;
Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:
SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DuplicateWord {
public static void main(String[] args) {
String para = "this is what it is this is what it can be";
List < String > paraList = new ArrayList < String > ();
paraList = Arrays.asList(para.split(" "));
System.out.println(paraList);
int size = paraList.size();
int i = 0;
Map < String, Integer > duplicatCountMap = new HashMap < String, Integer > ();
for (int j = 0; size > j; j++) {
int count = 0;
for (i = 0; size > i; i++) {
if (paraList.get(j).equals(paraList.get(i))) {
count++;
duplicatCountMap.put(paraList.get(j), count);
}
}
}
System.out.println(duplicatCountMap);
List < Integer > myCountList = new ArrayList < > ();
Set < String > myValueSet = new HashSet < > ();
for (Map.Entry < String, Integer > entry: duplicatCountMap.entrySet()) {
myCountList.add(entry.getValue());
myValueSet.add(entry.getKey());
}
System.out.println(myCountList);
System.out.println(myValueSet);
}
}
Input: this is what it is this is what it can be
Output:
[this, is, what, it, is, this, is, what, it, can, be]
{can=1, what=2, be=1, this=2, is=3, it=2}
[1, 2, 1, 2, 3, 2]
[can, what, be, this, is, it]
You can do it in Python 2.7+ with python-dateutil
(which is insalled on Mac by default):
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> datetime.now(tzlocal()).isoformat()
'2016-10-22T12:45:45.353489-03:00'
Or you if you want to convert from an existed stored string:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>> from dateutil.parser import parse
>>> parse("2016-10-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-10-21T16:33:27.696173-03:00' <-- Atlantic Daylight Time (ADT)
>>> parse("2016-01-21T16:33:27.696173").replace(tzinfo=tzlocal()).isoformat()
'2016-01-21T16:33:27.696173-04:00' <-- Atlantic Standard Time (AST)
The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:
explorer.exe "Windows PowerShell.lnk"
The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell
When a method only takes a reference type as a parameter (say a generic method constrained to be a class via the new
constraint), you will not be able to pass a reference type to it and have to box it.
This is also true for any methods that take object
as a parameter - this will have to be a reference type.
You don't need a IF statement at all.
WHERE
(IsNumeric(@OrderNumber) = 1 AND OrderNumber = @OrderNumber)
OR (IsNumeric(@OrderNumber) = 0 AND OrderNumber LIKE '%' + @OrderNumber + '%')
yes you can ... you just need to know the exact package name of the application:
And you can create the intent like this
Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
// The application exists
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage(application);
shareIntent.putExtra(android.content.Intent.EXTRA_TITLE, title);
shareIntent.putExtra(Intent.EXTRA_TEXT, description);
// Start the specific social application
context.startActivity(shareIntent);
} else {
// The application does not exist
// Open GooglePlay or use the default system picker
}
For Xamarin Users:
[Activity(MainLauncher = true,
ScreenOrientation = ScreenOrientation.Portrait,
WindowSoftInputMode = SoftInput.StateHidden)] //SoftInput.StateHidden - disables keyboard autopop
as text:
=CONCATENATE(TEXT(cell;"d");" days ";TEXT(cell;"t");" hours ";MID(TEXT(cell;"hh:mm:ss");4;2);" minutes ";TEXT(cell;"s");" seconds")
With jQuery you can do this by $.param
$.param({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })
// -> "action=ship&order_id=123&fees%5B%5D=f1&fees%5B%5D=f2&label=a+demo"
This is much easier if you're using jQuery scrollTop:
$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
The Simplest approach:
String[] stringArray = {"Hey", "Hi", "Hello"};
List<String> list = Arrays.asList(stringArray);
msbuild "C:\path to solution\project.sln"
Changing into MyISAM is not the solution. For innodb following worked for me.
set followings on my.cnf
innodb_strict_mode=0
I think you need to actually download and install XAMPP with the desired PHP version. I dont think you can just upgrade the components of XAMPP individually unless there is a facility provided for this within XAMPP itself.
The declaration and definition of insertLike
are different
In your header file:
void insertLike(const char sentence[], const int lengthTo, const int length,
const char writeTo[]);
In your 'function file':
void insertLike(const char sentence[], const int lengthTo, const int length,
char writeTo[]);
C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.
In this case, insertLike
which takes const char*
as its fourth parameter and insertLike
which takes char *
as its fourth parameter are different functions.
Enter in sqlplus (you'll see the version number)
# su - oracle
oracle# sqlplus
OR
echo $ORAHOME
Will give you the path where Oracle installed and path will include version number.
OR
Connect to Oracle DB and run
select * from v$version where banner like 'oracle%';
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
I came across these links:
http://mail.openjdk.java.net/pipermail/core-libs-dev/2009-May/001689.html
http://www.nabble.com/Review-request-for-5049299-td23667680.html
Seems to be a bug. Usage of a spawn() trick instead of the plain fork()/exec() is advised.
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
@Patrick's answer is a good idea, and deserves more credit!. You can have as many data items as you want, they are all separated, and can be used client side if necessary.
They can also be added declaratively rather than in code. I just did this for a GridView like this:
<asp:TemplateField HeaderText="Remind">
<ItemTemplate>
<asp:ImageButton ID="btnEmail"
data-rider-name="<%# ((Result)((GridViewRow) Container).DataItem).Rider %>"
data-rider-email="<%# ((Result)((GridViewRow) Container).DataItem).RiderEmail %>"
CommandName="Email" runat="server" ImageAlign="AbsMiddle" ImageUrl="~/images/email.gif" />
</ItemTemplate>
</asp:TemplateField>
In the RowCommand, you do this:
void gvMyView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Email")
{
var btnSender = (ImageButton)e.CommandSource;
var riderName = btnSender.Attributes["data-rider-name"];
var riderEmail = btnSender.Attributes["data-rider-email"];
// Do something here
}
}
So much cleaner than hacking all the values together with delimiters and unpacking again at the end.
Don't forget to test/clean any data you get back from the page, in case it's been tampered with!
your initial request is "I have a large PDF file that is a floor map for a building. "
I am afraid to tell you this might be harder than you guess.
Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.
Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).
see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163
Use gv$session for RAC, if you want get the total number of session across the cluster.
It's an X(HT)ML thing. When you use symbols like <
and >
within the JavaScript, e.g. for comparing two integers, this would have to be parsed like XML, thus they would mark as a beginning or end of a tag.
The CDATA means that the following lines (everything up unto the ]]>
is not XML and thus should not be parsed that way.
System.IO.File.ReadLines()
is perfect for this scenario. It returns all the lines of a file, but lets you begin iterating over the lines immediately which means it does not have to store the entire contents in memory.
Requires .NET 4.0 or higher.
foreach ($line in [System.IO.File]::ReadLines($filename)) {
# do something with $line
}
diplay: flex;
for it's container and margin:auto;
for it's item works perfect.
NOTE: You have to setup the width
and height
to see the effect.
#container{_x000D_
width: 100%; /*width needs to be setup*/_x000D_
height: 150px; /*height needs to be setup*/_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
margin: auto; /*These will make the item in center*/_x000D_
background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="item">CENTER</div>_x000D_
</div>
_x000D_
Both --assume-unchanged and --skip-worktree are NOT A CORRECT WAY to ignore files locally... Kindly check this answer and the notes in the documentation of git update-index. Files that for any reason keep changing frequently (and/or change from a clone to another) and their changes should not be committed, then these files SHOULD NOT be tracked in the first place.
However, the are two proper ways to ignore files locally (both work with untracked files). Either to put files names in .git/info/exclude file which is the local alternative of .gitignore but specific to the current clone. Or to use a global .gitignore (which should be properly used only for common auxiliary files e.g. pyz, pycache, etc) and the file will be ignored in any git repo in your machine.
To make the above as kind of automated (adding to exclude or global .gitignore), you can use the following commands (add to your bash-profile):
.git/info/exclude
~/.gitignore
Linux
alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
GITFILETOUNIGNORE=${1//\//\\\/}
sed -i "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
unset GITFILETOUNIGNORE
}
MacOS (you need the .bak for sed
inplace modifications (i.e. you are forced to add a file extension to inplace sed. i.e. make a backup before replacing something), therefore to delete the .bak file I added rm filename.bak)
alias git-ignore='echo $1 >> ##FILE-NAME##'
alias git-show-ignored='cat ##FILE-NAME##'
git-unignore(){
GITFILETOUNIGNORE=${1//\//\\\/}
sed -i.bak "/$GITFILETOUNIGNORE/d" ##FILE-NAME##
rm ##FILE-NAME##.bak
unset GITFILETOUNIGNORE
}
Then you can do:
git-ignore example_file.txt
git-unignore example_file.txt
UPDATE:
You'll also want to goto Security -> Server Roles
, and for public
check the permissions for TSQL Default TCP/TSQL Default VIA/TSQL Local Machine/TSQL Named Pipes
and remove the connect
permission
using an invalid/null pointer? Overrunning the bounds of an array? Kindof hard to be specific without any sample code.
Essentially, you are attempting to access memory that doesn't belong to your program, so the OS kills it.
use dateObj.toLocaleString([locales[, options]])
Option 1 - Using locales
var date = new Date();
console.log(date.toLocaleString('en-US'));
Option 2 - Using options
var options = { hour12: true };
console.log(date.toLocaleString('en-GB', options));
Note: supported on all browsers but safari atm
One more jQuery solution
For a single stylesheet with id "css" try this:
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:
var reloadCSS = function() {
$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};
Use layout width in the button like android:layout_width="75dp"
If you came across the error when tried to generate a jks file (keystore), so try adding
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool
before running the command, like so:
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
You can FAKE transitions between gradients, using transitions in the opacity of a few stacked gradients, as described in a few of the answers here:
CSS3 animation with gradients.
You can also transition the position instead, as described here:
CSS3 gradient transition with background-position.
Some more techniques here:
Slightly unrelated to your problem, so here's one for Google.
If you didn't mysqldump the SQL, it might be that your SQL is broken.
I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.
That's a fantastic error message to get for a runaway string, thanks for that MySQL!
You can use the overflow property
style="overflow: scroll ;max-height: 250px; width: 50%;"
Here's a complete working example based on your testing. Compare it to what you have currently to figure out where you are going wrong.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(1000).fadeOut();
});
</script>
</head>
<body>
<div id=deletesuccess > hiiiiiiiiiii </div>
</body>
</html>
You can use Django's built-in validators—
from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator
class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm
since the forms will do that automatically.
Yes you can upload your git repo from vs code. You have to get in the projects working directory and type git init in the terminal. Then add the files to your repository like you do with regular git commits.
In order to kill use:
killall -9 /usr/bin/node
To reload use:
killall -12 /usr/bin/node
You could do this with maps:
Map<String, String> fileToImg:
List<String> fileList = new ArrayList(fileToImg.keySet());
Collections.shuffle(fileList);
for(String item: fileList) {
fileToImf.get(item);
}
This will iterate through the images in the random order.
All the answers above are really good but I needed a way to type as little as possible in the terminal so I created a gem for that. You can install the gem only once and run the command 'shutup' every time you wanna kill the Rails process (while being in the current folder).
gem install shutup
then go in the current folder of your rails project and run
shutup
# this will kill the Rails process currently running
You can use the command 'shutup' every time you want
DICLAIMER: I am the creator of this gem
NOTE: if you are using rvm install the gem globally
rvm @global do gem install shutup
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.
You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.
If you make the relationships bidirectional, you should thus have
class User {
@OneToMany(mappedBy = "user")
private Set<UserService> userServices = new HashSet<UserService>();
}
class UserService {
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "service_code")
private Service service;
@Column(name = "blocked")
private boolean blocked;
}
class Service {
@OneToMany(mappedBy = "service")
private Set<UserService> userServices = new HashSet<UserService>();
}
If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.
User user = new User();
Service service = new Service();
UserService userService = new UserService();
user.addUserService(userService);
userService.setUser(user);
service.addUserService(userService);
userService.setService(service);
session.save(user);
session.save(service);
session.save(userService);
The data you want is in the "cols" meta-data table:
SELECT * FROM COLS WHERE COLUMN_NAME = 'id'
This one will give you a list of tables that have all of the columns you want:
select distinct
C1.TABLE_NAME
from
cols c1
inner join
cols c2
on C1.TABLE_NAME = C2.TABLE_NAME
inner join
cols c3
on C2.TABLE_NAME = C3.TABLE_NAME
inner join
cols c4
on C3.TABLE_NAME = C4.TABLE_NAME
inner join
tab t
on T.TNAME = C1.TABLE_NAME
where T.TABTYPE = 'TABLE' --could be 'VIEW' if you wanted
and upper(C1.COLUMN_NAME) like upper('%id%')
and upper(C2.COLUMN_NAME) like upper('%fname%')
and upper(C3.COLUMN_NAME) like upper('%lname%')
and upper(C4.COLUMN_NAME) like upper('%address%')
To do this in a different schema, just specify the schema in front of the table, as in
SELECT * FROM SCHEMA1.COLS WHERE COLUMN_NAME LIKE '%ID%';
If you want to combine the searches of many schemas into one output result, then you could do this:
SELECT DISTINCT
'SCHEMA1' AS SCHEMA_NAME
,TABLE_NAME
FROM SCHEMA1.COLS
WHERE COLUMN_NAME LIKE '%ID%'
UNION
SELECT DISTINCT
'SCHEMA2' AS SCHEMA_NAME
,TABLE_NAME
FROM SCHEMA2.COLS
WHERE COLUMN_NAME LIKE '%ID%'
Assuming your byteData
array is biger than 32 + byteSalt.length()
...you're going to it's length, not byteSalt.length
. You're trying to copy from beyond the array end.
To check whether a process/command returned 0 or not, use the operators && == 0 or
: not == 0 ||
Just add operator to your script:
execute_command && (
echo\Return 0, with no execution error
) || (
echo\Return non 0, something went wrong
)
command && echo\Return 0 || echo\Return non 0
Pressing (Cmd + /) will create a single line comment. i.e. // Single line comment
Type (/**
and press the Tab key) to create a block comment ala
/**
* Comment block
*/
You are expecting that your int
type is 16 bit wide, in which case you'd indeed get a negative value. But most likely it's 32 bits wide, so a signed int
can represent 65529 just fine. You can check this by printing sizeof(int)
.
It works fine for me, but it's a little tricky :)
Now you have settings for this session set (every time you load session it will be logged).
If you have an x
and y
column that you want to scatterplot, but not all of the cells in one of the columns is populated with meaningful values (i.e. some of them have #DIV/0!
), then insert a new column next to the offending column and type =IFERROR(A2, #N/A)
, where A2 is the value in the offending column.
This will return #N/A
if there is a #DIV/0!
and will return the good value otherwise. Now make your plot with your new column and Excel ignores #N/A
value and will not plot them as zeroes.
Important: do not output "#N/A"
in the formula, just output #N/A
.
To access the root directory from outside the controller you can simply inject %kernel.root_dir%
as an argument in your services configuration.
service_name:
class: Namespace\Bundle\etc
arguments: ['%kernel.root_dir%']
Then you can get the web root in the class constructor:
public function __construct($rootDir)
{
$this->webRoot = realpath($rootDir . '/../web');
}
Since other SO answers link to this question it's worth noting that there is another option now in PyOxidizer.
It's a rust utility which works in some of the same ways as pyinstaller, however has some additional features detailed here, to summarize the key ones:
onefile
mode(One other advantage of pyoxidizer
is that it does not seem to suffer from the GLIBC_X.XX not found
problem that can crop up with pyinstaller if you've created your binary on a system that has a glibc version newer than the target system).
Overall pyinstaller is much simpler to use than PyOxidizer, which often requires some complexity in the configuration file, and it's less Pythony since it's written in Rust and uses a configuration file format not very familiar in the Python world, but PyOxidizer does some more advanced stuff, especially if you are looking to produce single binaries (which is not pyinstaller's default).
All the answers provided here uses normal function but these days most of our code uses arrow functions in ES6. I hope my answer will help readers on how to use arrow function when we do iteration over array of objects
let data = {
"messages": [{
"msgFrom": "13223821242",
"msgBody": "Hi there"
}, {
"msgFrom": "Bill",
"msgBody": "Hello!"
}]
}
Do .forEach on array using arrow function
data.messages.forEach((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
Do .map on array using arrow function
data.messages.map((obj, i) => {
console.log("msgFrom", obj.msgFrom);
console.log("msgBody", obj.msgBody);
});
I use zsh-autoenv which is based off autoenv.
zsh-autoenv automatically sources (known/whitelisted)
.autoenv.zsh
files, typically used in project root directories. It handles "enter" and leave" events, nesting, and stashing of variables (overwriting and restoring).
Here is an example:
; cd dtree
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|?); cat .autoenv.zsh
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|?); cat .autoenv_leave.zsh
deactivate
So when I leave the dtree
directory, the virtual environment is automatically exited.
"Development tree utiles"
is just a name… No hidden mean linking to the Illuminati in here.
Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:
test = 'C:\\Windows\Users\alexb\'
rawtest = r'%s' %test
First run:
rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
Then run the command
npm install cross-env
npm install
and then you can also run
npm run dev
When you write your main function, you typically see one of two definitions:
int main(void)
int main(int argc, char **argv)
The second form will allow you to access the command line arguments passed to the program, and the number of arguments specified (arguments are separated by spaces).
The arguments to main
are:
int argc
- the number of arguments passed into your program when it was run. It is at least 1
.char **argv
- this is a pointer-to-char *
. It can alternatively be this: char *argv[]
, which means 'array of char *
'. This is an array of C-style-string pointers.For example, you could do this to print out the arguments passed to your C program:
#include <stdio.h>
int main(int argc, char **argv)
{
for (int i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\n", i, argv[i]);
}
}
I'm using GCC 4.5 to compile a file I called args.c
. It'll compile and build a default a.out
executable.
[birryree@lilun c_code]$ gcc -std=c99 args.c
Now run it...
[birryree@lilun c_code]$ ./a.out hello there
argv[0]: ./a.out
argv[1]: hello
argv[2]: there
So you can see that in argv
, argv[0]
is the name of the program you ran (this is not standards-defined behavior, but is common. Your arguments start at argv[1]
and beyond.
So basically, if you wanted a single parameter, you could say...
./myprogram integral
And you could check if argv[1]
was integral
, maybe like strcmp("integral", argv[1]) == 0
.
So in your code...
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2) // no arguments were passed
{
// do something
}
if (strcmp("integral", argv[1]) == 0)
{
runIntegral(...); //or something
}
else
{
// do something else.
}
}
Of course, this was all very rudimentary, and as your program gets more complex, you'll likely want more advanced command line handling. For that, you could use a library like GNU getopt
.
imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
imgDics.setOnClickListener(onPlayer2Click);
anim = new RotateAnimation(0f, 360f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(4000);
// Start animating the image
imgDics.startAnimation(anim);
Visual Leak Detector is a very good tool, altough it does not supports the calls on VC9 runtimes (MSVCR90D.DLL for example).
PHP has a method called md5 ;-) Just $password = md5($passToEncrypt);
If you are searching in a SQL u can use a MySQL Method MD5() too....
SELECT * FROM user WHERE Password='. md5($password) .'
or SELECT * FROM ser WHERE Password=MD5('. $password .')
To insert it u can do it the same way.
I had the same problem. The solution was to change the useState initial state value from string to array. In App.js, previous useState was
const [favoriteFilms, setFavoriteFilms] = useState('');
I changed it to
const [favoriteFilms, setFavoriteFilms] = useState([]);
and the component that uses those values stopped throwing error with .map function.
In setup.py under setup( :
setup(
name = 'foo library'
...
package_data={
'foolibrary.folderA': ['*'], # All files from folder A
'foolibrary.folderB': ['*.txt'] #All text files from folder B
},
Use rgba!
.alpha60 {
/* Fallback for web browsers that don't support RGBa */
background-color: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background-color: rgba(0, 0, 0, 0.6);
/* For IE 5.5 - 7*/
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
/* For IE 8*/
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";
}
In addition to this, you have to declare
background: transparent
for IE web browsers, preferably served via conditional comments or similar!
Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others
I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false
I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).
Setting copylocal=true, then rebuilding the installer, everything worked fine.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
private final Lock _mutex = new ReentrantLock(true);
_mutex.lock();
// your protected code here
_mutex.unlock();
If you are using bash on Mac OS X which neither has realpath existed nor its readlink can print the absolute path, you may have choice but to code your own version to print it. Here is my implementation:
(pure bash)
abspath(){
local thePath
if [[ ! "$1" =~ ^/ ]];then
thePath="$PWD/$1"
else
thePath="$1"
fi
echo "$thePath"|(
IFS=/
read -a parr
declare -a outp
for i in "${parr[@]}";do
case "$i" in
''|.) continue ;;
..)
len=${#outp[@]}
if ((len==0));then
continue
else
unset outp[$((len-1))]
fi
;;
*)
len=${#outp[@]}
outp[$len]="$i"
;;
esac
done
echo /"${outp[*]}"
)
}
(use gawk)
abspath_gawk() {
if [[ -n "$1" ]];then
echo $1|gawk '{
if(substr($0,1,1) != "/"){
path = ENVIRON["PWD"]"/"$0
} else path = $0
split(path, a, "/")
n = asorti(a, b,"@ind_num_asc")
for(i in a){
if(a[i]=="" || a[i]=="."){
delete a[i]
}
}
n = asorti(a, b, "@ind_num_asc")
m = 0
while(m!=n){
m = n
for(i=1;i<=n;i++){
if(a[b[i]]==".."){
if(b[i-1] in a){
delete a[b[i-1]]
delete a[b[i]]
n = asorti(a, b, "@ind_num_asc")
break
} else exit 1
}
}
}
n = asorti(a, b, "@ind_num_asc")
if(n==0){
printf "/"
} else {
for(i=1;i<=n;i++){
printf "/"a[b[i]]
}
}
}'
fi
}
(pure bsd awk)
#!/usr/bin/env awk -f
function abspath(path, i,j,n,a,b,back,out){
if(substr(path,1,1) != "/"){
path = ENVIRON["PWD"]"/"path
}
split(path, a, "/")
n = length(a)
for(i=1;i<=n;i++){
if(a[i]==""||a[i]=="."){
continue
}
a[++j]=a[i]
}
for(i=j+1;i<=n;i++){
delete a[i]
}
j=0
for(i=length(a);i>=1;i--){
if(back==0){
if(a[i]==".."){
back++
continue
} else {
b[++j]=a[i]
}
} else {
if(a[i]==".."){
back++
continue
} else {
back--
continue
}
}
}
if(length(b)==0){
return "/"
} else {
for(i=length(b);i>=1;i--){
out=out"/"b[i]
}
return out
}
}
BEGIN{
if(ARGC>1){
for(k=1;k<ARGC;k++){
print abspath(ARGV[k])
}
exit
}
}
{
print abspath($0)
}
example:
$ abspath I/am/.//..//the/./god/../of///.././war
/Users/leon/I/the/war
select unique red24.image_id from
(
select image_id from `list` where style_id = 24 and style_value = 'red'
) red24
inner join
(
select image_id from `list` where style_id = 25 and style_value = 'big'
) big25
on red24.image_id = big25.image_id
inner join
(
select image_id from `list` where style_id = 27 and style_value = 'round'
) round27
on red24.image_id = round27.image_id
This is a good question.
All your question is based on "how do we represent a number?"
ALL the numbers can be represented with decimal representation or with binary (2's complement) representation. All of them !!
BUT some (most of them) require infinite number of elements ("0" or "1" for the binary position, or "0", "1" to "9" for the decimal representation).
Like 1/3 in decimal representation (1/3 = 0.3333333... <- with an infinite number of "3")
Like 0.1 in binary ( 0.1 = 0.00011001100110011.... <- with an infinite number of "0011")
Everything is in that concept. Since your computer can only consider finite set of digits (decimal or binary), only some numbers can be exactly represented in your computer...
And as said Jon, 3 is a prime number which isn't a factor of 10, so 1/3 cannot be represented with a finite number of elements in base 10.
Even with arithmetic with arbitrary precision, the numbering position system in base 2 is not able to fully describe 6.1, although it can represent 61.
For 6.1, we must use another representation (like decimal representation, or IEEE 854 that allows base 2 or base 10 for the representation of floating-point values)
First, this code here,
string [] scripts = new String [] ("test3","test4","test5");
should be
String[] scripts = new String [] {"test3","test4","test5"};
Please read this tutorial on Arrays
Second,
Arrays are fixed size, so you can't add new Strings to above array. You may override existing values
scripts[0] = string1;
(or)
Create array with size then keep on adding elements till it is full.
If you want resizable arrays, consider using ArrayList.
I hit this question looking for how to run batch scripts during user logon on a standalone windows server (workgroup not in domain). I found the answer in using group policy.
cmd /k mybatchfile.cmd
if you want the command window to stay (on desktop) after batch script have finished.You'd have to define alphanumerics exactly, but
/^(\w{3,5})$/
Should match any digit/character/_ combination of length 3-5.
If you also need the dash, make sure to escape it ( add it, like this: :\-
)
/^([\w\-]{3,5})$/
Also: the ^
anchor means that the sequence has to start at the beginning of the line (character string), and the $
that it ends at the end of the line (character string). So your value
string mustn't contain anything else, or it won't match.
My answer might not be related to problem mention here, but I had same problem with Python 3.4 where Crypto.Cipher wasn't a valid import. So I tried installing PyCrypto and went into problems.
After some research I found with 3.4 you should use pycryptodome.
I install pycryptodome using pycharm and I was good.
from Crypto.Cipher import AES
char buffer [50];
unsigned long a = 5;
int n=sprintf (buffer, "%lu", a);
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
If you want to use the reset_index
method and also preserve your existing index you should use:
df.reset_index().set_index('index', drop=False)
or to change it in place:
df.reset_index(inplace=True)
df.set_index('index', drop=False, inplace=True)
For example:
print(df)
gi ptt_loc
0 384444683 593
4 384444684 594
9 384444686 596
print(df.reset_index())
index gi ptt_loc
0 0 384444683 593
1 4 384444684 594
2 9 384444686 596
print(df.reset_index().set_index('index', drop=False))
index gi ptt_loc
index
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
And if you want to get rid of the index label you can do:
df2 = df.reset_index().set_index('index', drop=False)
df2.index.name = None
print(df2)
index gi ptt_loc
0 0 384444683 593
4 4 384444684 594
9 9 384444686 596
This can be done very elegantly with Ray.
To parallelize your example, you'd need to define your functions with the @ray.remote
decorator, and then invoke them with .remote
.
import ray
ray.init()
# Define the functions.
@ray.remote
def solve1(a):
return 1
@ray.remote
def solve2(b):
return 2
# Start two tasks in the background.
x_id = solve1.remote(0)
y_id = solve2.remote(1)
# Block until the tasks are done and get the results.
x, y = ray.get([x_id, y_id])
There are a number of advantages of this over the multiprocessing module.
These function calls can be composed together, e.g.,
@ray.remote
def f(x):
return x + 1
x_id = f.remote(1)
y_id = f.remote(x_id)
z_id = f.remote(y_id)
ray.get(z_id) # returns 4
Note that Ray is a framework I've been helping develop.
In principle, it is wrong to look for an index of a key. Keys of a hash map are unordered, you should never expect specific order.
If you have pending scheduled local notifications and don't want to use cancelAllLocalNotifications
to clear old ones in Notification Center, you can also do the following:
[UIApplication sharedApplication].scheduledLocalNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
It appears that if you set the scheduledLocalNotifications
it clears the old ones in Notification Center, and by setting it to itself, you retain the pending local notifications.
To be absolutely correct you should put all the names into the SAN field.
The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.
This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.
The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...
If you found a correct implementation, the answers for your questions will be the followings:
Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.
What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.
In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.
The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)
On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)
Rob Farley's blog post might be of help:
Something like:
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'Department'
set @col_name = N'ModifiedDate'
select t.name, c.name, d.name, d.definition
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
I have many sites with this issue & finally found a fix to firefox fonts being thicker than chrome.
You need this line next to your -webkit fix -moz-osx-font-smoothing: grayscale;
body{
text-rendering: optimizeLegibility;
-webkit-font-smoothing: subpixel-antialiased;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
This is how I solved
<a href="#" >
<button type="button" class="btn btn-info">Button Text</button>
</a>
input[type='text'], input[type='password']
{
// my css
}
That is the correct way to do it. Sadly CSS is not a programming language.
bootstrap 3 has a class to align the text within a div
<div class="text-right">
will align the text on the right
<div class="pull-right">
will pull to the right all the content not only the text
Domain names are not case sensitive but the rest of the URI certainly can be. It's a big mistake to assume URIs are not case sensitive.
The safest way is to rely on the browser TextNode to correctly escape content. Here's an example:
function stripHTML(dirtyString) {_x000D_
var container = document.createElement('div');_x000D_
var text = document.createTextNode(dirtyString);_x000D_
container.appendChild(text);_x000D_
return container.innerHTML; // innerHTML will be a xss safe string_x000D_
}_x000D_
_x000D_
document.write( stripHTML('<p>some <span>content</span></p>') );_x000D_
document.write( stripHTML('<script><p>some <span>content</span></p>') );
_x000D_
The thing to remember here is that the browser escape the special characters of TextNodes when we access the html strings (innerHTML
, outerHTML
). By comparison, accessing text values (innerText
, textContent
) will yield raw strings, meaning they're unsafe and could contains XSS.
If you use jQuery, then using .text()
is safe and backward compatible. See the other answers to this question.
The simplest way in pure JavaScript if you work with browsers <= Internet Explorer 8 is:
string.replace(/(<([^>]+)>)/ig,"");
But there's some issue with parsing HTML with regex so this won't provide very good security. Also, this only takes care of HTML characters, so it is not totally xss-safe.
my solution is similar to the solution given by Server Themes. Do check it once:
localStorage.setItem("validNavigation", false);
$(document).on('keypress', function (e) {
if (e.keyCode == 116) {
localStorage.setItem("validNavigation", true);
}
});
// Attach the event click for all links in the page
$(document).on("click", "a", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event submit for all forms in the page
$(document).on("submit", "form", function () {
localStorage.setItem("validNavigation", true);
});
// Attach the event click for all inputs in the page
$(document).bind("click", "input[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
$(document).bind("click", "button[type=submit]", function () {
localStorage.setItem("validNavigation", true);
});
window.onbeforeunload = function (event) {
if (localStorage.getItem("validNavigation") === "false") {
event.returnValue = "Write something clever here..";
console.log("Test success!");
localStorage.setItem("validNavigation", false);
}
};
If you put the breakpoints correctly on the browser page, the if condition will be true only when the browser is about to be closed or the tab is about to be closed.
Check this link for reference: https://www.oodlestechnologies.com/blogs/Capture-Browser-Or-Tab-Close-Event-Jquery-Javascript/
I ran into the same issue on my win7 x64 laptop and was able to get it working using the curl release that is labeled Win64 - Generic w SSL by using the very similar command line format:
C:\Projects\curl-7.23.1-win64-ssl-sspi>curl -H "Content-Type: application/json" -X POST http://localhost/someapi -d "{\"Name\":\"Test Value\"}"
Which only differs from your 2nd escape version by using double-quotes around the escaped ones and the header parameter value. Definitely prefer the linux shell syntax more.
Here is the fiddle I've made:jsfiddle.net. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement
. Hence super(props)
should be called only when the superclass's constructor manually assings props
to this.props
. If you just extend the React.Component
calling super(props)
will do nothing with props. Maybe It will be changed in the next versions of React.
The char already has an IsDigit(char c) which does this:
public static bool IsDigit(char c)
{
if (!char.IsLatin1(c))
return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber;
if ((int) c >= 48)
return (int) c <= 57;
else
return false;
}
You can simply do this:
var theString = "839278";
bool digitsOnly = theString.All(char.IsDigit);
Consider you can't use multiple inheritance in C#, and then look at your question again.
SELECT e.*,
cnt.colCount
FROM eventsTable e
INNER JOIN (
select columnName,count(columnName) as colCount
from eventsTable e2
group by columnName
) as cnt on cnt.columnName = e.columnName
WHERE e.columnName='Business'
-- Added space
You need set image type :small_image or image
echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(163, 100);
https://stackoverflow.com/a/16350929/11860907
If you add e.SuppressKeyPress = true;
as shown in the answer in this link you will suppress the annoying ding sound that occurs.
I sometimes encounter the same issue. I can only answer your second bullet, because I am not as expert in R as I am with other languages. I have found that the standard for
loop has some unexpected results. Say x = 0
for (i in 1:x) {
print(i)
}
The output is
[1] 1
[1] 0
Whereas with python, for example
for i in range(x):
print i
does nothing. The loop is not entered.
I expected that if x = 0
that in R, the loop would not be entered. However, 1:0
is a valid range of numbers. I have not yet found a good workaround besides having an if
statement wrapping the for
loop
Sqlite helper class helps us to manage database creation and version management.
SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade()
methods of SQLiteOpenHelper
. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete()
to create, read, update and delete rows of your table.
Example to create a MyEmployees table and to select and insert records:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DBName";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table MyEmployees
( _id integer primary key,name text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS MyEmployees");
onCreate(database);
}
}
Now you can use this class as below,
public class MyDB{
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public final static String EMP_TABLE="MyEmployees"; // name of table
public final static String EMP_ID="_id"; // id value for employee
public final static String EMP_NAME="name"; // name of employee
/**
*
* @param context
*/
public MyDB(Context context){
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long createRecords(String id, String name){
ContentValues values = new ContentValues();
values.put(EMP_ID, id);
values.put(EMP_NAME, name);
return database.insert(EMP_TABLE, null, values);
}
public Cursor selectRecords() {
String[] cols = new String[] {EMP_ID, EMP_NAME};
Cursor mCursor = database.query(true, EMP_TABLE,cols,null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
}
Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.
In case anyone in the future had this problem, I'm using a Mac and just had to install the Command Line Tools using 'xcode-select --install'
Enter some junk value into your .htaccess
e.g. foo bar
, sakjnaskljdnas
any keyword not recognized by htaccess
and visit your URL. If it is working, you should get a
500 Internal Server Error
Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request....
I suggest you to put it soon after RewriteEngine on
.
Since you are on your machine. I presume you have access to apache .conf
file.
open the .conf
file, and look for a line similar to:
LoadModule rewrite_module modules/mod_rewrite.so
If it is commented(#), uncomment and restart apache.
To log rewrite
RewriteEngine On
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 9
Put the above 3 lines in your virtualhost
. restart the httpd.
RewriteLogLevel 9
Using a high value for Level will slow down your Apache server dramatically! Use the rewriting logfile at a Level greater than 2 only for debugging!
Level 9 will log almost every rewritelog detail.
Things have changed in Apache 2.4:
FROM Upgrading to 2.4 from 2.2
The RewriteLog and RewriteLogLevel directives have been removed. This functionality is now provided by configuring the appropriate level of logging for the mod_rewrite module using the LogLevel directive. See also the mod_rewrite logging section.
For more on LogLevel, refer LogLevel Directive
you can accomplish
RewriteLog "/path/to/rewrite.log"
in this manner now
LogLevel debug rewrite_module:debug
You need some sort of Inter Process Communication. Use a pipe or a shared buffer.
In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:
#include <stdio.h>
#include <stdlib.h>
typedef struct Cell {
int cellSeq;
struct Cell* next; /* 'tCell *next' will not work here */
} tCell;
int main(void) {
int i;
tCell *curr;
tCell *first;
tCell *last;
/* Construct linked list, 100 down to 80. */
first = malloc (sizeof (tCell));
last = first;
first->cellSeq = 100;
first->next = NULL;
for (i = 0; i < 20; i++) {
curr = malloc (sizeof (tCell));
curr->cellSeq = last->cellSeq - 1;
curr->next = NULL;
last->next = curr;
last = curr;
}
/* Walk the list, printing sequence numbers. */
curr = first;
while (curr != NULL) {
printf ("Sequence = %d\n", curr->cellSeq);
curr = curr->next;
}
return 0;
}
Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell
on the first line of the typedef
but not knowing about tCell
until the last line :-) That's how I remember that rule.
@SafeVarargs
does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.
http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.
Heap pollution is when you get a ClassCastException
when doing an operation on a generic interface and it contains another type than declared.
Why do you need to do this in one monster-regex? You can use actual code to implement some of these rules, and doing so would be much easier to modify if those requirements change later.
For example:
if(/^[A-Z0-9\s]*$/)
# sentence is all uppercase, so just fail out
return 0;
# Carry on with matching uppercase terms
It sets the distance of the inset between the content view and the enclosing scroll view.
Obj-C
aScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 7.0);
Swift 5.0
aScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 7.0)
Here's a good iOS Reference Library article on scroll views that has an informative screenshot (fig 1-3) - I'll replicate it via text here:
_|?_cW_?_|_?_
| |
---------------
|content| ?
? |content| contentInset.top
cH |content|
? |content| contentInset.bottom
|content| ?
---------------
_|_______|___
?
(cH = contentSize.height; cW = contentSize.width)
The scroll view encloses the content view plus whatever padding is provided by the specified content insets.
I have solved it by importing FormModule in a shared.module and importing the shared.module in all other modules. My case is the FormModule is used in multiple modules.
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/
in template:
<ion-item>
<ion-label>Home</ion-label>
<ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>
in controller:
focusInput(input) {
input.setFocus();
}
I know this is old, but, in running into a vendor that inconsistently uses 5 different date formats in their APIs (and test servers with a variety of PHP versions from the 5's through the latest 7's), I decided to write a universal converter that works with a myriad of PHP versions.
This converter will take virtually any input, including any standard datetime format (including with or without milliseconds) and any Epoch Time representation (including with or without milliseconds) and convert it to virtually any other format.
To call it:
$TheDateTimeIWant=convertAnyDateTome_toMyDateTime([thedateIhave],[theformatIwant]);
Sending null for the format will make the function return the datetime in Epoch/Unix Time. Otherwise, send any format string that date() supports, as well as with ".u" for milliseconds (I handle milliseconds as well, even though date() returns zeros).
Here's the code:
<?php
function convertAnyDateTime_toMyDateTime($dttm,$dtFormat)
{
if (!isset($dttm))
{
return "";
}
$timepieces = array();
if (is_numeric($dttm))
{
$rettime=$dttm;
}
else
{
$rettime=strtotime($dttm);
if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))>0)
{
$rettime=$rettime.substr($dttm,strpos($dttm,"."),strpos($dttm,"-",strpos($dttm,"."))-strpos($dttm,"."));
$timepieces[1]="";
}
else if (strpos($dttm,".")>0 and strpos($dttm,"-",strpos($dttm,"."))==0)
{
preg_match('/([0-9]+)([^0-9]+)/',substr($dttm,strpos($dttm,"."))." ",$timepieces);
$rettime=$rettime.".".$timepieces[1];
}
}
if (isset($dtFormat))
{
// RETURN as ANY date format sent
if (strpos($dtFormat,".u")>0) // Deal with milliseconds
{
$rettime=date($dtFormat,$rettime);
$rettime=substr($rettime,0,strripos($rettime,".")+1).$timepieces[1];
}
else // NO milliseconds wanted
{
$rettime=date($dtFormat,$rettime);
}
}
else
{
// RETURN Epoch Time (do nothing, we already built Epoch Time)
}
return $rettime;
}
?>
Here's some sample calls - you will note it also handles any time zone data (though as noted above, any non GMT time is returned in your time zone).
$utctime1="2018-10-30T06:10:11.2185007-07:00";
$utctime2="2018-10-30T06:10:11.2185007";
$utctime3="2018-10-30T06:10:11.2185007 PDT";
$utctime4="2018-10-30T13:10:11.2185007Z";
$utctime5="2018-10-30T13:10:11Z";
$dttm="10/30/2018 09:10:11 AM EST";
echo "<pre>";
echo "<b>Epoch Time to a standard format</b><br>";
echo "<br>Epoch Tm: 1540905011 to STD DateTime ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","Y-m-d H:i:s")."<hr>";
echo "<br>Epoch Tm: 1540905011 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011","c");
echo "<br>Epoch Tm: 1540905011.2185007 to UTC ----RESULT: ".convertAnyDateTime_toMyDateTime("1540905011.2185007","c")."<hr>";
echo "<b>Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)";
echo "</b><br>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,null);
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,null);
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,null);
echo "<br>UTCTime4: ".$utctime4." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime4,null);
echo "<br>UTCTime5: ".$utctime5." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime5,null);
echo "<br>NO MILIS: ".$dttm." ----RESULT: ".convertAnyDateTime_toMyDateTime($dttm,null);
echo "<hr>";
echo "<hr>";
echo "<b>Returned as whatever datetime format one desires</b>";
echo "<br>UTCTime1: ".$utctime1." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime1,"Y-m-d H:i:s")." Y-m-d H:i:s";
echo "<br>UTCTime2: ".$utctime2." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime2,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"Y-m-d H:i:s.u")." Y-m-d H:i:s.u";
echo "<p><b>Returned as ISO8601</b>";
echo "<br>UTCTime3: ".$utctime3." ----RESULT: ".convertAnyDateTime_toMyDateTime($utctime3,"c")." ISO8601";
echo "</pre>";
Here's the output:
Epoch Tm: 1540905011 ----RESULT: 2018-10-30 09:10:11
Epoch Tm: 1540905011 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Epoch Tm: 1540905011.2185007 to UTC ----RESULT: 2018-10-30T09:10:11-04:00
Returned as Epoch Time (the number of seconds that have elapsed since 00:00:00 Thursday, 1 January 1970, Coordinated Universal Time (UTC), minus leap seconds.)
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 1540905011.2185007
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 1540894211.2185007
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 1540905011.2185007
UTCTime4: 2018-10-30T13:10:11.2185007Z ----RESULT: 1540905011.2185007
UTCTime5: 2018-10-30T13:10:11Z ----RESULT: 1540905011
NO MILIS: 10/30/2018 09:10:11 AM EST ----RESULT: 1540908611
Returned as whatever datetime format one desires
UTCTime1: 2018-10-30T06:10:11.2185007-07:00 ----RESULT: 2018-10-30 09:10:11 Y-m-d H:i:s
UTCTime2: 2018-10-30T06:10:11.2185007 ----RESULT: 2018-10-30 06:10:11.2185007 Y-m-d H:i:s.u
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30 09:10:11.2185007 Y-m-d H:i:s.u
Returned as ISO8601
UTCTime3: 2018-10-30T06:10:11.2185007 PDT ----RESULT: 2018-10-30T09:10:11-04:00 ISO8601
The only thing not in this version is the ability to select the time zone you want the returned datetime to be in. Originally, I wrote this to change any datetime to Epoch Time, so, I didn't need time zone support. It's trivial to add though.
You have misspelt the second pixels
as pixel
. The following works:
pixels = [1,2,3]
pixels[0] = 5
It appears that due to the typo you were trying to accidentally modify some tuple called pixel
, and in Python tuples are immutable. Hence the confusing error message.
In Symfony 2 ( to be more specific, the 2.3 version ) you can get a data of an field by
$var = $form->get('yourformfieldname')->getData();
or you can get all data sent
$data = $form->getData();
where '$data' is an array containing your form fields' values.
Mean for each column in df
:
A B C
0 5 3 8
1 5 3 9
2 8 4 9
df.mean()
A 6.000000
B 3.333333
C 8.666667
dtype: float64
and if you want average of all columns:
df.stack().mean()
6.0
This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) : in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]
Braintree also has an open source PHP library that makes PHP integration pretty easy.
The element.getBoundingClientRect()
method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.
While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.
If you want the column names only, you can do:
List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
DataTable dt = reader.GetSchemaTable();
foreach (DataRow row in dt.Rows)
{
columns.Add(row.Field<String>("ColumnName"));
}
}
But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.
public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
// Add the parameters for the SelectCommand.
if (queryParams != null)
foreach (var param in queryParams)
cmd.Parameters.AddWithValue(param.Key, param.Value);
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(reader);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
}
}
}
}
conn.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return CaseInsensitiveDictionary;
}
In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:
Python-2.x
class A(object):
def __init__(self):
print "world"
class B(A):
def __init__(self):
print "hello"
super(B, self).__init__()
Python-3.x
class A(object):
def __init__(self):
print("world")
class B(A):
def __init__(self):
print("hello")
super().__init__()
super()
is now equivalent to super(<containing classname>, self)
as per the docs.
To remove everything before a certain character, use a regular expression:
re.sub(r'^[^a]*', '')
to remove everything up to the first 'a'. [^a]
can be replaced with any character class you like, such as word characters.
If you created new settings.xml file instead of copy it from somewhere else, remember to put the tag inside :
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 https://maven.apache.org/xsd/settings-1.0.0.xsd"> <proxies> ..... </proxies> </settings>
Array.Equals
is comparing the references, not their contents:
Currently, when you compare two arrays with the = operator, we are really using the System.Object's = operator, which only compares the instances. (i.e. this uses reference equality, so it will only be true if both arrays points to the exact same instance)
If you want to compare the contents of the arrays you need to loop though the arrays and compare the elements.
The same blog post has an example of how to do this.
For bash, store your command like this:
command="ls | grep -c '^'"
Run your command like this:
echo $command | bash
abs(x-y)
will do exactly what you're looking for:
In [1]: abs(1-2)
Out[1]: 1
In [2]: abs(2-1)
Out[2]: 1
If you happen to get this error on an ASP.NET web application, in addition to other things mentioned check the following:
Here's a sample code on how to read a file properly inside a jar file (in this case, the current executing jar file)
Just change executable with the path of your jar file if it is not the current running one.
Then change the filePath to the path of the file you want to use inside the jar file. I.E. if your file is in
someJar.jar\img\test.gif
. Set the filePath to "img\test.gif"
File executable = new File(BrowserViewControl.class.getProtectionDomain().getCodeSource().getLocation().toURI());
JarFile jar = new JarFile(executable);
InputStream fileInputStreamReader = jar.getInputStream(jar.getJarEntry(filePath));
byte[] bytes = new byte[fileInputStreamReader.available()];
int sizeOrig = fileInputStreamReader.available();
int size = fileInputStreamReader.available();
int offset = 0;
while (size != 0){
fileInputStreamReader.read(bytes, offset, size);
offset = sizeOrig - fileInputStreamReader.available();
size = fileInputStreamReader.available();
}
I was wondering if it is possible to execute something like this using JDBC.
"SELECT FROM * TABLE;INSERT INTO TABLE;"
Yes it is possible. There are two ways, as far as I know. They are
Following examples demonstrate the above two possibilities.
Example 1: ( To allow multiple queries ):
While sending a connection request, you need to append a connection property allowMultiQueries=true
to the database url. This is additional connection property to those if already exists some, like autoReConnect=true
, etc.. Acceptable values for allowMultiQueries
property are true
, false
, yes
, and no
. Any other value is rejected at runtime with an SQLException
.
String dbUrl = "jdbc:mysql:///test?allowMultiQueries=true";
Unless such instruction is passed, an SQLException
is thrown.
You have to use execute( String sql )
or its other variants to fetch results of the query execution.
boolean hasMoreResultSets = stmt.execute( multiQuerySqlString );
To iterate through and process results you require following steps:
READING_QUERY_RESULTS: // label
while ( hasMoreResultSets || stmt.getUpdateCount() != -1 ) {
if ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // if has rs
else { // if ddl/dml/...
int queryResult = stmt.getUpdateCount();
if ( queryResult == -1 ) { // no more queries processed
break READING_QUERY_RESULTS;
} // no more queries processed
// handle success, failure, generated keys, etc here
} // if ddl/dml/...
// check to continue in the loop
hasMoreResultSets = stmt.getMoreResults();
} // while results
Example 2: Steps to follow:
select
, and DML
queries.CallableStatement
.ResultSet
s executed in procedure.select
Sample table and procedure:
mysql> create table tbl_mq( i int not null auto_increment, name varchar(10), primary key (i) );
Query OK, 0 rows affected (0.16 sec)
mysql> delimiter //
mysql> create procedure multi_query()
-> begin
-> select count(*) as name_count from tbl_mq;
-> insert into tbl_mq( names ) values ( 'ravi' );
-> select last_insert_id();
-> select * from tbl_mq;
-> end;
-> //
Query OK, 0 rows affected (0.02 sec)
mysql> delimiter ;
mysql> call multi_query();
+------------+
| name_count |
+------------+
| 0 |
+------------+
1 row in set (0.00 sec)
+------------------+
| last_insert_id() |
+------------------+
| 3 |
+------------------+
1 row in set (0.00 sec)
+---+------+
| i | name |
+---+------+
| 1 | ravi |
+---+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Call Procedure from Java:
CallableStatement cstmt = con.prepareCall( "call multi_query()" );
boolean hasMoreResultSets = cstmt.execute();
READING_QUERY_RESULTS:
while ( hasMoreResultSets ) {
Resultset rs = stmt.getResultSet();
// handle your rs here
} // while has more rs
Sub Results2()
Dim rCell As Range
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim lCnt As Long
Set shSource = ThisWorkbook.Sheets("Sheet1")
Set shDest = ThisWorkbook.Sheets("Sheet2")
For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
lCnt = lCnt + 1
shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
Next rCell
End Sub
This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.
To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.
I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,
Sub Results3()
Dim i As Long, lCnt As Long
Dim sh As Worksheet
lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
Set sh = ThisWorkbook.Sheets("Sheet2")
Const sSOURCE As String = "Sheet1!"
For i = 1 To lCnt
sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
Next i
End Sub
html, body, ul, li, img {_x000D_
box-sizing: border-box;_x000D_
margin: 0px; _x000D_
padding: 0px; _x000D_
}_x000D_
_x000D_
#slideshowWrapper {_x000D_
width: 25rem;_x000D_
height: auto;_x000D_
position: relative;_x000D_
_x000D_
margin-top: 50px;_x000D_
border: 3px solid black;_x000D_
}_x000D_
_x000D_
ul {_x000D_
list-style: none;_x000D_
border: 3px solid blue; _x000D_
}_x000D_
_x000D_
li {_x000D_
/* center horizontal */_x000D_
position: relative;_x000D_
left: 0;_x000D_
top: 50%;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
font-size: 18px;_x000D_
/* center horizontal */_x000D_
_x000D_
border: 3px solid red; _x000D_
}_x000D_
_x000D_
img {_x000D_
border: 1px solid #ccc;_x000D_
padding: 4px;_x000D_
//width: 200px;_x000D_
height: 100px;_x000D_
}
_x000D_
<body>_x000D_
<div id="slideshowWrapper">_x000D_
<ul id="slideshow">_x000D_
<li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li>_x000D_
<li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li>_x000D_
<li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li> _x000D_
</ul>_x000D_
</div>_x000D_
</body>
_x000D_
I found the solution: Go to the link below and submit your application.
Play Protect Appeals Submission Form
After a few days, the problem will be fixed
The problem is the tv.setText(text)
. The variable tv is probably null
and you call the setText
method on that null
, which you can't.
My guess that the problem is on the findViewById
method, but it's not here, so I can't tell more, without the code.
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
To use the 'json' library:
require 'json'
To convert an object to JSON (these 3 ways are equivalent):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
To convert JSON text to an object (these 2 ways are equivalent):
JSON.load string #returns an object
JSON.parse string #returns an object
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\""
.
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:
class A
def to_json
{'a' => @a, 'b' => @b}.to_json
end
def self.from_json string
data = JSON.load string
self.new data['a'], data['b']
end
end
You could automate this by inheriting from a 'JSONable' class:
class JSONable
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
def from_json! string
JSON.load(string).each do |var, val|
self.instance_variable_set var, val
end
end
end
Then you can use object.to_json
to serialise to JSON and object.from_json! string
to copy the saved state that was saved as the JSON string to the object.
In java you don't check if a key is pressed, instead you listen to KeyEvent
s.
The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean wPressed = false;
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch (ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
}
break;
}
return false;
}
}
});
}
}
Then you can always use:
if (IsKeyPressed.isWPressed()) {
// do your thing.
}
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
Please try this:
CREATE TABLE article (
article_id bigint(20) NOT NULL serial,
article_name varchar(20) NOT NULL,
article_desc text NOT NULL,
date_added datetime default NULL,
PRIMARY KEY (article_id)
);
Here is another solution:
for(String serverId : serverIds) {
sb.append(",");
sb.append(serverId);
}
String resultingString = "";
if ( sb.length() > 1 ) {
resultingString = sb.substring(1);
}
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
import org.apache.log4j.PropertyConfigurator;
Import this, then:
Properties props = new Properties();
InputStream is = Main.class.getResourceAsStream("/log4j.properties");
try {
props.load(is);
} catch (Exception e) {
// ignore this exception
log.error("Unable to load log4j properties file.",e);
}
PropertyConfigurator.configure(props);
My java files directory like this:
src/main/java/com/abc/xyz
And log4j directory like this:
src/main/resources
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
You can clear the input field by using $('#shares').val('');
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
This is from Python docs
>>> from ftplib import FTP_TLS
>>> ftps = FTP_TLS('ftp.python.org')
>>> ftps.login() # login anonymously before securing control
channel
>>> ftps.prot_p() # switch to secure data connection
>>> ftps.retrlines('LIST') # list directory content securely
total 9
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .
drwxr-xr-x 8 root wheel 1024 Jan 3 1994 ..
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin
drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc
d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming
drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib
drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub
drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr
-rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg
@import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");
.row {
height: 100px;
background-color: green;
}
.container {
margin-top: 50px;
box-shadow: 0 0 30px black;
padding:0 15px 0 15px;
}
<div class="container">
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
</div>
</body>
For example, if I wanted to move all .txt files from one location to another ( on a Windows OS for instance ) I would do it something like this:
import shutil
import os,glob
inpath = 'R:/demo/in'
outpath = 'R:/demo/out'
os.chdir(inpath)
for file in glob.glob("*.txt"):
shutil.move(inpath+'/'+file,outpath)
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
IEnumerable<T> ids = list.Select(x => x).Distinct();
When is lexing enough, when do you need EBNF?
EBNF really doesn't add much to the power of grammars. It's just a convenience / shortcut notation / "syntactic sugar" over the standard Chomsky's Normal Form (CNF) grammar rules. For example, the EBNF alternative:
S --> A | B
you can achieve in CNF by just listing each alternative production separately:
S --> A // `S` can be `A`,
S --> B // or it can be `B`.
The optional element from EBNF:
S --> X?
you can achieve in CNF by using a nullable production, that is, the one which can be replaced by an empty string (denoted by just empty production here; others use epsilon or lambda or crossed circle):
S --> B // `S` can be `B`,
B --> X // and `B` can be just `X`,
B --> // or it can be empty.
A production in a form like the last one B
above is called "erasure", because it can erase whatever it stands for in other productions (product an empty string instead of something else).
Zero-or-more repetiton from EBNF:
S --> A*
you can obtan by using recursive production, that is, one which embeds itself somewhere in it. It can be done in two ways. First one is left recursion (which usually should be avoided, because Top-Down Recursive Descent parsers cannot parse it):
S --> S A // `S` is just itself ended with `A` (which can be done many times),
S --> // or it can begin with empty-string, which stops the recursion.
Knowing that it generates just an empty string (ultimately) followed by zero or more A
s, the same string (but not the same language!) can be expressed using right-recursion:
S --> A S // `S` can be `A` followed by itself (which can be done many times),
S --> // or it can be just empty-string end, which stops the recursion.
And when it comes to +
for one-or-more repetition from EBNF:
S --> A+
it can be done by factoring out one A
and using *
as before:
S --> A A*
which you can express in CNF as such (I use right recursion here; try to figure out the other one yourself as an exercise):
S --> A S // `S` can be one `A` followed by `S` (which stands for more `A`s),
S --> A // or it could be just one single `A`.
Knowing that, you can now probably recognize a grammar for a regular expression (that is, regular grammar) as one which can be expressed in a single EBNF production consisting only from terminal symbols. More generally, you can recognize regular grammars when you see productions similar to these:
A --> // Empty (nullable) production (AKA erasure).
B --> x // Single terminal symbol.
C --> y D // Simple state change from `C` to `D` when seeing input `y`.
E --> F z // Simple state change from `E` to `F` when seeing input `z`.
G --> G u // Left recursion.
H --> v H // Right recursion.
That is, using only empty strings, terminal symbols, simple non-terminals for substitutions and state changes, and using recursion only to achieve repetition (iteration, which is just linear recursion - the one which doesn't branch tree-like). Nothing more advanced above these, then you're sure it's a regular syntax and you can go with just lexer for that.
But when your syntax uses recursion in a non-trivial way, to produce tree-like, self-similar, nested structures, like the following one:
S --> a S b // `S` can be itself "parenthesized" by `a` and `b` on both sides.
S --> // or it could be (ultimately) empty, which ends recursion.
then you can easily see that this cannot be done with regular expression, because you cannot resolve it into one single EBNF production in any way; you'll end up with substituting for S
indefinitely, which will always add another a
s and b
s on both sides. Lexers (more specifically: Finite State Automata used by lexers) cannot count to arbitrary number (they are finite, remember?), so they don't know how many a
s were there to match them evenly with so many b
s. Grammars like this are called context-free grammars (at the very least), and they require a parser.
Context-free grammars are well-known to parse, so they are widely used for describing programming languages' syntax. But there's more. Sometimes a more general grammar is needed -- when you have more things to count at the same time, independently. For example, when you want to describe a language where one can use round parentheses and square braces interleaved, but they have to be paired up correctly with each other (braces with braces, round with round). This kind of grammar is called context-sensitive. You can recognize it by that it has more than one symbol on the left (before the arrow). For example:
A R B --> A S B
You can think of these additional symbols on the left as a "context" for applying the rule. There could be some preconditions, postconditions etc. For example, the above rule will substitute R
into S
, but only when it's in between A
and B
, leaving those A
and B
themselves unchanged. This kind of syntax is really hard to parse, because it needs a full-blown Turing machine. It's a whole another story, so I'll end here.
If you try to use "ModelState.Remove" or "ModelState["Prop"].Errors.Clear()" the "ModelState.IsValid" stil returns false.
Why not just removing the default "Required" Annotation from Model and make your custom validation before the "ModelState.IsValid" on Controller 'Post' action? Like this:
if (!String.IsNullOrEmpty(yourClass.Property1) && String.IsNullOrEmpty(yourClass.dependantProperty))
ModelState.AddModelError("dependantProperty", "It´s necessary to select some 'dependant'.");
Tested in Internet Explorer (10 and 11), Edge, Firefox, and Chrome
select::-ms-expand {
display: none;
}
select {
display: inline-block;
box-sizing: border-box;
padding: 0.5em 2em 0.5em 0.5em;
border: 1px solid #eee;
font: inherit;
line-height: inherit;
-webkit-appearance: none;
-moz-appearance: none;
-ms-appearance: none;
appearance: none;
background-repeat: no-repeat;
background-image: linear-gradient(45deg, transparent 50%, currentColor 50%), linear-gradient(135deg, currentColor 50%, transparent 50%);
background-position: right 15px top 1em, right 10px top 1em;
background-size: 5px 5px, 5px 5px;
}
_x000D_
<select name="">
<option value="">Lorem</option>
<option value="">Lorem Ipsum</option>
</select>
<select name="" disabled>
<option value="">Disabled</option>
</select>
<select name="" style="color:red;">
<option value="">Color!</option>
<option value="">Lorem Ipsum</option>
</select>
_x000D_