/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (Stream<String> lines = Files.lines(file.toPath())) {
return lines.count();
}
}
Tested on JDK8_u31. But indeed performance is slow compared to this method:
/**
* Count file rows.
*
* @param file file
* @return file row count
* @throws IOException
*/
public static long getLineCount(File file) throws IOException {
try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(file), 1024)) {
byte[] c = new byte[1024];
boolean empty = true,
lastEmpty = false;
long count = 0;
int read;
while ((read = is.read(c)) != -1) {
for (int i = 0; i < read; i++) {
if (c[i] == '\n') {
count++;
lastEmpty = true;
} else if (lastEmpty) {
lastEmpty = false;
}
}
empty = false;
}
if (!empty) {
if (count == 0) {
count = 1;
} else if (!lastEmpty) {
count++;
}
}
return count;
}
}
Tested and very fast.
Missing the 'implements' keyword in the impl classes might also be the issue
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
Just adding .htaccess in root resolved 404 while refreshing the page in angular 4 apache2.
<IfModule mod_rewrite.c>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html
# to allow html5 state links
RewriteRule ^ index.html [L]
</IfModule>
Since $.browser is deprecated, here is an alternative solution:
/**
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
function getInternetExplorerVersion()
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 8.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
However, the reason that its deprecated is because jQuery wants you to use feature detection instead.
An example:
$("p").html("This frame uses the W3C box model: <span>" +
jQuery.support.boxModel + "</span>");
And last but not least, the most reliable way to check IE versions:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
// UPDATE: Now using Live NodeList idea from @jdalton
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
From R 3.0.0 onwards mean(<data.frame>)
is defunct (and passing a data.frame to mean
will give the error you state)
A data frame is a list of variables of the same number of rows with unique row names, given class "data.frame".
In your case, result has two variables (if your description is correct) . You could obtain the column means by using any of the following
lapply(results, mean, na.rm = TRUE)
sapply(results, mean, na.rm = TRUE)
colMeans(results, na.rm = TRUE)
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
I've been using this in Python 3, including pattern matching on the filename.
from pathlib import Path
def latest_file(path: Path, pattern: str = "*"):
files = path.glob(pattern)
return max(files, key=lambda x: x.stat().st_ctime)
Whatever your separator is in your ls.dat, you can specify it to gnuplot:
set datafile separator "\t"
From Google Play Console, Select your app. Select Store Presence and select Pricing and Distribution from the side menu. There is a toggle switch to Publish and Unpublish app. Select UnPublish and click Submit Update Button in the top right corner.
There's a difference between an empty string (email != "") and NULL. NULL is null and an Empty string is something.
I had the same issue. Try this, it should work!
Right click on MySQL Notifier -> Actions -> Manage Monitored Items
Highlight the MySQL56 entry and click the delete button
PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.
Read this tutorial: How To Synchronize Your PHP and MySQL Timezones
The syntax is
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
It is the container of the Grid
that is imposing on its width. In this case, that's a ListBoxItem
, which is left-aligned by default. You can set it to stretch as follows:
<ListBox>
<!-- other XAML omitted, you just need to add the following bit -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
Happy Coding :)
Sorry, you cannot inherit from multiple classes. You may use interfaces or a combination of one class and interface(s), where interface(s) should follow the class name in the signature.
interface A { }
interface B { }
class Base { }
class AnotherClass { }
Possible ways to inherit:
class SomeClass : A, B { } // from multiple Interface(s)
class SomeClass : Base, B { } // from one Class and Interface(s)
This is not legal:
class SomeClass : Base, AnotherClass { }
html
<input type="hidden" value="hidden value" id='h_v' class='h_v'>
js
var hv = $('#h_v').attr("value");
alert(hv);
As an alternative to rendering a raster image, you can embed a SVG:
https://gist.github.com/CyberShadow/95621a949b07db295000
Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.
Use:
$.ajax({
url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
console.log(data);
}
});
Always remember to use _METHOD=PUT
.
You can just unpack both sets into one like this:
>>> set_1 = {1, 2, 3, 4}
>>> set_2 = {3, 4, 5, 6}
>>> union = {*set_1, *set_2}
>>> union
{1, 2, 3, 4, 5, 6}
The *
unpacks the set. Unpacking is where an iterable (e.g. a set or list) is represented as every item it yields. This means the above example simplifies to {1, 2, 3, 4, 3, 4, 5, 6}
which then simplifies to {1, 2, 3, 4, 5, 6}
because the set can only contain unique items.
Two possible approaches:
I don't think popen()
is part of the C++ standard (it's part of POSIX from memory), but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is ./some_command
).
On the off-chance that there is no popen()
, you can use system("./some_command >/tmp/some_command.out");
, then use the normal I/O functions to process the output file.
The sudo password is stored as a variable called ansible_sudo_pass
.
You can set this variable in a few ways:
Per host, in your inventory hosts file (inventory/<inventoryname>/hosts
)
[server]
10.0.0.0 ansible_sudo_pass=foobar
Per group, in your inventory groups file (inventory/<inventoryname>/groups
)
[server:vars]
ansible_sudo_pass=foobar
Per group, in group vars (group_vars/<groupname>/ansible.yml
)
ansible_sudo_pass: "foobar"
Per group, encrypted (ansible-vault create group_vars/<groupname>/ansible.yml
)
ansible_sudo_pass: "foobar"
You want to put the ISNULL
inside of the COUNT
function, not outside:
Not GOOD: ISNULL(COUNT(field), 0)
GOOD: COUNT(ISNULL(field, 0))
Thanks. Opening the URL connection by passing the Proxy as suggested by NickDK works fine.
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
System properties however doesn't work as I had mentioned earlier.
Thanks again.
Regards, Keya
Add:
for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
result:
The y-values v
are both the x-location and the string values for ax.text
, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i
is the y-location.
Use XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:
long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));
This will print:
Duration: 1:23:45.678
Centering floats is easy. Just use the style for container:
.pagination{ display: table; margin: 0 auto; }
change the margin for floating elements:
.pagination a{ margin: 0 2px; }
or
.pagination a{ margin-left: 3px; }
.pagination a.first{ margin-left: 0; }
and leave the rest as it is.
It's the best solution for me to display things like menus or pagination.
Strengths:
cross-browser for any elements (blocks, list-items etc.)
simplicity
Weaknesses:
@arnaud576875 Using inline-block elements will work great (cross-browser) in this case as pagination contains just anchors (inline), no list-items or divs:
Strengths:
Weknesses:
gaps between inline-block elements - it works the same way as a space between words. It may cause some troubles calculating the width of the container and styling margins. Gaps width isn't constant but it's browser specific (4-5px). To get rid of this gaps I would add to arnaud576875 code (not fully tested):
.pagination{ word-spacing: -1em; }
.pagination a{ word-spacing: .1em; }
it won't work in IE6/7 on block and list-items elements
There is a hasClass function
if($('#popup p').hasClass('filled-text'))
Put from before where, and order_by on last:
$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");
Or try BINARY:
ORDER BY BINARY course_name DESC;
You should add manually on codeigniter for binary sorting.
And set "course_name" character column.
If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.
What type of structure data in courses table?
If you frustrated you can put into array and return using PHP:
Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)
Your array from database as example: $array_db = $result_from_db
:
$final_result = natcasesort($array_db);
print_r($final_result);
It cost me a little bit to understand what was the difference, but this is a simple explanation. master
in your localhost is a branch.
When you clone a repository you fetch the entire repository to you local host. This means that at that time you have an origin/master pointer to HEAD
and master pointing to the same HEAD
.
when you start working and do commits you advance the master pointer to HEAD
+ your commits. But the origin/master pointer is still pointing to what it was when you cloned.
So the difference will be:
git fetch
it will just fetch all the changes in the remote repository (GitHub) and move the origin/master pointer to HEAD
. Meanwhile your local branch master will keep pointing to where it has.git pull
, it will do basically fetch (as explained previously) and merge any new changes to your master branch and move the pointer to HEAD
.note that the span & group are indexed for multi capture groups in a regex
regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
for idx in range(0, 4):
print(match.span(idx), match.group(idx))
SELECT * FROM user_cons_columns WHERE table_name = 'table_name';
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
Don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.
Try something like this (FIDDLE)
// record start time
var startTime = new Date();
...
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
// strip the ms
timeDiff /= 1000;
// get seconds (Original had 'round' which incorrectly counts 0:28, 0:29, 1:30 ... 1:59, 1:0)
var seconds = Math.round(timeDiff % 60);
// remove seconds from the date
timeDiff = Math.floor(timeDiff / 60);
// get minutes
var minutes = Math.round(timeDiff % 60);
// remove minutes from the date
timeDiff = Math.floor(timeDiff / 60);
// get hours
var hours = Math.round(timeDiff % 24);
// remove hours from the date
timeDiff = Math.floor(timeDiff / 24);
// the rest of timeDiff is number of days
var days = timeDiff ;
The following is works best in my opinion:
Get-Item Env:PATH
Get-ChildItem
. There's no hierarchy with environment variables.Set-Item -Path env:SomeVariable -Value "Some Value"
)Get-Item Env:
)I found the syntax odd at first, but things started making more sense after I understood the notion of Providers. Essentially PowerShell let's you navigate disparate components of the system in a way that's analogous to a file system.
What's the point of the trailing colon in Env:
? Try listing all of the "drives" available through Providers like this:
PS> Get-PSDrive
I only see a few results... (Alias, C, Cert, D, Env, Function, HKCU, HKLM, Variable, WSMan). It becomes obvious that Env
is simply another "drive" and the colon is a familiar syntax to anyone who's worked in Windows.
You can navigate the drives and pick out specific values:
Get-ChildItem C:\Windows
Get-Item C:
Get-Item Env:
Get-Item HKLM:
Get-ChildItem HKLM:SYSTEM
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Override
public void onStartOfSpeech() {
}
@Override
public void onSpeechRmsChanged(float value) {
}
@Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
@Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
Hope this will help someone in future.
This is a common code adapted from another examples:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.google.com/")
#open tab
# ... take the code from the options below
# Load a page
driver.get('http://bings.com')
# Make the tests...
# close the tab
driver.quit()
the possible ways were:
Sending <CTRL> + <T>
to one element
#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
Sending <CTRL> + <T>
via Action chains
ActionChains(driver).key_down(Keys.CONTROL).send_keys('t').key_up(Keys.CONTROL).perform()
Execute a javascript snippet
driver.execute_script('''window.open("http://bings.com","_blank");''')
In order to achieve this you need to ensure that the preferences browser.link.open_newwindow and browser.link.open_newwindow.restriction are properly set. The default values in the last versions are ok, otherwise you supposedly need:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.link.open_newwindow", 3)
fp.set_preference("browser.link.open_newwindow.restriction", 2)
driver = webdriver.Firefox(browser_profile=fp)
the problem is that those preferences preset to other values and are frozen at least selenium 3.4.0. When you use the profile to set them with the java binding there comes an exception and with the python binding the new values are ignored.
In Java there is a way to set those preferences without specifying a profile object when talking to geckodriver, but it seem to be not implemented yet in the python binding:
FirefoxOptions options = new FirefoxOptions().setProfile(fp);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 2);
FirefoxDriver driver = new FirefoxDriver(options);
The third option did stop working for python in selenium 3.4.0.
The first two options also did seem to stop working in selenium 3.4.0. They do depend on sending CTRL key event to an element. At first glance it seem that is a problem of the CTRL key, but it is failing because of the new multiprocess feature of Firefox. It might be that this new architecture impose new ways of doing that, or maybe is a temporary implementation problem. Anyway we can disable it via:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.tabs.remote.autostart", False)
fp.set_preference("browser.tabs.remote.autostart.1", False)
fp.set_preference("browser.tabs.remote.autostart.2", False)
driver = webdriver.Firefox(browser_profile=fp)
... and then you can use successfully the first way.
try this,
package example.txtRead;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class txtRead extends Activity {
String labels="caption";
String text="";
String[] s;
private Vector<String> wordss;
int j=0;
private StringTokenizer tokenizer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wordss = new Vector<String>();
TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.toc);
// InputStream inputStream = getResources().openRawResource(R.raw.internals);
System.out.println(inputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
We can achieve this other way despite of directly calling event with <select>
.
JS part:
$("#sort").change(function(){
alert('Selected value: ' + $(this).val());
});
HTML part:
<select id="sort">
<option value="1">View All</option>
<option value="2">Ready for Review</option>
<option value="3">Registration Date</option>
<option value="4">Last Modified</option>
<option value="5">Ranking</option>
<option value="6">Reviewed</option>
</select>
In older versions of jquery you'll have to do it the "javascript way" using settimeout
setTimeout( function(){$('div').hide();} , 4000);
or
setTimeout( "$('div').hide();", 4000);
Recently with jquery 1.4 this solution has been added:
$("div").delay(4000).hide();
Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.
http://www.useragentstring.com/
Visit that page, it'll give you a good explanation of each element of your user agent.
Mozilla:
MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore
For a more cross-browser solution you could style all inputs the way you want the non-typed, text, and password then another style the overrides that style for radios, checkboxes, etc.
input { border:solid 1px red; }
input[type=radio],
input[type=checkbox],
input[type=submit],
input[type=reset],
input[type=file]
{ border:none; }
- Or -
could whatever part of your code that is generating the non-typed inputs give them a class like .no-type
or simply not output at all? Additionally this type of selection could be done with jQuery.
String s = "0.01";
double d = Double.parseDouble(s);
int i = (int) d;
The reason for the exception is that an integer does not hold rational numbers (= basically fractions). So, trying to parse 0.3
to a int is nonsense.
A double
or a float
datatype can hold rational numbers.
The way Java casts a double
to an int
is done by removing the part after the decimal separator by rounding towards zero.
int i = (int) 0.9999;
i
will be zero.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
Rotate 90 clockwise:
ffmpeg -i in.mov -vf "transpose=1" out.mov
For the transpose parameter you can pass:
0 = 90CounterCLockwise and Vertical Flip (default)
1 = 90Clockwise
2 = 90CounterClockwise
3 = 90Clockwise and Vertical Flip
Use -vf "transpose=2,transpose=2"
for 180 degrees.
Make sure you use a recent ffmpeg version from here (a static build will work fine).
Note that this will re-encode the audio and video parts. You can usually copy the audio without touching it, by using -c:a copy
. To change the video quality, set the bitrate (for example with -b:v 1M
) or have a look at the H.264 encoding guide if you want VBR options.
A solution is also to use this convenience script.
Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
based on drew010 example I made a working example for easy understanding.
imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data
function imagesaver($image_data){
list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating
if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
$fullname = time().$type;
if(file_put_contents($fullname, $data)){
$result = $fullname;
}else{
$result = "error";
}
/* it will return image name if image is saved successfully
or it will return error on failing to save image. */
return $result;
}
I can think of An Array inside an Array or a Guava's MultiMap?
e.g.
ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();
This seems to be working for me :
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (before - count == 1) {
onBackSpace();
} else if (s.subSequence(start, start + count).toString().equals("\n")) {
onNewLine();
}
}
The std::string::append()
method expects its argument to be a NULL terminated string (char*
).
There are several approaches for producing a string
containg an int
:
#include <sstream>
std::ostringstream s;
s << "select logged from login where id = " << ClientID;
std::string query(s.str());
std::to_string
(C++11)
std::string query("select logged from login where id = " +
std::to_string(ClientID));
#include <boost/lexical_cast.hpp>
std::string query("select logged from login where id = " +
boost::lexical_cast<std::string>(ClientID));
(Reputation not high enough to comment) The second part of John Petrone's answer works - no query needed. It will delete the type and all documents contained in that type, but that can just be re-created whenever you index a new document to that type.
Just to clarify:
$ curl -XDELETE 'http://localhost:9200/twitter/tweet'
Note: this does delete the mapping! But as mentioned before, it can be easily re-mapped by creating a new document.
UPDATE R
SET R.status = '0'
FROM dbo.ProductReviews AS R
INNER JOIN dbo.products AS P
ON R.pid = P.id
WHERE R.id = '17190'
AND P.shopkeeper = '89137';
Hi i got a tricky solution, which works only on new browsers:
just open a websocket to your server, when the user closes the window, the onclose event will be fired
Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.
Run script.
Alt+PgDn - puts you in Script Output panel.
Ctrl+Shift+D - clears panel.
Alt+PgUp - puts you back in editor panel.
$ echo -n 'Hello world!' | hd
00000000 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 |Hello world!|
0000000c
You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).
But, try this:
a = [0 for x in range(N)] # N = size of list you want
a[i] = 5 # as long as i < N, you're okay
For lists of other types, use something besides 0. None
is often a good choice as well.
The solution of creating a new HTML file with HTML (Web Forms) Designer worked for that file but not for other, individual HTML files that I wanted to edit.
I did find the Open With option in the Open File dialogue and was able to select the HTML (Web Forms) Editor there. Having clicked the "Set as Default" option in that window, VS then remembered to use that editor when I opened other HTML files.
You could also try string addition:
print " "+'"'+'a word that needs quotation marks'+'"'
You have to edit postgresql.conf file and change line with 'listen_addresses'.
This file you can find in the /etc/postgresql/9.3/main
directory.
Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:
listen_addresses = '*'
Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:
host all all 192.168.1.0/24 md5
Please, read comments in this file...
EDIT:
After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.
EDIT2: Highlited configuration files.
What you are looking for is called Restricted Shell. Bash provides such a mode in which users can only execute commands present in their home directories (and they cannot move to other directories), which might be good enough for you.
I've found this thread to be very illustrative, if a bit dated.
I had a CASE statement with WHEN column = 'sometext & more text' THEN ....
I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...
you could also use WHEN column LIKE 'sometext _ more text' THEN ...
(_ is the wildcard for a single character)
I figured out such data design:
Main sheet: Column A: Pump codes (numbers)
Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'
=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)
Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.
Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B
=INDIRECT("Ruhrpumpen!A"&$B2)
Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:
=INDIRECT("Ruhrpumpen!B"&$B2)
Sheet 'Ruhrpumpen':
Column A: some data about a certain pump
Column B: some more data
Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.
Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls
scan
can read from a web page automatically; you don't necessarily have to mess with connections.
Java 1.8 version has nice update for data time API.
Here is snippet of code:
LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
System.out.println("last april day: " + lastAprilDay);
LocalDate firstMay = lastAprilDay.plusDays(1);
System.out.println("should be first may day: " + firstMay);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
String formatDate = formatter.format(firstMay);
System.out.println("formatted date: " + formatDate);
Output:
last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01
For more info see Java documentations to this classes:
Yet another way to do this:
(Get-Date).AddDays(-1).Date.AddHours(22)
show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| datapass_schema |
| mysql |
| test |
+--------------------+
4 rows in set (0.05 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables
-> ;
+---------------------------+
| Tables_in_mysql |
+---------------------------+
| columns_priv |
| db |
| event |
| func |
| general_log |
| help_category |
| help_keyword |
| help_relation |
| help_topic |
| host |
| ndb_binlog_index |
| plugin |
| proc |
| procs_priv |
| servers |
| slow_log |
| tables_priv |
| time_zone |
| time_zone_leap_second |
| time_zone_name |
| time_zone_transition |
| time_zone_transition_type |
| user |
+---------------------------+
23 rows in set (0.00 sec)
mysql> create user m identified by 'm';
Query OK, 0 rows affected (0.02 sec)
check for the database mysql and table user as shown above if that dosent work, your mysql installation is not proper.
use the below command as mention in other post to install tables again
mysql_install_db
Here's a LESS mixin for transitioning two properties at once:
.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
-webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}
I had the same problem and just solved it. I had posted my own question on stackoverflow:
Can't PUT to my IHttpHandler, GET works fine
The solution was to set runManagedModulesForWebDavRequests to true in the modules element. My guess is that once you install WebDAV then all PUT requests are associated with it. If you need the PUT to go to your handler, you need to remove the WebDAV module and set this attribute to true.
<modules runManagedModulesForWebDavRequests="true">
...
</modules>
So if you're running into the problem when you use the PUT verb and you have installed WebDAV then hopefully this solution will fix your problem.
<?php
$a = 12345;
$b = bcdiv($a, 3);
?>
MySQL (it's an interview from Oracle)
> SELECT 12345 DIV 3;
a:= 12345;
b:= a div 3;
x86-64 assembly language:
mov r8, 3
xor rdx, rdx
mov rax, 12345
idiv r8
This is quite simple really.
-> This is centered Text <-
So taking that in mind you can apply this to the img syntax.
->![alt text](/link/to/img)<-
if you have autoplay property in the iframe src it wont help to reload the src attr/prop so you have to replace the autoplay=1 to autoplay=0
var stopVideo = function(player) {
var vidSrc = player.prop('src').replace('autoplay=1','autoplay=0');
player.prop('src', vidSrc);
};
stopVideo($('#video'));
If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:
>>> import array
>>> a1 = array.array('B', 'Hello, World!')
>>> a1
array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
>>> a2 = array.array('B', ('secret'*3))
>>> for i in range(len(a1)):
a1[i] ^= a2[i]
>>> a1.tostring()
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
I've achieved the same thing before by using subqueries. So if your original table was called StoreCountsByWeek, and you had a separate table that listed the Store IDs, then it would look like this:
SELECT StoreID,
Week1=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=1),
Week2=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=2),
Week3=(SELECT ISNULL(SUM(xCount),0) FROM StoreCountsByWeek WHERE StoreCountsByWeek.StoreID=Store.StoreID AND Week=3)
FROM Store
ORDER BY StoreID
One advantage to this method is that the syntax is more clear and it makes it easier to join to other tables to pull other fields into the results too.
My anecdotal results are that running this query over a couple of thousand rows completed in less than one second, and I actually had 7 subqueries. But as noted in the comments, it is more computationally expensive to do it this way, so be careful about using this method if you expect it to run on large amounts of data .
SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
and idCustomer is not null
Make sure your list parameter does not contain null values.
Here's an explanation:
WHERE field1 NOT IN (1, 2, 3, null)
is the same as:
WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.
Did you try export
directive of Make itself (assuming that you use GNU Make)?
export PATH := bin:$(PATH)
test all:
x
Also, there is a bug in you example:
test all:
PATH=bin:${PATH}
@echo $(PATH)
x
First, the value being echo
ed is an expansion of PATH
variable performed by Make, not the shell. If it prints the expected value then, I guess, you've set PATH
variable somewhere earlier in your Makefile, or in a shell that invoked Make. To prevent such behavior you should escape dollars:
test all:
PATH=bin:$$PATH
@echo $$PATH
x
Second, in any case this won't work because Make executes each line of the recipe in a separate shell. This can be changed by writing the recipe in a single line:
test all:
export PATH=bin:$$PATH; echo $$PATH; x
I just fixed it by restarting / starting oracleService in services
You can find clear difference between interface and abstract class.
Interface
Abstract class
Abstract class contains abstract and non-abstract methods.
Does not force users to implement all methods when inherited the abstract class.
Contains all kinds of variables including primitive and non-primitive
Declare using abstract keyword.
Methods and members of an abstract class can be defined with any visibility.
A child class can only extend a single class (abstract or concrete).
Just add these lines of code to your activity/fragment java file:
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
Finally, this is what I did:
private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}
...
File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();
I think I observed a similar problem: some processes started, seemed to run successfully but never completed. The function waitFor() was waiting forever except if I killed the process in Task Manager.
However, everything worked well in cases the length of the command line was 127 characters or shorter. If long file names are inevitable you may want to use environmental variables, which may allow you keeping the command line string short. You can generate a batch file (using FileWriter) in which you set your environmental variables before calling the program you actually want to run.
The content of such a batch could look like:
set INPUTFILE="C:\Directory 0\Subdirectory 1\AnyFileName"
set OUTPUTFILE="C:\Directory 2\Subdirectory 3\AnotherFileName"
set MYPROG="C:\Directory 4\Subdirectory 5\ExecutableFileName.exe"
%MYPROG% %INPUTFILE% %OUTPUTFILE%
Last step is running this batch file using Runtime.
When you use a command substitution (i.e., the $(...)
construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.
Your variable e
is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:
myfunc() {
echo "Hello"
}
var="$(myfunc)"
echo "$var"
The above outputs:
Hello
For a numerical value in the range of 0 through 255, you can use return
to pass the number as the exit status:
mysecondfunc() {
echo "Hello"
return 4
}
var="$(mysecondfunc)"
num_var=$?
echo "$var - num is $num_var"
This outputs:
Hello - num is 4
@Jon: Jon, are you saying using multiple where clauses e.g.
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX"
where r.Field<string>("UserName") != "YYYY"
select r;
is more restictive than using
var query = from r in tempData.AsEnumerable()
where r.Field<string>("UserName") != "XXXX" && r.Field<string>("UserName") != "YYYY"
select r;
I think they are equivalent as far as the result goes.
However, I haven't tested, if using multiple where in the first example cause in 2 subqueries, i.e. .Where(r=>r.UserName!="XXXX").Where(r=>r.UserName!="YYYY)
or the LINQ translator is smart enought to execute .Where(r=>r.UserName!="XXXX" && r.UsernName!="YYYY")
Sometimes matplotlib requires range(len(y))
, e.g., while y=array([1,2,5,6])
, plot(y)
works fine, scatter(y)
does not. One has to write scatter(range(len(y)),y)
. (Personally, I think this is a bug in scatter
; plot
and its friends scatter
and stem
should use the same calling sequences as much as possible.)
To make it a bit more user-friendly:
After you've unpacked it, go into the directory, and run bin/pycharm.sh
.
Once it opens, it either offers you to create a desktop entry, or if it doesn't, you can ask it to do so by going to the Tools menu and selecting Create Desktop Entry...
Then close PyCharm, and in the future you can just click on the created menu entry. (or copy it onto your Desktop)
To answer the specifics between Run and Run in Terminal: It's essentially the same, but "Run in Terminal" actually opens a terminal window first and shows you console output of the program. Chances are you don't want that :)
(Unless you are trying to debug an application, you usually do not need to see the output of it.)
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx
You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.
More from the link (fixed up alot heh):
Socket s;
IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;
if (remoteIpEndPoint != null)
{
// Using the RemoteEndPoint property.
Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}
if (localIpEndPoint != null)
{
// Using the LocalEndPoint property.
Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}
Arrays are different than ArrayList
s, on which you could call add
. You'll need an index first. Declare i
before the for
loop. Then you can use an array access expression to assign the element to the array.
num[i] = s;
i++;
In charSequence you don't have very useful methods which are available for String. If you don't want to look in the documentation, type: obj. and str.
and see what methods your compilator offers you. That's the basic difference for me.
After i iterations the first i elements are ordered.
In each iteration the next element is bubbled through the sorted section until it reaches the right spot:
sorted | unsorted
1 3 5 8 | 4 6 7 9 2
1 3 4 5 8 | 6 7 9 2
The 4 is bubbled into the sorted section
Pseudocode:
for i in 1 to n
for j in i downto 2
if array[j - 1] > array[j]
swap(array[j - 1], array[j])
else
break
After i iterations the last i elements are the biggest, and ordered.
In each iteration, sift through the unsorted section to find the maximum.
unsorted | biggest
3 1 5 4 2 | 6 7 8 9
1 3 4 2 | 5 6 7 8 9
The 5 is bubbled out of the unsorted section
Pseudocode:
for i in 1 to n
for j in 1 to n - i
if array[j] > array[j + 1]
swap(array[j], array[j + 1])
Note that typical implementations terminate early if no swaps are made during one of the iterations of the outer loop (since that means the array is sorted).
In insertion sort elements are bubbled into the sorted section, while in bubble sort the maximums are bubbled out of the unsorted section.
I wrote up some code that will sort a table by a row, assuming only one <tbody>
and cells don't have a colspan.
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
// sortTable(tableNode, columId, false);
If you don't want to make the assumptions above, you'd need to consider how you want to behave in each circumstance. (e.g. put everything into one <tbody>
or add up all the preceeding colspan values, etc.)
You could then attach this to each of your tables, e.g. assuming titles are in <thead>
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
and then invoking makeAllSortable
onload.
Example fiddle of it working on a table.
You can reduce the per-call overhead by retaining the padding data, rather than rebuilding it every time:
public class RightPadder {
private int length;
private String padding;
public RightPadder(int length, String pad) {
this.length = length;
StringBuilder sb = new StringBuilder(pad);
while (sb.length() < length) {
sb.append(sb);
}
padding = sb.toString();
}
public String pad(String s) {
return (s.length() < length ? s + padding : s).substring(0, length);
}
}
As an alternative, you can make the result length a parameter to the pad(...)
method. In that case do the adjustment of the hidden padding in that method instead of in the constructor.
(Hint: For extra credit, make it thread-safe! ;-)
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
@ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
Instead of VALUES
part of INSERT
query, just use SELECT
query as below.
INSERT INTO table1 ( column1 , 2, 3... )
SELECT col1, 2, 3... FROM table2
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
If you just have the xml
file of the color scheme you can:
Go to Preferences
-> Editor
-> Color and Fonts
and use the Import
button.
If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.
The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):
CREATE TABLE shirts (
name VARCHAR(40),
size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);
But, I always say that explaining the query like this:
EXPLAIN SELECT * FROM shirts WHERE size='medium';
will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.
feel free to use this tool https://github.com/rooty0/ffmpeg_video_cutter I wrote awhile ago Pretty much that's cli front-end for ffmpeg... you just need to create a yaml what you want to cut out... something like this
cut_method: delete # we're going to delete following video fragments from a video
timeframe:
- from: start # waiting for people to join the conference
to: 4m
- from: 10m11s # awkward silence
to: 15m50s
- from: 30m5s # Off-Topic Discussion
to: end
and then just run a tool to get result
Add this to your Activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// some your code
}
Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:
step1: open terminal and edit .bashrc using the following command.
vi .bashrc
step2: add the following line at the end of the .bashrc file :
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
step3: source .bashrc in the root (home) directory by doing:
/rootfolder:~$ source .bashrc
Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)
Call .get()
at the very end to turn the resulting jQuery object into a true array.
$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
}).get(); // <----
console.log(searchIDs);
});
Per the documentation:
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.
As far as I know, and I cant verify it now, you cannot stop remote services with the Stop-Service cmdlet or with .Net, it is not supported.
Yes it works, but it stopes the service on your local machine, not on the remote computer.
Now, if the above is correct, without remoting or wmi enabled, you could set a scheduled job on the remote system, using AT, that runs Stop-Service locally.
contentType
option to false
is used for multipart/form-data
forms that pass files.
When one sets the contentType
option to false
, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Use jQuery's .serialize()
method which creates a text string in standard URL-encoded notation.
You need to pass un-encoded data when using contentType: false
.
Try using new FormData
instead of .serialize():
var formData = new FormData($(this)[0]);
See for yourself the difference of how your formData is passed to your php page by using console.log()
.
var formData = new FormData($(this)[0]);
console.log(formData);
var formDataSerialized = $(this).serialize();
console.log(formDataSerialized);
The modern answer:
if your app support split view on iPad, this problem becomes a little complicated. You need window's size, not the screen's, which may contain 2 apps. Window's size may also vary while running.
Use app's main window's size:
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
Note: The method above may get wrong value before window becoming key window when starting up. if you only need width, method below is very recommended:
UIApplication.shared.statusBarFrame.width
The old solution using UIScreen.main.bounds
will return the device's bounds. If your app running in split view mode, it get the wrong dimensions.
self.view.window
in the hottest answer may get wrong size when app contains 2 or more windows and the window have small size.
For eclipselink, only the following dependency is sufficient to generate metamodel. Nothing else is needed.
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.5.1</version>
<scope>provided</scope>
</dependency>
it will helps you use your object instant of the frame
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
This works for me:
// Document click blurer
$(document).on('mousedown', '*:not(input,textarea)', function() {
try {
var $a = $(document.activeElement).prop("disabled", true);
setTimeout(function() {
$a.prop("disabled", false);
});
} catch (ex) {}
});
Here is a simple and very inelegant & potentially dangerous way.
I'm guessing that you are not doing log backups. (Which truncate the log). My advice is to change recovery model from full to simple. This will prevent log bloat.
You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw()
, ensure that you binding the parameters.
Try the following:
$array = array(1,2,3); $query = DB::table('offers'); $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used'); $query->leftJoin('user_offer_collection', function ($join) use ($array) { $join->on('user_offer_collection.offers_id', '=', 'offers.id') ->whereIn('user_offer_collection.user_id', $array); }); $query->get();
LinearLayout
means you can align views one by one (vertically/ horizontally).
RelativeLayout
means based on relation of views from its parents and other views.
ConstraintLayout
is similar to a RelativeLayout in that it uses relations to position and size widgets, but has additional flexibility and is easier to use in the Layout Editor.
WebView
to load html, static or dynamic pages.
FrameLayout
to load child one above another, like cards inside a frame, we can place one above another or anywhere inside the frame.
deprecated - AbsoluteLayout
means you have to give exact position where the view should be.
For more information, please check this address https://developer.android.com/guide/topics/ui/declaring-layout#CommonLayouts
i had the same problem, i fixed it by removing the transform:translateY
CSS i placed on the footer
of the page.
Will be more portable in case of extending to other alphabets:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
##If i want to wait for some response from server or any action we use setTimeOut.
functionOne =function(){
console.info("First");
setTimeout(()=>{
console.info("After timeOut 1");
},5000);
console.info("only setTimeOut() inside code waiting..");
}
functionTwo =function(){
console.info("second");
}
functionOne();
functionTwo();
## So here console.info("After timeOut 1"); will be executed after time elapsed.
Output:
*******************************************************************************
First
only setTimeOut() inside code waiting..
second
undefined
After timeOut 1 // executed after time elapsed.
Your meta tag should look like this:
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
And it has to be placed on the page you want to share (this is unclear in your question).
If you have shared the page before the image (or the meta tag) was present, then it is possible, that facebook has the page in its "memory" without an image. In this case simply enter the URL of your page in the debug tool http://developers.facebook.com/tools/debug. After that, the image should be present when the page is shared the next time.
public List<Student> findStudentByReports(Date startDate, Date endDate) {
System.out.println("call findStudentMethd******************with this pattern"
+ startDate
+ endDate
+ "*********************************************");
return em
.createQuery(
"' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
+ "'")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}
I have used pdflib for this.
p = new pdflib();
/* Open the input PDF */
indoc = p.open_pdi_document("myTestFile.pdf", "");
pageCount = (int) p.pcos_get_number(indoc, "length:pages");
I use the SubInACL utility for this. For example, if I wanted to give the user job on the computer VMX001 the ability to start and stop the World Wide Web Publishing Service (also know as w3svc), I would issue the following command as an Administrator:
subinacl.exe /service w3svc /grant=VMX001\job=PTO
The permissions you can grant are defined as follows (list taken from here):
F : Full Control
R : Generic Read
W : Generic Write
X : Generic eXecute
L : Read controL
Q : Query Service Configuration
S : Query Service Status
E : Enumerate Dependent Services
C : Service Change Configuration
T : Start Service
O : Stop Service
P : Pause/Continue Service
I : Interrogate Service
U : Service User-Defined Control Commands
So, by specifying PTO, I am entitling the job user to Pause/Continue, Start, and Stop the w3svc service.
cat script.sh
var1=$1
var2=$2
if [ "$#" -eq 2 ]
then
if [ -d $var1 ]
then
echo directory ${var1} exist
else
echo Directory ${var1} Does not exists
fi
if [ -d $var2 ]
then
echo directory ${var2} exist
else
echo Directory ${var2} Does not exists
fi
else
echo "Arguments are not equals to 2"
exit 1
fi
execute it like below -
./script.sh directory1 directory2
Output will be like -
directory1 exit
directory2 Does not exists
I believe you need to create a file called __init__.py
in the Models directory so that python treats it as a module.
Then you can do:
from Models.user import User
You can include code in the __init__.py
(for instance initialization code that a few different classes need) or leave it blank. But it must be there.
I had a similar issue and I tried all the workarounds above but none of them worked for me ( I was using special characters (like '@' symbol) in my password and I also needed to add domain name).
Apart from that I was bit apprehensive to add my password as plain text. It turned-out the easiest solution to overcome all these challenges was to use some sort of reverse proxy (like Fiddler).
I have already detailed the configuration steps in this answer in SO.
==
will still test object equality. It is easy to be fooled, however:
Integer a = 10;
Integer b = 10;
System.out.println(a == b); //prints true
Integer c = new Integer(10);
Integer d = new Integer(10);
System.out.println(c == d); //prints false
Your examples with inequalities will work since they are not defined on Objects. However, with the ==
comparison, object equality will still be checked. In this case, when you initialize the objects from a boxed primitive, the same object is used (for both a and b). This is an okay optimization since the primitive box classes are immutable.
You probably included your JavaScript before the HTML: example.
You should either execute your JavaScript when the window loads (or better, when the DOM is fully loaded), or you should include your JavaScript after your HTML: example.
The scope of a variable is always the block it is inside. For example if you do something like
if(...)
{
int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
int y = 8; //y is created
} //y leaves scope, since the block ends.
cout << y << endl; //Gives error since y is not defined.
The solution is to define y outside of the if blocks
int y; //y is created
if(...)
{
y = 5;
}
else
{
y = 8;
}
cout << y << endl; //Ok
In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:
//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
int y, c;
int d=date;
if (month==1||month==2)
{
y=((year-1)%100);
c=(year-1)/100;
}
else
{
y=year%100;
c=year/100;
}
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}
X
is a dataframe and can't be accessed via slice terminology like X[:, 3]
. You must access via iloc
or X.values
. However, the way you constructed X
made it a copy... so. I'd use values
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
# dataset = pd.read_csv('50_Startups.csv')
dataset = pd.DataFrame(np.random.rand(10, 10))
y=dataset.iloc[:, 4]
X=dataset.iloc[:, 0:4]
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X = LabelEncoder()
# I changed this line
X.values[:, 3] = labelencoder_X.fit_transform(X.values[:, 3])
None of solutions that I found on the Internet worked, but a modified version of Peter Kriens's answer seems to do the job.
First find your Java folder by running /usr/libexec/java_home
. For me it was the 1.6.0.jdk
version. Then go to its lib/security
subfolder (for me /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security
).
Then delete the cacerts
file if there is one already and search for one on the system with sudo find / -name "cacerts"
. It found multiple items for me, in versions of Xcode or other applications that I had installed, but also at /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts
which I chose.
Use that file and make a symbolic link to it (while inside the Java folder from before), sudo ln -fsh "/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts"
, and it should work.
I have both - Java from Apple's 2017-001 download (https://support.apple.com/kb/dl1572 - I assume that's where the correct certificates are from) and Oracle's one installed on Mac OS X v10.12 (Sierra).
In jQuery I mostly use:
$("#element").trigger("change");
Implement both deprecated and non-deprecated methods like below. First one is to handle API level 21 and higher, second one is handle lower than API level 21
webViewClient = object : WebViewClient() {
.
.
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
parseUri(request?.url)
return true
}
@SuppressWarnings("deprecation")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
parseUri(Uri.parse(url))
return true
}
}
This library makes it simple.
Just Call:
PickImageDialog.on(MainActivity.this, new PickSetup(BuildConfig.APPLICATION_ID));
Then make your Activity implement IPickResult and override this below method.
@Override
public void onPickResult(PickResult r) {
if (r.getError() == null) {
imageView.setImageBitmap(r.getBitmap());
//or
imageView.setImageURI(r.getUri());
} else {
//Handle possible errors
//TODO: do what you have to do with r.getError();
}
}
pull
:adb pull "/sdcard/Folder1"
Output:
adb pull "/sdcard/Folder1"
pull: building file list...
pull: /sdcard/Folder1/image1.jpg -> ./image1.jpg
pull: /sdcard/Folder1/image2.jpg -> ./image2.jpg
pull: /sdcard/Folder1/image3.jpg -> ./image3.jpg
3 files pulled. 0 files skipped.
find
from BusyBox
:adb shell find "/sdcard/Folder1" -iname "*.jpg" | tr -d '\015' | while read line; do adb pull "$line"; done;
Here is an explanation:
adb shell find "/sdcard/Folder1" - use the find command, use the top folder
-iname "*.jpg" - filter the output to only *.jpg files
| - passes data(output) from one command to another
tr -d '\015' - explained here: http://stackoverflow.com/questions/9664086/bash-is-removing-commands-in-while
while read line; - while loop to read input of previous commands
do adb pull "$line"; done; - pull the files into the current running directory, finish. The quotation marks around $line are required to work with filenames containing spaces.
The scripts will start in the top folder and recursively go down and find all the "*.jpg" files and pull them from your phone to the current directory.
HTML - InputFile component can be hide by writing some css. Here I am adding an icon which overrides inputfile component.
<label class="custom-file-upload">
<InputFile OnChange="HandleFileSelected" />
<i class="fa fa-cloud-upload"></i> Upload
</label>
css-
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
}
</style>
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC
Here, i am using link in the form of button for CANCEL operation.
<button><a href="main.html">cancel</a></button>
taskAffinity name must have at least one '.' separator
After some tries, these are the samples I am using in order to connect:
Specifying the username and the password:
sqlcmd -S 211.11.111.111 -U NotSA -P NotTheSaPassword
Specifying the DB as well:
sqlcmd -S 211.11.111.111 -d SomeSpecificDatabase -U NotSA -P NotTheSaPassword
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.
Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.
If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.
There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd
on Mac and ifconfig
works differently.
The following table is useful for knowing the various unix shells.
sh The original Bourne shell Present on every unix system
ksh Original Korn shell Richer shell programming environment than sh
csh Original C-shell C-like syntax; early versions buggy
tcsh Enhanced C-shell User-friendly and less buggy csh implementation
bash GNU Bourne-again shell Enhanced and free sh implementation
zsh Z shell Enhanced, user-friendly ksh-like shell
You may also find these guides helpful:
http://homepage.mac.com/rgriff/files/TerminalBasics.pdf
http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html
On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile
on OSX) file with aliases, some examples below.
I now placed all my aliases in a separate .bash_aliases file and include it with:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
in the .bashrc or .bash_profile file.
Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto
. The first time I did this (without knowing) I redefined ls
to be invalid which was a bit alarming until I removed --auto-color
!
You may also find https://unix.stackexchange.com/q/127799/10043 useful
# ~/.bash_aliases
# ls variants
#alias l='ls -CF'
alias la='ls -A'
alias l='ls -alFtr'
alias lsd='ls -d .*'
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i'
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed'
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status'
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'
As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).
I have shortened your slice to make it...shorter...:
func GetLetterGoodness() []float32 {
return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}
For me general solution :)
@{
var selectedCity = Model.Cities.Where(k => k.Id == Model.Addres.CityId).FirstOrDefault();
if (selectedCity != null)
{
@Html.DropDownListFor(model => model.Addres.CityId, new SelectList(Model.Cities, "Id", "Name", selectedCity.Id), new { @class = "form-control" })
}
else
{
@Html.DropDownListFor(model => model.Cities, new SelectList(Model.Cities, "Id", "Name", "1"), new { @class = "form-control" })
}
}
example: int array[10]; memset(array,-1, 10 *sizeof(int));
Equivalent to "find and replace." Don't overthink it.
Try it with one:
library(tidyverse)
df <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))
df %>%
mutate(var1 = str_replace(var1, " ", ""))
#> name var1 var2
#> 1 a <2 <3
#> 2 a <2 <3
#> 3 a <2 <3
#> 4 b <2 <3
#> 5 b <2 <3
#> 6 b <2 <3
#> 7 c <2 <3
#> 8 c <2 <3
#> 9 c <2 <3
Apply to all
df %>%
mutate_all(funs(str_replace(., " ", "")))
#> name var1 var2
#> 1 a <2 <3
#> 2 a <2 <3
#> 3 a <2 <3
#> 4 b <2 <3
#> 5 b <2 <3
#> 6 b <2 <3
#> 7 c <2 <3
#> 8 c <2 <3
#> 9 c <2 <3
If the extra space was produced by uniting columns, think about making str_trim
part of your workflow.
Created on 2018-03-11 by the reprex package (v0.2.0).
return x2 >= y1 && x1 <= y2;
see http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.switch%28VS.71%29.aspx
switch statement basically a look up table it have options which are known and if statement is like boolean type. according to me switch and if-else are same but for logic switch can help more better. while if-else helps to understand in reading also.
Use:
ImageView image = (ImageView) findViewById(R.id.image);
image.setAlpha(150); // Value: [0-255]. Where 0 is fully transparent
// and 255 is fully opaque. Set the value according
// to your choice, and you can also use seekbar to
// maintain the transparency.
You can't remove API functions without breaking the API. If you would, many applications would no longer compile or run at all.
This is the reason that one reference gives:
Reading a line that overflows the array pointed to by s results in undefined behavior. The use of fgets() is recommended.
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
Using windows authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01;integratedSecurity=true";
Using SQL authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01";
Say that you want to count the rows in an existing table:
Use mysql_result with only one parameter set to "0"
Like this:
$string = mysql_result(
mysql_query("SELECT COUNT(*) FROM database_name.table_name ")
,0);
Put ( ` ) around database_name and table_name
var_dump($string);
// string(1) "5" //if it only has 5 records in the table
Note: if you query for something else like
SELECT * FROM database.table LIMIT 1
and the table has more than one column then you WILL NOT get an array()
in your var_dump you will get the first column only
It could be a case-sensitivity issue. Normally tables and columns are not case sensitive, but they will be if you use quotation marks. For example:
create table bad_design("goodLuckSelectingThisColumn" number);
Adding to the correct answers above, the problem still might occur due to library nesting. In this case, try as the example below:
compile 'com.android.support:support-v4:20.+'
compile ('com.github.chrisbanes.actionbarpulltorefresh:extra-abs:+') { // example
exclude group: 'com.android.support', module:'support-v4'
exclude group: 'com.android.support', module:'appcompat-v7'
}
Here is a one liner that does this, just replace username with the username you want to kill things for. Don't even think on putting root there!
pkill -9 -u `id -u username`
Note: if you want to be nice remove -9, but it will not kill all kinds of processes.
Here is the complete code, import pfx, add iis website, add ssl binding:
$SiteName = "MySite"
$HostName = "localhost"
$CertificatePassword = '1234'
$SiteFolder = Join-Path -Path 'C:\inetpub\wwwroot' -ChildPath $SiteName
$certPath = 'c:\cert.pfx'
Write-Host 'Import pfx certificate' $certPath
$certRootStore = “LocalMachine”
$certStore = "My"
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$CertificatePassword,"Exportable,PersistKeySet")
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.Open('ReadWrite')
$store.Add($pfx)
$store.Close()
$certThumbprint = $pfx.Thumbprint
Write-Host 'Add website' $SiteName
New-WebSite -Name $SiteName -PhysicalPath $SiteFolder -Force
$IISSite = "IIS:\Sites\$SiteName"
Set-ItemProperty $IISSite -name Bindings -value @{protocol="https";bindingInformation="*:443:$HostName"}
if($applicationPool) { Set-ItemProperty $IISSite -name ApplicationPool -value $IISApplicationPool }
Write-Host 'Bind certificate with Thumbprint' $certThumbprint
$obj = get-webconfiguration "//sites/site[@name='$SiteName']"
$binding = $obj.bindings.Collection[0]
$method = $binding.Methods["AddSslCertificate"]
$methodInstance = $method.CreateInstance()
$methodInstance.Input.SetAttributeValue("certificateHash", $certThumbprint)
$methodInstance.Input.SetAttributeValue("certificateStoreName", $certStore)
$methodInstance.Execute()
SOLUTION After all this time, I managed to resolve the problem.
In Module: UserForms(Name).Userform_Initialize
This method works best to dynamically init the current UserForm
On Windows you can use Chocolatey to install and update Node.js (and lots of other packages).
Install Node
cinst nodejs.install
Update Node
cup nodejs.install
Note: You will need to install Chocolatey before you can use cinst
and cup
.
"2) Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – one idea can be, calculate the minimum weight value, add a positive value (equal to absolute value of minimum weight value) to all weights and run the Dijksra’s algorithm for the modified graph. Will this algorithm work?"
This absolutely doesn't work unless all shortest paths have same length. For example given a shortest path of length two edges, and after adding absolute value to each edge, then the total path cost is increased by 2 * |max negative weight|. On the other hand another path of length three edges, so the path cost is increased by 3 * |max negative weight|. Hence, all distinct paths are increased by different amounts.
Xcode 5 has iOS 6/7 Deltas
which is specifically made to resolve this issue. In the storyboard, I moved my views 20 pixels down to look right on iOS 7 and in order to make it iOS 6 compatible, I changed Delta y
to -20.
Since my storyboard is not using auto-layout, in order to resize the height of views properly on iOS 6 I had to set Delta height
as well as Delta Y
.
Or simply:
Date.now
From MDN documentation:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970
Available since ECMAScript 5.1
It's the same as was mentioned above (new Date().getTime()
), but more shortcutted version.
The following will find all product_id that are used more than once. You only get a single record for each product_id.
SELECT product_id FROM oc_product_reward GROUP BY product_id HAVING count( product_id ) >1
Code taken from : http://chandreshrana.blogspot.in/2014/12/find-duplicate-records-based-on-any.html
There's some discussion about the use of the term "pass by reference" in JavaScript here, but to answer your question:
A object is automatically passed by reference, without the need to specifically state it
(From the article mentioned above.)
This is currently not possible with CSS alone as @BoltClock wrote in the accepted answer, but you can work around that by using JavaScript.
I created a container query (aka element query) prolyfill to solve this kind of issue. It works a bit different than other scripts, so you don’t have to edit the HTML code of your elements. All you have to do is include the script and use it in your CSS like so:
.element:container(width > 99px) {
/* If its container is at least 100px wide */
}
Your question did not indicate if order or distinct values are a requirement.
If you don't care about order, and will not have the same value in the container more than once, use a Set. It will be way faster, and more succinct.
var aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
aSet.delete(2);
For hexadecimal code try this
& 0x00FFFFFF
For RGB one
Red
, Green
, Blue
valuesImplementation
private static string HexConverter(Color c) {
return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}
public static string RgbConverter(Color c) {
return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}
I had problems making a sub query until I added the method ->toArray()
to the result, I hope it helps more than one since I had a good time looking for the solution.
Example
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
->get();
also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.
the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.
I had the same error. To fix the error:
Gallery Menu
and select API Manager
.Credentials
and then click New Credentials
.Create Credentials
.API KEY
.Navigator Key
(there are more options; It depends on when consumed).You must use this new API Navigator Key
, generated by the system.
var result =_x000D_
'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())_x000D_
_x000D_
console.log(result) // This Is Very Interesting
_x000D_
I found a reference to this in condas issues. The following should now work.
name: sample_env
channels:
dependencies:
- requests
- bokeh>=0.10.0
- pip:
- git+https://github.com/pythonforfacebook/facebook-sdk.git
glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:
OpenGL documentation (my bold)
The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).
The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:
Parallel projections have lines of projection that are parallel both in reality and in the projection plane.
Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".
Check <mvc:annotation-driven />
in dispatcherservlet.xml , if not add it.
And add
<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>
these dependencies in your pom.xml
I also come across same problem, I changed transaction timeout to 15 minutes and it works. I hope this helps.
TransactionOptions options = new TransactionOptions();
options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
options.Timeout = new TimeSpan(0, 15, 0);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required,options))
{
sp1();
sp2();
...
}
ls -d */ | xargs -iA cp file.txt A
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
I really like following clean solution.
class Router
include Rails.application.routes.url_helpers
def self.default_url_options
ActionMailer::Base.default_url_options
end
end
router = Router.new
router.posts_url # http://localhost:3000/posts
router.posts_path # /posts
It's from http://hawkins.io/2012/03/generating_urls_whenever_and_wherever_you_want/
If I understand things correctly, you want to install over your existing Vim, for better or worse :-) This is a bad idea and it is not the "clean" way to do it. Why? Well, OS X expects that nothing will ever change in /usr/bin unbeknownst to it, so any time you overwrite stuff in there you risk breaking some intricate interdependency. And, Let's say you do break something -- there's no way to "undo" that damage. You will be sad and alone. You may have to reinstall OS X.
The "clean" way is to install in a separate place, and make the new binary higher priority in the $PATH. Here is how I recommend doing that:
$ # Create the directories you need
$ sudo mkdir -p /opt/local/bin
$ # Download, compile, and install the latest Vim
$ cd ~
$ hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
$
$ cd vim
$ ./configure --prefix=/opt/local
$ make
$ sudo make install
$ # Add the binary to your path, ahead of /usr/bin
$ echo 'PATH=/opt/local/bin:$PATH' >> ~/.bash_profile
$ # Reload bash_profile so the changes take effect in this window
$ source ~/.bash_profile
Voila! Now when we use vim we will be using the new one. But, to get back to our old configuration in the event of huge f*ckups, we can just delete the /opt directory.
$ which vim
/opt/local/bin/vim
$ vim --version | head -n 2
VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Aug 27 2011 20:55:46)
MacOS X (unix) version
See how clean this is.
I recommend not to install in /usr/local/bin when you want to override binaries in /usr/bin, because by default OS X puts /usr/bin higher priority in $PATH than /usr/local/bin, and screwing with that opens its own can of worms.... So, that's what you SHOULD do.
Assuming you're set on doing that, you are definitely on track. To install on top of your current installation, you need to set the "prefix" directory. That's done like this:
hg clone https://bitbucket.org/vim-mirror/vim or git clone https://github.com/vim/vim.git
cd vim
./configure --prefix=/usr
make
sudo make install
You can pass "configure" a few other options too, if you want. Do "./configure --help" to see them. I hope you've got a backup before you do it, though, in case something goes wrong....
What is the 'best' way? Words like 'most efficient,' 'fastest rendering,' etc. are more specific. Anyway, I am offering an alternative answer that helps me most of the time (whether or not is 'best' is irrelevant).
Alternate answer: Use an iframe.
That is, host the SWF file on the server. If you put the SWF file in the root or public_html folder then the SWF file will be located at www.YourDomain.com/YourFlashFile.swf
.
Then, on your index.html or wherever, link the above location to your iframe and it will be displayed around your content wherever you put your iframe. If you can put an iframe there, you can put an SWF file there. Make the iframe dimensions the same as your SWF file. In the example below, the SWF file is 500 by 500.
Pseudo code:
<iframe src="//www.YourDomain.com/YourFlashFile.swf" width="500" height="500"></iframe>
The line of HTML code above will embed your SWF file. No other mess needed.
Pros: W3C compliant, page design friendly, no speed issue, minimalist approach.
Cons: White space around your SWF file when launched in a browser.
That is an alternate answer. Whether it is the 'best' answer depends on your project.
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Follow this tutorial to learn more about log4j usage:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
There's more than one way
First, shortest but Inefficient way
Network State Permission only needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then this method,
public boolean activeNetwork () {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
As seen in answers ConnectivityManager
is a solution, I just added it within a method this is a simplified method all use
ConnectivityManager
returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability
Second, Efficient way
Network State and Internet Permissions needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Then this class,
public class CheckInternetAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private Context context;
public CheckInternetAsyncTask(Context context) {
this.context = context;
}
@Override
protected Boolean doInBackground(Void... params) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
assert cm != null;
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (isConnected) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
if (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0)
return true;
} catch (IOException e) {
Log.e("TAG", "Error checking internet connection", e);
return false;
}
} else {
Log.d("TAG", "No network available!");
return false;
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.d("TAG", "result" + result);
if(result){
// do ur code
}
}
}
Call CheckInternetAsyncTask
new CheckInternetAsyncTask(getApplicationContext()).execute();
Some Explanations :-
you have to check Internet on AsyncTask
, otherwise it can throw android.os.NetworkOnMainThreadException
in some cases
ConnectivityManager
used to check the network access if true sends request (Ping)
Request send to http://clients3.google.com/generate_204
, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient than http://www.google.com
, read this. if you have website it's preferred to put you website instead of google, only if you use it within the app
Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used
Another thing on linux is:
send
does not allow to operate on non-socket fd. Thus, for example to write on usb port, write
is necessary.
The cause in my case was having a jupyter notebook open, which was importing the relevant library; the root cause seems to be windows error due to the file being open / in use (see also @Robert's answer, and the recommendation to reboot).
So another thing to verify is that no other python processes are running.
For me, shutting down the notebook server solved the issue.
Try this:
const url = "files/images/gallery/image.jpg";_x000D_
_x000D_
console.log(url.split("/").pop());
_x000D_
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(message);
}
innerHTML
is a string representing the contents of the element.
You want to modify the element itself. Drop the .innerHTML
part.
If you're willing and able to employ a little jquery, you can simply do this:
$('.someDiv').css([".radius", ".opacity"]);
If you have a javascript that already processes the page or you can enclose it somewhere in <script> tags. If so, wrap the above in the document ready function:
$(document).ready( function() {
$('.someDiv').css([".radius", ".opacity"]);
}
I recently came across this while updating a wordpress plugin. The them has been changed which used a lot of "!important" directives across the css. I had to use jquery to force my styles because of the genius decision to declare !important on several tags.
To subtract timevals:
gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:
long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;
If you are using C function fgetc
then you should check a next character whether it is equal to the new line character or to EOF. For example
unsigned int count = 0;
while ( 1 )
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
if ( c == EOF ) break;
}
else
{
++count;
}
}
or maybe it would be better to rewrite the code using do-while loop. For example
unsigned int count = 0;
do
{
int c = fgetc( FileStream );
if ( c == EOF || c == '\n' )
{
printF( "The length of the line is %u\n", count );
count = 0;
}
else
{
++count;
}
} while ( c != EOF );
Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc
to read lines of a file.
But if the program is written in C++ then it would be much better if you would use std::ifstream
and std::string
classes and function std::getline
to read a whole line.
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Python boolean keywords are True
and False
, notice the capital letters. So like this:
a = True;
b = True;
match_var = True if a == b else False
print match_var;
When compiled and run, this prints:
True
In Swift 3 and later you can:
let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"id": 13,
"name": "Jack & Jill"
]
request.httpBody = parameters.percentEncoded()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else { // check for fundamental networking error
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
Where:
extension Dictionary {
func percentEncoded() -> Data? {
return map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed = CharacterSet.urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query.
Note, I used a name
of Jack & Jill
, to illustrate the proper x-www-form-urlencoded
result of name=Jack%20%26%20Jill
, which is “percent encoded” (i.e. the space is replaced with %20
and the &
in the value is replaced with %26
).
See previous revision of this answer for Swift 2 rendition.
This questions seems a little bit outdated but here is my solution.
I assume that you have already downloaded GlassFish on your hard drive and unzipped the files on a directory.
The first thing as it is said on previous answers, you have to downloaded GlassFish Tools from eclipse marketplace;
Help -> EclipseMarket Place
And install GlassFish on the screen below;
Open Server View, if it is not visible on the bottom of the eclipse, then;
Window -> Show View -> Servers
As the server view is visible, simply click "No servers are available. Click this link to create a new server..." as shown below;
On the New Server window, select GlassFish as shown below. On my experience, there is only one GlassFish option that I can select, instead of several GlassFish options with versions as you can see down below;
Enter the exact GlassFish location and also Java location as you can see below;
On the last step of this configuration, just leave everything as it is. For simplicity, I don't define an admin password;
Now everything is all set, hope that this helps!
Example using react-router v4, redux-thunk and react-router-redux(5.0.0-alpha.6) package.
When user uses search feature, I want him to be able to send url link for same query to a colleague.
import { push } from 'react-router-redux';
import qs from 'query-string';
export const search = () => (dispatch) => {
const query = { firstName: 'John', lastName: 'Doe' };
//API call to retrieve records
//...
const searchString = qs.stringify(query);
dispatch(push({
search: searchString
}))
}