XmlTextWriter xw = new XmlTextWriter(writer);
xw.Formatting = Formatting.Indented;
Jackson has a class named SimpleBeanPropertyFilter that helps to filter fields during serialization and deserialization; not globally. I think that's what you wanted.
@JsonFilter("custom_serializer")
class User {
private String password;
//setter, getter..
}
Then in your code:
String[] fieldsToSkip = new String[] { "password" };
ObjectMapper mapper = new ObjectMapper();
final SimpleFilterProvider filter = new SimpleFilterProvider();
filter.addFilter("custom_serializer",
SimpleBeanPropertyFilter.serializeAllExcept(fieldsToSkip));
mapper.setFilters(filter);
String jsonStr = mapper.writeValueAsString(currentUser);
This will prevent password
field to get serialized. Also you will be able to deserialize password
fields as it is. Just make sure no filters are applied on the ObjectMapper object.
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(yourJsonStr, User.class); // user object does have non-null password field
For some reason, adding the environment variable didn't work for me.
I was able to specify a path to Firefox in the command line node configuration, as described on this page (grid2).
-browser “browserName=firefox,version=3.6,firefox_binary=c:\Program Files\Mozilla Firefox\firefox.exe ,maxInstances=3, platform=WINDOWS”
cheeky jquery solution if anyone's interested. Just make sure all your cols (el) have a common classname...works responsively too if you bind it to $(window).resize
function equal_cols(el)
{
var h = 0;
$(el).each(function(){
$(this).css({'height':'auto'});
if($(this).outerHeight() > h)
{
h = $(this).outerHeight();
}
});
$(el).each(function(){
$(this).css({'height':h});
});
}
$(document).ready(function(){
equal_cols('.selector');
});
Note: This post has been edited as per @Chris' comment out that the code was only set the last highest height in the $.each()
function
What most answers here don't explain is - what if you need to make columns visible again and invisible, all based on data dynamically? After all, shouldn't GridViews
be data centric?
What if you want to turn ON or OFF columns based on your data?
My Gridview
<asp:GridView ID="gvLocationBoard" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="false" ShowHeader="true" Visible="true" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None"
DataSourceID="sdsLocationBoard" OnDataBound="gvLocationBoard_DataBound" OnRowDataBound="gvLocationBoard_RowDataBound" PageSize="15" OnPreRender="gvLocationBoard_PreRender">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student" SortExpression="StudentName">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="CheckStatusName" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HiddenField ID="hfStatusID" runat="server" Value='<%# Eval("CheckStatusID") %>' />
<asp:Label ID="Label4" runat="server" Text='<%# Eval("CheckStatusName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod0" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod0" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod0" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod1" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod1" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod1" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
..
etc..
Note the `"RollCallPeriodn", where 'n' is a sequential number.
The way I do it, is to by design hide all columns that I know are going to be ON (visible="true") or OFF (visible="false") later, and depending on my data.
In my case I want to display Period Times up to a certain column. So for example, if today is 9am then I want to show periods 6am, 7am, 8am and 9am, but not 10am, 11am, etc.
On other days I want to show ALL the times. And so on.
So how do we do this?
Why not use PreRender
to "reset" the Gridview
?
protected void gvLocationBoard_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
int wsPos = 3;
for (int wsCol = 0; wsCol < 19; wsCol++)
{
gv.Columns[wsCol + wsPos].HeaderText = "RollCallPeriod" + wsCol.ToString("{0,00}");
gv.Columns[wsCol + wsPos].Visible = false;
}
}
Now turn ON the columns you need based on finding the Start of the HeaderText and make the column visible if the header text is not the default.
protected void gvLocationBoard_DataBound(object sender, EventArgs e)
{
//Show the headers for the Period Times directly from sdsRollCallPeriods
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dv = sdsRollCallPeriods.Select(dss) as DataView;
DataTable dt = dv.ToTable() as DataTable;
if (dt != null)
{
int wsPos = 0;
int wsCol = 3; //start of PeriodTimes column in gvLocationBoard
foreach (DataRow dr in dt.Rows)
{
gvLocationBoard.Columns[wsCol + wsPos].HeaderText = dr.ItemArray[1].ToString();
gvLocationBoard.Columns[wsCol + wsPos].Visible = !gvLocationBoard.Columns[wsCol + wsPos].HeaderText.StartsWith("RollCallPeriod");
wsPos += 1;
}
}
}
I won't reveal the SqlDataSource
here, but suffice to say with the PreRender
, I can reset my GridView
and turn ON the columns I want with the headers I want.
So the way it works is that everytime you select a different date or time periods to display as headers, it resets the GridView to the default header text and Visible="false" status before it builds the gridview
again. Otherwise, without the PreRender
, the GridView will have the previous data's headers as the code behind wipes the default settings.
This is easier than trapping the exception:
import os
if not os.path.exists(...):
os.makedirs(...)
Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaway script running in a controlled environment, you're better off going with the accepted answer that requires only one system call.
UPDATE 2012-07-27
I'm tempted to delete this answer, but I think there's value in the comment thread below. As such, I'm converting it to a wiki.
function ajax_form(selector, obj)
{
var form = document.querySelectorAll(selector);
if(obj)
{
var before = obj.before ? obj.before : function(){return true;};
var $success = obj.success ? obj.success: function(){return true;};
for (var i = 0; i < form.length; i++)
{
var url = form[i].hasAttribute('action') ? form[i].getAttribute('action') : window.location;
var $form = form[i];
form[i].submit = function()
{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
var FD = new FormData($form);
/** prevent submiting twice */
if($form.disable === true)
return this;
$form.disable = true;
if(before() === false)
return;
xhttp.addEventListener('load', function()
{
$form.disable = false;
return $success(JSON.parse(this.response));
});
xhttp.send(FD);
}
}
}
return form;
}
Didn't check how it works. You can also bind(this) so it will work like jquery ajaxForm
use it like:
ajax_form('form',
{
before: function()
{
alert('submiting form');
// if return false form shouldn't be submitted
},
success:function(data)
{
console.log(data)
}
}
)[0].submit();
it return nodes so you can do something like submit i above example
so far from perfection but it suppose to work, you should add error handling or remove disable condition
The java.lang.management package does give you a whole lot more info than Runtime - for example it will give you heap memory (ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
) separate from non-heap memory (ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()
).
You can also get process CPU usage (without writing your own JNI code), but you need to cast the java.lang.management.OperatingSystemMXBean
to a com.sun.management.OperatingSystemMXBean
. This works on Windows and Linux, I haven't tested it elsewhere.
For example ... call the get getCpuUsage() method more frequently to get more accurate readings.
public class PerformanceMonitor {
private int availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();
private long lastSystemTime = 0;
private long lastProcessCpuTime = 0;
public synchronized double getCpuUsage()
{
if ( lastSystemTime == 0 )
{
baselineCounters();
return;
}
long systemTime = System.nanoTime();
long processCpuTime = 0;
if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
{
processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
}
double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );
lastSystemTime = systemTime;
lastProcessCpuTime = processCpuTime;
return cpuUsage / availableProcessors;
}
private void baselineCounters()
{
lastSystemTime = System.nanoTime();
if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )
{
lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();
}
}
}
im building and Angular App with electron, my solution was the following:
index.html
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
angular.json
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/popper.js/dist/umd/popper.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"
]
So Jquery gets loaded from angular.json if on browser, else if it is an electron builded app it will require module instead.
If you want to import jquery in index.html instead of importing from angular.json use the following solution:
<script src="path/to/jquery"></script>
<script>
if ( typeof module === "object" && typeof module.exports === "object" ) {
window.$ = window.jQuery = require('jquery');
}
</script>
tar -czf workspace.tar.gz .??* *
Specifying .??*
will include "dot" files and directories that have at least 2 characters after the dot. The down side is it will not include files/directories with a single character after the dot, such as .a
, if there are any.
I think it's better to use the chrome toggle device toolbar with the chrome inspector. It provides you a user agent switch along with responsive mode.
What worked for me:
In your POM - you have to set compiler plugin to version 1.8 (or 1.7) in <build>
section:
<build>
...
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Ensure that change Java Build shows 1.8. If it does not - click EDIT and select what it should be.
Instead of changing it:
a) uncheck the Dynamic Web Module
b) apply
c) check it again. New version 3.0 should be set.**
After applying and checking it again:
Hope this helps.
Angular 1.3 now has ng-model-options, and you can set the option to { 'updateOn': 'blur'}
for example, and you can even debounce, when the use is either typing too fast, or you want to save a few expensive DOM operations (like a model writing to multiple DOM places and you don't want a $digest cycle happening on every key down)
https://docs.angularjs.org/guide/forms#custom-triggers and https://docs.angularjs.org/guide/forms#non-immediate-debounced-model-updates
By default, any change to the content will trigger a model update and form validation. You can override this behavior using the ngModelOptions directive to bind only to specified list of events. I.e. ng-model-options="{ updateOn: 'blur' }" will update and validate only after the control loses focus. You can set several events using a space delimited list. I.e. ng-model-options="{ updateOn: 'mousedown blur' }"
And debounce
You can delay the model update/validation by using the debounce key with the ngModelOptions directive. This delay will also apply to parsers, validators and model flags like $dirty or $pristine.
I.e. ng-model-options="{ debounce: 500 }" will wait for half a second since the last content change before triggering the model update and form validation.
Since this question is ranked #1 in Google for "triggering a click on an <a>
element" and no answer actually mentions how you do that, this is how you do it:
$('#titleee a')[0].click();
Explanation: you trigger a click
on the underlying html-element, not the jQuery-object.
You're welcome googlers :)
val jobName = "WordCount";
//overwrite the output directory in spark set("spark.hadoop.validateOutputSpecs", "false")
val conf = new
SparkConf().setAppName(jobName).set("spark.hadoop.validateOutputSpecs", "false");
val sc = new SparkContext(conf)
This just allow positive integers.
^[0-9]*[1-9][0-9]*$
The scss
solution for Bootstrap 4.0
.modal {
max-height: 100vh;
.modal-dialog {
.modal-content {
.modal-body {
max-height: calc(80vh - 140px);
overflow-y: auto;
}
}
}
}
Make sure the .modal
max-height
is 100vh
. Then for .modal-body
use calc()
function to calculate desired height. In above case we want to occupy 80vh
of the viewport, reduced by the size of header + footer in pixels. This is around 140px together but you can measure it easily and apply your own custom values. For smaller/taller modal modify 80vh
accordingly.
A2DD.h
class A2DD
{
private:
int gx;
int gy;
public:
A2DD(int x,int y);
int getSum();
};
A2DD.cpp
A2DD::A2DD(int x,int y)
{
gx = x;
gy = y;
}
int A2DD::getSum()
{
return gx + gy;
}
The idea is to keep all function signatures and members in the header file.
This will allow other project files to see how the class looks like without having to know the implementation.
And besides that, you can then include other header files in the implementation instead of the header. This is important because whichever headers are included in your header file will be included (inherited) in any other file that includes your header file.
Else this will helps you
The ADB is now located in the Android SDK platform-tools.
Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.
Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the
"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.
Hope this helps!
While not strictly nested, you can use common table expressions to reuse previous queries in subsequent ones.
To do this, the form of the statement you are looking for would be
WITH x AS
(
SELECT * FROM MyTable
),
y AS
(
SELECT * FROM x
)
SELECT * FROM y
Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.
Thread myThread= new Thread(nameOfFunction);
workerThread.Start();
Calling the start function on the thread object will cause the execution of your function call in a new thread.
create table xyz_new as select * from xyz where 1=0;
http://www.codeassists.com/questions/oracle/copy-table-data-to-new-table-in-oracle
Nowadays with HTML5, it's pretty simple:
<input type="search" placeholder="Search..."/>
Most modern browsers will automatically render a usable clear button in the field by default.
(If you use Bootstrap, you'll have to add an override to your css file to make it show)
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
Safari/WebKit browsers can also provide extra features when using type="search"
, like results=5
and autosave="..."
, but they also override many of your styles (e.g. height, borders) . To prevent those overrides, while still retaining functionality like the X button, you can add this to your css:
input[type=search] {
-webkit-appearance: none;
}
See css-tricks.com for more info about the features provided by type="search"
.
Just a tip:
In Visual Studio to comment a text, you can highlight the text you want to comment, and then use Ctrl + K followed by Ctrl + C. To uncomment, you can use Ctrl + K followed by Ctrl + U.
Another design pattern that I have seen involves using blocks, which is especially useful when a method is being run asynchronously.
Say we have the following error codes defined:
typedef NS_ENUM(NSInteger, MyErrorCodes) {
MyErrorCodesEmptyString = 500,
MyErrorCodesInvalidURL,
MyErrorCodesUnableToReachHost,
};
You would define your method that can raise an error like so:
- (void)getContentsOfURL:(NSString *)path success:(void(^)(NSString *html))success failure:(void(^)(NSError *error))failure {
if (path.length == 0) {
if (failure) {
failure([NSError errorWithDomain:@"com.example" code:MyErrorCodesEmptyString userInfo:nil]);
}
return;
}
NSString *htmlContents = @"";
// Exercise for the reader: get the contents at that URL or raise another error.
if (success) {
success(htmlContents);
}
}
And then when you call it, you don't need to worry about declaring the NSError object (code completion will do it for you), or checking the returning value. You can just supply two blocks: one that will get called when there is an exception, and one that gets called when it succeeds:
[self getContentsOfURL:@"http://google.com" success:^(NSString *html) {
NSLog(@"Contents: %@", html);
} failure:^(NSError *error) {
NSLog(@"Failed to get contents: %@", error);
if (error.code == MyErrorCodesEmptyString) { // make sure to check the domain too
NSLog(@"You must provide a non-empty string");
}
}];
From PHP using single quotes for the line break worked for me to support the line breaks when I pass that var to an HTML text area value attribute
PHP
foreach ($videoUrls as $key => $value) {
$textAreaValue .= $value->video_url . '\n';
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTML/JS
$( document ).ready(function() {
var text = "<?= htmlspecialchars($textAreaValue); ?>";
document.getElementById("video_urls_textarea").value = text;
});
The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:
When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:
Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.
In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company
with the value 'ABC123'
and the field address
with the value '123 Street'
, in the exact order:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
I use the following:
Function GetProgramOutput([string]$exe, [string]$arguments)
{
$process = New-Object -TypeName System.Diagnostics.Process
$process.StartInfo.FileName = $exe
$process.StartInfo.Arguments = $arguments
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.Start()
$output = $process.StandardOutput.ReadToEnd()
$err = $process.StandardError.ReadToEnd()
$process.WaitForExit()
$output
$err
}
$exe = "C:\Program Files\7-Zip\7z.exe"
$arguments = "i"
$runResult = (GetProgramOutput $exe $arguments)
$stdout = $runResult[-2]
$stderr = $runResult[-1]
[System.Console]::WriteLine("Standard out: " + $stdout)
[System.Console]::WriteLine("Standard error: " + $stderr)
IntelliJ IDEA Plugins / GenerateSerialVersionUID https://plugins.jetbrains.com/plugin/?idea&id=185
very nice, very easy to install. you can install that from plugins menu, select install from disk, select the jar file you unpacked in the lib folder. restart, control + ins, and it pops up to generate serial UID from menu. love it. :-)
You can use
moment().isSameOrBefore(Moment|String|Number|Date|Array);
moment().isSameOrAfter(Moment|String|Number|Date|Array);
or
moment().isBetween(moment-like, moment-like);
See here : http://momentjs.com/docs/#/query/
I wrote a script which displays diff between two commits, works well on Ubuntu.
https://gist.github.com/jacobabrahamb4/a60624d6274ece7a0bd2d141b53407bc
#!/usr/bin/env python
import sys, subprocess, os
TOOLS = ['bcompare', 'meld']
def getTool():
for tool in TOOLS:
try:
out = subprocess.check_output(['which', tool]).strip()
if tool in out:
return tool
except subprocess.CalledProcessError:
pass
return None
def printUsageAndExit():
print 'Usage: python bdiff.py <project> <commit_one> <commit_two>'
print 'Example: python bdiff.py <project> 0 1'
print 'Example: python bdiff.py <project> fhejk7fe d78ewg9we'
print 'Example: python bdiff.py <project> 0 d78ewg9we'
sys.exit(0)
def getCommitIds(name, first, second):
commit1 = None
commit2 = None
try:
first_index = int(first) - 1
second_index = int(second) - 1
if int(first) < 0 or int(second) < 0:
print "Cannot handle negative values: "
sys.exit(0)
logs = subprocess.check_output(['git', '-C', name, 'log', '--oneline', '--reverse']).split('\n')
if first_index >= 0:
commit1 = logs[first_index].split(' ')[0]
if second_index >= 0:
commit2 = logs[second_index].split(' ')[0]
except ValueError:
if first != '0':
commit1 = first
if second != '0':
commit2 = second
return commit1, commit2
def validateCommitIds(name, commit1, commit2):
if commit1 == None and commit2 == None:
print "Nothing to do, exit!"
return False
try:
if commit1 != None:
subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit1]).strip()
if commit2 != None:
subprocess.check_output(['git', '-C', name, 'cat-file', '-t', commit2]).strip()
except subprocess.CalledProcessError:
return False
return True
def cleanup(commit1, commit2):
subprocess.check_output(['rm', '-rf', '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])
def checkoutCommit(name, commit):
if commit != None:
subprocess.check_output(['git', 'clone', name, '/tmp/'+commit])
subprocess.check_output(['git', '-C', '/tmp/'+commit, 'checkout', commit])
else:
subprocess.check_output(['mkdir', '/tmp/0'])
def compare(tool, commit1, commit2):
subprocess.check_output([tool, '/tmp/'+(commit1 if commit1 != None else '0'), '/tmp/'+(commit2 if commit2 != None else '0')])
if __name__=='__main__':
tool = getTool()
if tool == None:
print "No GUI diff tools"
sys.exit(0)
if len(sys.argv) != 4:
printUsageAndExit()
name, first, second = None, 0, 0
try:
name, first, second = sys.argv[1], sys.argv[2], sys.argv[3]
except IndexError:
printUsageAndExit()
commit1, commit2 = getCommitIds(name, first, second)
if not validateCommitIds(name, commit1, commit2):
sys.exit(0)
cleanup(commit1, commit2)
checkoutCommit(name, commit1)
checkoutCommit(name, commit2)
try:
compare(tool, commit1, commit2)
except KeyboardInterrupt:
pass
finally:
cleanup(commit1, commit2)
sys.exit(0)
In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:
sudo snap stop docker
sudo snap remove docker
... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:
sudo apt purge snap
:-)
My favourite way of doing this is to use Sysinternals Autoruns application. Just select the service and press delete.
You can use a ComboBox
with its ComboBoxStyle
(appears as DropDownStyle
in later versions) set to DropDownList
. See: http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
It's Working
package com.keshav.fetchmacaddress;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("keshav","getMacAddr -> " +getMacAddr());
}
public static String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
// res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
//handle exception
}
return "";
}
}
UPDATE 1
This answer got a bug where a byte that in hex form got a single digit, will not appear with a "0" before it. The append to res1
has been changed to take care of it.
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
// res1.append(Integer.toHexString(b & 0xFF) + ":");
res1.append(String.format("%02X:",b));
}
it worked. Just modified it
global $woocommerce, $post;
$order = new WC_Order($post->ID);
//to escape # from order id
$order_id = trim(str_replace('#', '', $order->get_order_number()));
Do you really need to do that programmatically?
Just considering the title: You could use a ShapeDrawable as android:background…
For example, let's define res/drawable/my_custom_background.xml
as:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="2dp"
android:topRightRadius="0dp"
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp" />
<stroke
android:width="1dp"
android:color="@android:color/white" />
</shape>
and define android:background="@drawable/my_custom_background".
I've not tested but it should work.
Update:
I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border"
android:padding="10dip" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
[... more TextView ...]
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World, SOnich"
/>
</LinearLayout>
and a res/drawable/border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="5dip"
android:color="@android:color/white" />
</shape>
Reported to work on a gingerbread device. Note that you'll need to relate android:padding
of the LinearLayout to the android:width
shape/stroke's value. Please, do not use @android:color/white
in your final application but rather a project defined color.
You could apply android:background="@drawable/border" android:padding="10dip"
to each of the LinearLayout from your provided sample.
As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…
Your problem resides clearly in the use of getBorder.set{Width,Height}(100);
. Why do you do that in an onClick method?
I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.
To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…
I used a very similar method to @bott, but I modified it a little bit to make there be no need to resize the image:
BufferedImage img = null;
try {
img = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Image dimg = img.getScaledInstance(800, 508, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(dimg);
setContentPane(new JLabel(imageIcon));
Works every time. You can also get the width and height of the jFrame and use that in place of the 800 and 508 respectively.
You can just split on the word boundary using \b
. See MDN
"\b: Matches a zero-width word boundary, such as between a letter and a space."
You should also make sure it is followed by whitespace \s
. so that strings like "My car isn't red"
still work:
var stringArray = str.split(/\b(\s)/);
The initial \b
is required to take multiple spaces into account, e.g. my car is red
EDIT: Added grouping
Well, first off, the ^
operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.
Now, regarding your problem with using the pow()
function, some googling shows that casting one of the arguments to double helps:
result = (int) pow((double) a,i);
Note that I also cast the result to int
as all pow()
overloads return double, not int
. I don't have a MS compiler available so I couldn't check the code above, though.
Since C99, there are also float
and long double
functions called powf
and powl
respectively, if that is of any help.
DHT nodes have unique identifiers, termed, Node ID. Node IDs are chosen at random from the same 160-bit space as BitTorrent info-hashes. Closeness is measured by comparing Node ID's routing tables, the closer the Node, the more detailed, resulting in optimal
What then makes them more optimal than it's predecessor "Kademlia" which used simple unsigned integers: distance(A,B) = |A xor B| Smaller values are closer. XOR. Besides not being secure, its logic was flawed.
If your client supports DHT, there are 8-bytes reserved in which contains 0x09 followed by a 2-byte payload with the UDP Port and DHT node. If the handshake is successful the above will continue.
If you are certain that you have a JDK installed (and not a JRE), you can specify the location of the JDK on the commandline when starting the installer (as mentioned in the error message you get).
These FAQ entries might also help you:
http://wiki.netbeans.org/FaqInstallJavahome
http://wiki.netbeans.org/FaqSuitableJvmNotFound
It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.
I wasn't able to reproduce your problem in Google Chrome 4.0, IE8, or Firefox 3.5 using that code. The label and radio button stayed on the same line.
Try putting them both inside a <p>
tag, or set the radio button to be inline like The Elite Gentleman suggested.
If you have an java.awt.Image
, rezising it doesn't require any additional libraries. Just do:
Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
Ovbiously, replace newWidth
and newHeight
with the dimensions of the specified image.
Notice the last parameter: it tells to the runtime the algorithm you want to use for resizing.
There are algorithms that produce a very precise result, however these take a large time to complete.
You can use any of the following algorithms:
Image.SCALE_DEFAULT
: Use the default image-scaling algorithm.Image.SCALE_FAST
: Choose an image-scaling algorithm that gives higher priority to scaling speed than smoothness of the scaled image.Image.SCALE_SMOOTH
: Choose an image-scaling algorithm that gives higher priority to image smoothness than scaling speed.Image.SCALE_AREA_AVERAGING
: Use the Area Averaging image scaling algorithm.Image.SCALE_REPLICATE
: Use the image scaling algorithm embodied in the ReplicateScaleFilter
class.See the Javadoc for more info.
The accepted answer calls the draw
function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:
datatable.clear().rows.add(newData).draw();
You may try to relogin your ITC account via Application Loader.
You need to use
$rootScope.$broadcast()
in the controller that must send datas. And in the one that receive those datas, you use
$scope.$on
Here is a fiddle that i forked a few time ago (I don't know who did it first anymore
If you are on production server and the .env file doesn't work at all, go to /bootstrap/cache/config.php and on the line 230 more or less you will find the database data that is beeing cached from the .env file.
'mysql' =>
array (
'driver' => 'mysql',
'host' => '127.0.0.1',
'port' => '3306',
'database' => 'yorDBname',
'username' => 'YOURUSERNAME',
'password' => 'yourpass',
'unix_socket' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',
),
if you want to list all the containers name with the relevant volumes that attached to each container you can try this:
docker ps -q | xargs docker container inspect -f '{{ .Name }} {{ .HostConfig.Binds }}'
example output:
/opt_rundeck_1 [/opt/var/lib/mysql:/var/lib/mysql:rw /var/lib/rundeck/var/storage:/var/lib/rundeck/var/storage:rw /opt/var/rundeck/.ssh:/var/lib/rundeck/.ssh:rw /opt/etc/rundeck:/etc/rundeck:rw /var/log/rundeck:/var/log/rundeck:rw /opt/rundeck-plugins:/opt/rundeck-plugins:rw /opt/var/rundeck:/var/rundeck:rw]
/opt_rundeck_1 - container name
[..] - volumes attached to the conatiner
Using jQuery:
var str = '{"id":1,"name":"Test1"},{"id":2,"name":"Test2"}';
var jsonObj = $.parseJSON('[' + str + ']');
jsonObj
is your JSON object.
I tried to disable and enable focusability for view and it worked for me (focus was reset):
focusedView.setFocusable(false);
focusedView.setFocusableInTouchMode(false);
focusedView.setFocusable(true);
focusedView.setFocusableInTouchMode(true);
I am using ANGULAR and since it gave me problems the routerLink just add the data-toggle and target in the li tag.... or use jquery like "ZimSystem"
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">_x000D_
<a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
try it.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
You can also use any()
, map()
like so:
if any(map(l.startswith, x)):
pass # Do something
Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
pass # Do something
You don't need to pass both arguments when performing a remount. You can simply pass the mount point (here /system). And /system is universal amongst Android devices.
ProgressDialog
was deprecated in API level 26 .
refers to functions or elements that are in the process of being replaced by newer ones."Deprecated"
ProgressDialog is a modal dialog, which prevents the user from interacting with the app. Instead of using this class, you should use a progress indicator like
ProgressBar
, which can be embedded in your app's UI.
Advantage
I would personally say that ProgressBar
has the edge over the two .ProgressBar
is a user interface element that indicates the progress of an operation. Display progress bars to a user in a non-interruptive way. Show the progress bar in your app's user interface.
Here's a controller
@RestController
@RequestMapping("/loggers")
public class LoggerConfigController {
private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PetController.class);
@GetMapping()
public List<LoggerDto> getAllLoggers() throws CoreException {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
List<Logger> loggers = loggerContext.getLoggerList();
List<LoggerDto> loggerDtos = new ArrayList<>();
for (Logger logger : loggers) {
if (Objects.isNull(logger.getLevel())) {
continue;
}
LoggerDto dto = new LoggerDto(logger.getName(), logger.getLevel().levelStr);
loggerDtos.add(dto);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("All loggers retrieved. Total of {} loggers found", loggerDtos.size());
}
return loggerDtos;
}
@PutMapping
public boolean updateLoggerLevel(
@RequestParam String name,
@RequestParam String level
)throws CoreException {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger logger = loggerContext.getLogger(name);
if (Objects.nonNull(logger) && StringUtils.isNotBlank(level)) {
switch (level) {
case "INFO":
logger.setLevel(Level.INFO);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "DEBUG":
logger.setLevel(Level.DEBUG);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "ALL":
logger.setLevel(Level.ALL);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
break;
case "OFF":
default:
logger.setLevel(Level.OFF);
LOGGER.info("Logger [{}] updated to [{}]", name, level);
}
}
return true;
}
}
The crux of the solution is setting
CURLOPT_RETURNTRANSFER => true
then
$response = curl_exec($ch);
CURLOPT_RETURNTRANSFER tells PHP to store the response in a variable instead of printing it to the page, so $response will contain your response. Here's your most basic working code (I think, didn't test it):
// init curl object
$ch = curl_init();
// define options
$optArray = array(
CURLOPT_URL => 'http://www.google.com',
CURLOPT_RETURNTRANSFER => true
);
// apply those options
curl_setopt_array($ch, $optArray);
// execute request and get response
$result = curl_exec($ch);
Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
This code dumps to a text file
$ cat text.txt
{"two": 2, "one": 1}
Also you can load from a JSON file:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
A modification of the code by @CarloCannas:
public static void sudo(String...strings) {
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
outputStream.close();
}catch(IOException e){
e.printStackTrace();
}
}
(You are welcome to find a better place for outputStream.close())
Usage example:
private static void suMkdirs(String path) {
if (!new File(path).isDirectory()) {
sudo("mkdir -p "+path);
}
}
Update: To get the result (the output to stdout), use:
public static String sudoForResult(String...strings) {
String res = "";
DataOutputStream outputStream = null;
InputStream response = null;
try{
Process su = Runtime.getRuntime().exec("su");
outputStream = new DataOutputStream(su.getOutputStream());
response = su.getInputStream();
for (String s : strings) {
outputStream.writeBytes(s+"\n");
outputStream.flush();
}
outputStream.writeBytes("exit\n");
outputStream.flush();
try {
su.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
res = readFully(response);
} catch (IOException e){
e.printStackTrace();
} finally {
Closer.closeSilently(outputStream, response);
}
return res;
}
public static String readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toString("UTF-8");
}
The utility to silently close a number of Closeables (So?ket may be no Closeable) is:
public class Closer {
// closeAll()
public static void closeSilently(Object... xs) {
// Note: on Android API levels prior to 19 Socket does not implement Closeable
for (Object x : xs) {
if (x != null) {
try {
Log.d("closing: "+x);
if (x instanceof Closeable) {
((Closeable)x).close();
} else if (x instanceof Socket) {
((Socket)x).close();
} else if (x instanceof DatagramSocket) {
((DatagramSocket)x).close();
} else {
Log.d("cannot close: "+x);
throw new RuntimeException("cannot close "+x);
}
} catch (Throwable e) {
Log.x(e);
}
}
}
}
}
This formula does not require a column letter reference ("A", "B", etc.). It returns the value of the cell one row above in the same column.
=INDIRECT(ADDRESS(ROW()-1,COLUMN()))
Convert the JSON string to UTF-8 on your own.
@RequestMapping(value = "/example.json", method = RequestMethod.GET)
@ResponseBody
public byte[] example() throws Exception {
return "{ 'text': 'äöüß' } ".getBytes("UTF-8");
}
shareing for others:
read stream line by line,should be good for large files piped into stdin, my version:
var n=0;
function on_line(line,cb)
{
////one each line
console.log(n++,"line ",line);
return cb();
////end of one each line
}
var fs = require('fs');
var readStream = fs.createReadStream('all_titles.txt');
//var readStream = process.stdin;
readStream.pause();
readStream.setEncoding('utf8');
var buffer=[];
readStream.on('data', (chunk) => {
const newlines=/[\r\n]+/;
var lines=chunk.split(newlines)
if(lines.length==1)
{
buffer.push(lines[0]);
return;
}
buffer.push(lines[0]);
var str=buffer.join('');
buffer.length=0;
readStream.pause();
on_line(str,()=>{
var i=1,l=lines.length-1;
i--;
function while_next()
{
i++;
if(i<l)
{
return on_line(lines[i],while_next);
}
else
{
buffer.push(lines.pop());
lines.length=0;
return readStream.resume();
}
}
while_next();
});
}).on('end', ()=>{
if(buffer.length)
var str=buffer.join('');
buffer.length=0;
on_line(str,()=>{
////after end
console.error('done')
////end after end
});
});
readStream.resume();
Like Eliran Malka asked, why do you need to check for IE 9?
Detecting browser make and version is generally a bad smell. This generally means that you there is a bigger problem with the code if you need JavaScript to detect specific versions of browser.
There are genuine cases where a feature won't work, like say WebSockets isn't supported in IE 8 or 9. This should be solved by checking for WebSocket support, and applying a polyfill if there is no native support.
This should be done with a library like Modernizr.
That being said, you can easily create service that would return the browser. There are valid cases where a feature exists in a browser but the implementation is outdated or broken. Modernizr is not appropriate for these cases.
app.service('browser', ['$window', function($window) {
return function() {
var userAgent = $window.navigator.userAgent;
var browsers = {chrome: /chrome/i, safari: /safari/i, firefox: /firefox/i, ie: /internet explorer/i};
for(var key in browsers) {
if (browsers[key].test(userAgent)) {
return key;
}
};
return 'unknown';
}
}]);
Fixed typo broswers
Note: This is just an example of how to create a service in angular that will sniff the userAgent string. This is just a code example that is not expected to work in production and report all browsers in all situations.
UPDATE
It is probably best to use a third party library like https://github.com/ded/bowser or https://github.com/darcyclarke/Detect.js. These libs place an object on the window
named bowser or detect respectively.
You can then expose this to the Angular IoC Container
like this:
angular.module('yourModule').value('bowser', bowser);
Or
detectFactory.$inject = ['$window'];
function detectFactory($window) {
return detect.parse($window.navigator.userAgent);
}
angular.module('yourModule').factory('detect', detectFactory);
You would then inject one of these the usual way, and use the API provided by the lib. If you choose to use another lib that instead uses a constructor method, you would create a factory that instantiates it:
function someLibFactory() {
return new SomeLib();
}
angular.module('yourModule').factory('someLib', someLibFactory);
You would then inject this into your controllers and services the normal way.
If the library you are injecting does not exactly match your requirements, you may want to employ the Adapter Pattern
where you create a class/constructor with the exact methods you need.
In this example we just need to test for IE 9, and we are going to use the bowser
lib above.
BrowserAdapter.$inject = ['bowser']; // bring in lib
function BrowserAdapter(bowser) {
this.bowser = bowser;
}
BrowserAdapter.prototype.isIe9 = function() {
return this.bowser.msie && this.browser.version == 9;
}
angular.module('yourModule').service('browserAdapter', BrowserAdapter);
Now in a controller or service you can inject the browserAdapter
and just do if (browserAdapter.isIe9) { // do something }
If later you wanted to use detect instead of bowser, the changes in your code would be isolated to the BrowserAdapter.
UPDATE
In reality these values never change. IF you load the page in IE 9 it will never become Chrome 44. So instead of registering the BrowserAdapter as a service, just put the result in a value
or constant
.
angular.module('app').value('isIe9', broswerAdapter.isIe9);
JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia
If you are using Babel or such transpilers and using async/await you could do :
function onDrop() {
console.log("dropped");
}
async function dropAll( collections ) {
const drops = collections.map(col => conn.collection(col).drop(onDrop) );
await drops;
console.log("all dropped");
}
If you don't intend to have any telephone numbers on your page, then
<meta name="format-detection" content="telephone=no">
will work just fine. But rhetorically speaking, what if you intend to use a mix of phone and non-phone numbers?
Assuming you're just hard-coding numbers into your HTML, the "insert stuff in the middle of your digits" hacks will work. But they are of little to no use for dynamic pages, such as using PHP to output numerical data from a query.
As an example, I was generating a list of city populations. Some of the populations were large enough to cause Mobile Safari to turn them into phone number links. Fortunately, all I had to do was use PHP number_format()
around the array output to insert "thousands" commas:
<?php echo number_format($row["population"]) ?>
This formatting was enough to convince Mobile Safari that there was a somewhat more specific purpose for the number, so it didn't default my larger numbers into telephone links anymore. The same would hold true for the suggestion by @davidcondrey of using <a href="tel:18001234567">1-800-123-4567</a>
to specify a purpose to the number.
Bottom line is that Safari Mobile apparently does pay attention to semantics. Given that HTML5 is built around semantic markup, and search engines are relying on semantic markup, I intend to use it as much as I can.
Should it have anything to do with "opacity" of the form / its background ? Did you try opacity = 0
Also see if this CP article helps:
I'm a bit late to the party here i know but,
You could directly access the calls object, which can give you the variables for each call
expect(spy.calls.argsFor(0)[0].value).toBe(expectedValue)
In golang's wiki it show some tricks for slice, including delete an element from slice.
Link: enter link description here
For example a is the slice which you want to delete the number i element.
a = append(a[:i], a[i+1:]...)
OR
a = a[:i+copy(a[i:], a[i+1:])]
Documentation here, and I'll use the Frankfurt region as an example.
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
Objects in JavaScript can be thought of as associative arrays, mapping keys (properties) to values.
To remove a property from an object in JavaScript you use the delete
operator:
const o = { lastName: 'foo' }
o.hasOwnProperty('lastName') // true
delete o['lastName']
o.hasOwnProperty('lastName') // false
Note that when delete
is applied to an index property of an Array
, you will create a sparsely populated array (ie. an array with a missing index).
When working with instances of Array
, if you do not want to create a sparsely populated array - and you usually don't - then you should use Array#splice
or Array#pop
.
Note that the delete
operator in JavaScript does not directly free memory. Its purpose is to remove properties from objects. Of course, if a property being deleted holds the only remaining reference to an object o
, then o
will subsequently be garbage collected in the normal way.
Using the delete
operator can affect JavaScript engines' ability to optimise code.
In keeping with its unbroken record of backwards-compatibility, ECMAScript 6, JavaScript still doesn't have a class
type (though not everyone understands this). It does have a class
keyword as part of its class
syntax for creating prototypes—but still no thing called class. JavaScript is not now and has never been a classical OOP language. Speaking of JS in terms of class is only either misleading or a sign of not yet grokking prototypical inheritance (just keeping it real).
That means this.constructor
is still a great way to get a reference to the constructor
function. And this.constructor.prototype
is the way to access the prototype itself. Since this isn't Java, it's not a class. It's the prototype object your instance was instantiated from. Here is an example using the ES6 syntactic sugar for creating a prototype chain:
class Foo {
get foo () {
console.info(this.constructor, this.constructor.name)
return 'foo'
}
}
class Bar extends Foo {
get foo () {
console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))
return `${super.foo} + bar`
}
}
const bar = new Bar()
console.dir(bar.foo)
This is what that outputs using babel-node
:
> $ babel-node ./foo.js ? 6.2.0 [±master ?]
[THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
[SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
[Function: Bar] 'Bar'
'foo + bar'
There you have it! In 2016, there's a class
keyword in JavaScript, but still no class type. this.constructor
is the best way to get the constructor function, this.constructor.prototype
the best way to get access to the prototype itself.
I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.
And what happen if the user catch de JSON and change the bool to True?
I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.
You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:
echo preg_replace("/[^0-9]/","",'604-619-5135');
I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange
You can create folder using the following Java code:
File dir = new File("nameoffolder");
dir.mkdir();
By executing above you will have folder 'nameoffolder' in current folder.
The HTML attribute required="required"
is a statement telling the browser that this field is required in order for the form to be valid. (required="required"
is the XHTML form, just using required
is equivalent)
The Angular attribute ng-required="yourCondition"
means 'isRequired(yourCondition)' and sets the HTML attribute dynamically for you depending on your condition.
Also note that the HTML version is confusing, it is not possible to write something conditional like required="true"
or required="false"
, only the presence of the attribute matters (present means true) ! This is where Angular helps you out with ng-required
.
First of all, I would not make any changes directly in the "main" repo. If you really want to have a "main" repo, then you should only push to it, never change it directly.
Regarding the error you are getting, have you tried git pull
from your local repo, and then git push
to the main repo? What you are currently doing (if I understood it well) is forcing the push and then losing your changes in the "main" repo. You should merge the changes locally first.
If you are using Any CPU
you may need to put it in single quotes.
Certainly when running in a Dockerfile, I had to use single quotes:
# Fails. Gives: MSBUILD : error MSB1008: Only one project can be specified.
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform="Any CPU"
# Passes. Gives: Successfully built 40163c3e0121
RUN msbuild ConsoleAppFw451.sln /p:Configuration=Debug /p:Platform='Any CPU'
I had trouble with changing the JFrame background as well and the above responses did not solve it entirely. I am using Eclipse. Adding a layout fixed the issue.
public class SampleProgram extends JFrame {
public SampleProgram() {
setSize(400,400);
setTitle("Sample");
getContentPane().setLayout(new FlowLayout());//specify a layout manager
getContentPane().setBackground(Color.red);
setVisible(true);
}
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.
execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute
will also perform better if you are repeating a query multiple times. Example of prepared statements:
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
// data is separated from the query
Best practice is to stick with prepared statements and execute
for increased security.
See also: Are PDO prepared statements sufficient to prevent SQL injection?
Refactoring the above methods and showing with the use:
private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
for (int i = 0; i < arr.length; i++)
if(arr[i].equals(str)) return i;
return -1;
}
indexOf(languages, "en")
If you are looking to do an exact match, use the following syntax:
(param)?
.
Eg.
<Route path={`my/(exact)?/path`} component={MyComponent} />
The nice thing about this is that you'll have props.match
to play with, and you don't need to worry about checking the value of the optional parameter:
{ props: { match: { "0": "exact" } } }
nothing worked for me ... except when I found this
I suspect that you have a local file called unittest.py that is getting imported instead of the standard module.
I have stumbled upon your question a few weeks back, but since then also learned about Circumflex. This is a nice, minimal framework that is therefore easy to learn, and it has pretty good documentation available as well.
Beside it's minimal-ness, it also claims to work well with other libraries and lets you use your own implementation of things when you need it.
You can use an <input type="number" />
. This will only allow numbers to be entered into othe input box.
Example: http://jsfiddle.net/SPqY3/
Please note that the input type="number"
tag is only supported in newer browsers.
For firefox, you can validate the input by using javascript:
Update 2018-03-12: Browser support is much better now it's supported by the following:
It looks like you just want:
eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
? (DateTime?) null
: DateTime.Parse(dateTimeEnd);
Note that this will throw an exception if dateTimeEnd
isn't a valid date.
An alternative would be:
DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
? validValue
: (DateTime?) null;
That will now set the result to null
if dateTimeEnd
isn't valid. Note that TryParse
handles null
as an input with no problems.
unicode('foo,bar').translate(dict([[ord(char), u''] for char in u',']))
I would recommend having a look at the plyr
package.
It might not be as fast as data.table or other packages, but it is quite instructive, especially when starting with R and having to do some data manipulation.
> DF <- data.frame(A = c("1", "1", "2", "3", "3"), B = c(2, 3, 3, 5, 6))
> library(plyr)
> DF.sum <- ddply(DF, c("A"), summarize, B = sum(B))
> DF.sum
A B
1 1 5
2 2 3
3 3 11
I have encountered with same issue. When I changed content type it has solved. I'm not sure this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).
If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.
For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:
.row {
zoom: 1;
margin-left: -20px;
}
.row > [class*="span"] {
display: inline;
float: left;
margin-left: 20px;
}
.span4 {
width: 220px;
}
To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).
For example, to allow for the left border on the sidebar, they added this CSS in the <head>
after the the main <link href="../bootstrap.css" rel="stylesheet">
.
.content .span4 {
margin-left: 0;
padding-left: 19px;
border-left: 1px solid #eee;
}
You'll see they've reduced padding-left
by 1px
to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.
I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.
First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
With the above example, I get around 10fps.
Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.
However, there are a lot of things you can do to speed this example up.
There are two main reasons why this is as slow as it is.
1) Calling fig.canvas.draw()
redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.
2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.
Both these can be fixed by using blitting.
To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.
However, without knowing a bit more about what you're doing, I can't help you there.
Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
This gives me ~200fps.
To make this a bit more convenient, there's an animations
module in recent versions of matplotlib.
As an example:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
<form method="post" action="">
<table>
<tr><td><input name="Submit" type="submit" value="refresh"></td></tr>
</table>
</form>
<?php
if(isset($_POST['Submit']))
{
header("Location: http://yourpagehere.com");
}
?>
Well, for one thing your epression can be simplified:
$("#pDetails").attr("style")
since there should only be one element for any given ID and the ID selector will be much faster than the attribute id selector you're using.
If you just want to return the display value or something, use css():
$("#pDetails").css("display")
If you want to search for elements that have display none, that's a lot harder to do reliably. This is a rough example that won't be 100%:
$("[style*='display: none']")
but if you just want to find things that are hidden, use this:
$(":hidden")
Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items
:
>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
True
>>> all(item in b.items() for item in a.items())
False
That's because dict.items
returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable
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;
I wrote a blog post that explains how to access an unpublished port of a container In different ways depending on the needs:
The post also goes through a brief introduction of both how port mapping works, the difference between exposing and publishing a port, and what is socat.
Here’s the link: https://lmcaraig.com/accessing-an-unpublished-port-of-a-running-docker-container
isinstance is preferrable over type because it also evaluates as True when you compare an object instance with it's superclass, which basically means you won't ever have to special-case your old code for using it with dict or str subclasses.
For example:
>>> class a_dict(dict):
... pass
...
>>> type(a_dict()) == type(dict())
False
>>> isinstance(a_dict(), dict)
True
>>>
Of course, there might be situations where you wouldn't want this behavior, but those are –hopefully– a lot less common than situations where you do want it.
To get path
grep url .gitmodules | sed 's/.*= //'
To get names as in repos
grep path .gitmodules | sed 's/.*= //'
Based on @blushrt 's great answer I will update this response. Just using -
$("#Select_ID").val(id);
works if you've preloaded everything you need to the selector.
Since you are asking about .NET, you should change the parameter from Long
to Integer
. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)
Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
Really though, the managed method isn't difficult...
System.Threading.Thread.CurrentThread.Sleep(5000)
Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep
a good idea.
//You can do it with json.MarshalIndent(data, "", " ")
package main
import(
"fmt"
"encoding/json" //Import package
)
//Create struct
type Users struct {
ID int
NAME string
}
//Asign struct
var user []Users
func main() {
//Append data to variable user
user = append(user, Users{1, "Saturn Rings"})
//Use json package the blank spaces are for the indent
data, _ := json.MarshalIndent(user, "", " ")
//Print json formatted
fmt.Println(string(data))
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;
.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
class myFileReaderThatStarts with arguments
{
class MissingArgumentException extends Exception{
MissingArgumentException(String s)
{
super(s);
}
}
public static void main(String[] args) throws MissingArgumentException
{
//You can test args array for value
if(args.length>0)
{
// do something with args[0]
}
else
{
// default in a path
// or
throw new MissingArgumentException("You need to start this program with a path");
}
}
Did you try Process
as mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?
You could use
Process myProcess = new Process();
try
{
// true is the default, but it is important not to set it to false
myProcess.StartInfo.UseShellExecute = true;
myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
myProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -
Base Functions
def a(x):
print('a')
return x
def b(x):
print('b')
return x
AND
if(a(True) and b(True)):
print(1,end='\n\n')
if(a(False) and b(True)):
print(2,end='\n\n')
AND-OUTPUT
a
b
1
a
OR
if(a(True) or b(False)):
print(3,end='\n\n')
if(a(False) or b(True)):
print(4,end='\n\n')
OR-OUTPUT
a
3
a
b
4
Here is the regex for the Internet Email Address using the RegularExpressionValidator in .NET
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
By the way if you put a RegularExpressionValidator on the page and go to the design view there is a ValidationExpression field that you can use to choose from a list of expressions provided by .NET. Once you choose the expression you want there is a Validation expression: textbox that holds the regex used for the validator
Try:
git stash
git checkout -b new-branch
git stash apply
If based on click here it is:
ng-click="orderReverse = orderReverse ? false : true"
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
Adding this answer as I had to lookup multiple places to achieve my use case. I had a script that runs on startup. This script runs process as a specific (passwordless) user and is running on multiple linux flavors. Here are options on different flavors: (I have taken java as target process for example)
1. RHEL / CentOS 6:
source /etc/rc.d/init.d/functions
daemon --user=myUser $JAVA_HOME/bin/java
2. RHEL 7 / SUSE12 / other linux flavors where systemd is used:
In your systemd unit file add:
User=myUser
3. Suse 11:
/sbin/startproc -u myUser $JAVA_HOME/bin/java
... or if you really want to use NOT IN
you can use
SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)
Shuffle any number of arrays together, in-place, using only NumPy.
import numpy as np
def shuffle_arrays(arrays, set_seed=-1):
"""Shuffles arrays in-place, in the same order, along axis=0
Parameters:
-----------
arrays : List of NumPy arrays.
set_seed : Seed value if int >= 0, else seed is random.
"""
assert all(len(arr) == len(arrays[0]) for arr in arrays)
seed = np.random.randint(0, 2**(32 - 1) - 1) if set_seed < 0 else set_seed
for arr in arrays:
rstate = np.random.RandomState(seed)
rstate.shuffle(arr)
And can be used like this
a = np.array([1, 2, 3, 4, 5])
b = np.array([10,20,30,40,50])
c = np.array([[1,10,11], [2,20,22], [3,30,33], [4,40,44], [5,50,55]])
shuffle_arrays([a, b, c])
A few things to note:
After the shuffle, the data can be split using np.split
or referenced using slices - depending on the application.
No.. It is not proper way. Refer the steps,
For Classpath reference:
Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.
For Deployment Assembly:
Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.
This is the proper way! Don't forget to remove environment variable. It is not required now.
Try this. Surely it will work. Try to use Maven, it will simplify you task.
The simplest way of getting parent function name is:
$caller = next(debug_backtrace())['function'];
> library(plyr)
> as.matrix(ldply(a))
V1 V2 V3 V4 V5 V6
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Well maybe a little late after 4 years haha... but I was looking for solution to do OBJECT to CSV, however most solutions here is actually for ARRAY to CSV...
After some tinkering, here is my solution to convert object into CSV, I think is pretty neat. Hope this would help someone else.
$resp = array();
foreach ($entries as $entry) {
$row = array();
foreach ($entry as $key => $value) {
array_push($row, $value);
}
array_push($resp, implode(',', $row));
}
echo implode(PHP_EOL, $resp);
Note that for the $key => $value
to work, your object
's attributes must be public, the private ones will not get fetched.
The end result is that you get something like this:
blah,blah,blah
blah,blah,blah
I call it "positional expansion", as opposed to **
which I call "keyword expansion".
Make this entry in dimens
<!--Floating action button-->
<dimen name="design_fab_image_size" tools:override="true">36dp</dimen>
Here 36dp is icon size on floating point button. This will set 36dp size for all icons for floating action button.
Updates As Per Comments
If you want to set icon size to particular Floating Action Button just go with Floating action button attributes like app:fabSize="normal" and android:scaleType="center".
<!--app:fabSize decides size of floating action button You can use normal, auto or mini as per need-->
app:fabSize="normal"
<!--android:scaleType decides how the icon drawable will be scaled on Floating action button. You can use center(to show scr image as original), fitXY, centerCrop, fitCenter, fitEnd, fitStart, centerInside.-->
android:scaleType="center"
An alternative ist to use the short form of "concatenate" which is either "r_[...]" or "c_[...]" as shown in the example code beneath (see http://wiki.scipy.org/NumPy_for_Matlab_Users for additional information):
%pylab
vector_a = r_[0.:10.] #short form of "arange"
vector_b = array([1,1,1,1])
vector_c = r_[vector_a,vector_b]
print vector_a
print vector_b
print vector_c, '\n\n'
a = ones((3,4))*4
print a, '\n'
c = array([1,1,1])
b = c_[a,c]
print b, '\n\n'
a = ones((4,3))*4
print a, '\n'
c = array([[1,1,1]])
b = r_[a,c]
print b
print type(vector_b)
Which results in:
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
[1 1 1 1]
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 1. 1. 1. 1.]
[[ 4. 4. 4. 4.]
[ 4. 4. 4. 4.]
[ 4. 4. 4. 4.]]
[[ 4. 4. 4. 4. 1.]
[ 4. 4. 4. 4. 1.]
[ 4. 4. 4. 4. 1.]]
[[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]]
[[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 4. 4. 4.]
[ 1. 1. 1.]]
From the Window menu, Reset Perspective
Right. The function you pass to getLocations() won't get called until the data is available, so returning "country" before it's been set isn't going to help you.
The way you need to do this is to have the function that you pass to geocoder.getLocations() actually do whatever it is you wanted done with the returned values.
Something like this:
function reverseGeocode(latitude,longitude){
var geocoder = new GClientGeocoder();
var latlng = new GLatLng(latitude, longitude);
geocoder.getLocations(latlng, function(addresses) {
var address = addresses.Placemark[0].address;
var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
var countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
do_something_with_address(address, country, countrycode, locality);
});
}
function do_something_with_address(address, country, countrycode, locality) {
if (country==="USA") {
alert("USA A-OK!"); // or whatever
}
}
If you might want to do something different every time you get the location, then pass the function as an additional parameter to reverseGeocode:
function reverseGeocode(latitude,longitude, callback){
// Function contents the same as above, then
callback(address, country, countrycode, locality);
}
reverseGeocode(latitude, longitude, do_something_with_address);
If this looks a little messy, then you could take a look at something like the Deferred feature in Dojo, which makes the chaining between functions a little clearer.
ERROR :
ORA-00604: error occurred at recursive SQL level 1 ORA-01882: timezone region not found
Solution: CIM setup in Centos.
/opt/oracle/product/ATG/ATG11.2/home/bin/dynamoEnv.sh
Add this java arguments:
JAVA_ARGS="${JAVA_ARGS} -Duser.timezone=EDT"
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));
Assuming $WORKING_DIR
is set to the directory... this one-liner should do it:
if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi
(otherwise just replace with your directory)
Month start from 0. 0 = January, 1 = February, 2 = March, ..., 11 = December.
This piece of code:
for s in ("fukushima", "123 is a number", ""):
print s.ljust(20), s[0].isdigit() if s else False
prints out the following:
fukushima False
123 is a number True
False
You can handle CTRL+C by catching the KeyboardInterrupt
exception. You can implement any clean-up code in the exception handler.
main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
custom.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Video1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video1"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
main.java:
package com.example.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView l1;
String[] t1={"video1","video2"};
String[] d1={"lesson1","lesson2"};
int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
l1=(ListView)findViewById(R.id.list);
l1.setAdapter(new dataListAdapter(t1,d1,i1));
}
class dataListAdapter extends BaseAdapter {
String[] Title, Detail;
int[] imge;
dataListAdapter() {
Title = null;
Detail = null;
imge=null;
}
public dataListAdapter(String[] text, String[] text1,int[] text3) {
Title = text;
Detail = text1;
imge = text3;
}
public int getCount() {
// TODO Auto-generated method stub
return Title.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.custom, parent, false);
TextView title, detail;
ImageView i1;
title = (TextView) row.findViewById(R.id.title);
detail = (TextView) row.findViewById(R.id.detail);
i1=(ImageView)row.findViewById(R.id.img);
title.setText(Title[position]);
detail.setText(Detail[position]);
i1.setImageResource(imge[position]);
return (row);
}
}
}
Try this.
What you are doing right now is you are adding .
on the string and not concatenating. It should be,
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");
or simply
$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");
an alterable way to run an .jar app is create an .bat cmd for it. for example, you have jre10 and jre8 installed on your pc,and jre10 is your default jre. but your jar is specified to work with jre8,following cmd will work:
"C:\Program Files\Java\jre1.8.0_181\bin\java.exe" -jar JabRef-4.3.1.jar
gradle supports ndk compilation by generating another Android.mk file with absolute paths to your sources. NDK supports absolute paths since r9 on OSX, r9c on Windows, so you need to upgrade your NDK to r9+.
You may run into other troubles as NDK support by gradle is preliminary. If so you can deactivate the ndk compilation from gradle by setting:
sourceSets.main {
jni.srcDirs = []
jniLibs.srcDir 'src/main/libs'
}
to be able to call ndk-build yourself and integrate libs from libs/.
btw, you have any issue compiling for x86 ? I see you haven't included it in your APP_ABI.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
rowTextView.setText(text);
layout.addView(rowTextView);
This is how I'm using this:
private List<Tag> tags = new ArrayList<>();
if(tags.isEmpty()){
Gson gson = new Gson();
Type listType = new TypeToken<List<Tag>>() {
}.getType();
tags = gson.fromJson(tour.getTagsJSONArray(), listType);
}
if (flowLayout != null) {
if(!tags.isEmpty()) {
Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
flowLayout.removeAllViews();
for (Tag tag : tags) {
FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
rowTextView.setText(tag.getLabel());
rowTextView.setLayoutParams(lparams);
flowLayout.addView(rowTextView);
}
}
Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
}
And this is my custom TextView named tag:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">
this is my tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>
efect:
In other place I'm adding textviews with language names from dialog with listview:
.htaccess:
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
Well, you have some options.
You could configure sudo to not prompt for a password. This is not recommended, due to the security risks.
You could write an expect script to read the password and supply it to sudo when required, but that's clunky and fragile.
I would recommend designing the script to run as root and drop its privileges whenever they're not needed. Simply have it sudo -u someotheruser command
for the commands that don't require root.
(If they have to run specifically as the user invoking the script, then you could have the script save the uid and invoke a second script via sudo with the id as an argument, so it knows who to su to..)
It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:
my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
for i in range(my_strings.count(undesirable_string)):
my_strings.remove(undesirable_string)
which changes my_strings to ['a', 'c', 'e']
As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:
mailto:[email protected]?subject=Subject&body=message%20goes%20here
User doesn't need to click a link if you force it to be opened with JavaScript
window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";
Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
From the man read:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
Input parameters:
int fd
file descriptor is an integer and not a file pointer. The file descriptor for stdin
is 0
void *buf
pointer to buffer to store characters read by the read
function
size_t count
maximum number of characters to read
So you can read character by character with the following code:
char buf[1];
while(read(0, buf, sizeof(buf))>0) {
// read() here read from stdin charachter by character
// the buf[0] contains the character got by read()
....
}
You Can do this without using AlertDialog
by defining new Class that extends from Dialog
Class like this:
public class myDialog extends Dialog {
public myDialog(Context context) {
super(context);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ()
.
e.g. Class A defines self.a
and self.a()
:
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:
Build Events:
copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"
copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"
Debug:
Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe
Working Directory C:\<path-to-main>\bin\debug
This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.
I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
In fact, seems like a bit complicated, is not.
get method as a parameter:
function JS_method(_callBack) {
_callBack("called");
}
You can give as a parameter method:
JS_method(function (d) {
//Finally this will work.
alert(d)
});
See this similar question and answer to searching with case insensitivity - SQL server ignore case in a where expression
Try using something like:
SELECT DISTINCT COL_NAME
FROM myTable
WHERE COL_NAME COLLATE SQL_Latin1_General_CP1_CI_AS LIKE '%priceorder%'
class MyMath
{
public dynamic Sum(dynamic x, dynamic y)
{
return (x+y);
}
}
class Demo
{
static void Main(string[] args)
{
MyMath d = new MyMath();
Console.WriteLine(d.Sum(23.2, 32.2));
}
}
I've taken elindeblom's solution and modified it - the use of strings (even if cast to dates) makes me nervous for the different formats of dates used around the world. This avoids that issue.
While not requested, I've also included time so the week ends 1 second before midnight:
DECLARE @WeekNum INT = 12,
@YearNum INT = 2014 ;
SELECT DATEADD(wk,
DATEDIFF(wk, 6,
CAST(RTRIM(@YearNum * 10000 + 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum - 1 ), 6) AS [start_of_week],
DATEADD(second, -1,
DATEADD(day,
DATEDIFF(day, 0,
DATEADD(wk,
DATEDIFF(wk, 5,
CAST(RTRIM(@YearNum * 10000
+ 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum + -1 ), 5)) + 1, 0)) AS [end_of_week] ;
Yes, I know I'm still casting but from a number. It "feels" safer to me.
This results in:
start_of_week end_of_week
----------------------- -----------------------
2014-03-16 00:00:00.000 2014-03-22 23:59:59.000
You may call U.difference(lists)
method in underscore-java library. I am the maintainer of the project. Live example
import com.github.underscore.U;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(1, 2);
List<Integer> list3 = U.difference(list1, list2);
System.out.println(list3);
// [3]
}
}
Yes, if you can acquire any WSDL file, then you can use SoapUI to create mock service of that service complete with unit test requests. I created an example of this (using Maven) that you can try out.
I found the information in this conversation so helpful that I just wanted to add how I figured it out by using the timestamp from my MySQL database and a little PHP
<?= date("Y-m-d\TH:i:s\+01:00",strtotime($column['loggedin'])) ?>
The output was: 2017-03-03T08:22:36+01:00
Thanks very much Stewe you answer was a eureka for me.
Use this:
\d{10}
I hope it helps.
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
Robust Functional programming way to do Title Case Function
Exaplin Version
function toTitleCase(input){
let output = input
.split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
.map((letter) => {
let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y
let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
return firstLetter + restLetters // conbine together
})
.join(' ') //['How' 'Are' 'You'] => 'How Are You'
return output
}
Implementation version
function toTitleCase(input){
return input
.split(' ')
.map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
.join(' ')
}
toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
The term "context" is sometimes used to refer to the object referenced by this. Its use is inappropriate because it doesn't fit either semantically or technically with ECMAScript's this.
"Context" means the circumstances surrounding something that adds meaning, or some preceding and following information that gives extra meaning. The term "context" is used in ECMAScript to refer to execution context, which is all the parameters, scope, and this within the scope of some executing code.
This is shown in ECMA-262 section 10.4.2:
Set the ThisBinding to the same value as the ThisBinding of the calling execution context
which clearly indicates that this is part of an execution context.
An execution context provides the surrounding information that adds meaning to the code that is being executed. It includes much more information than just the thisBinding.
So the value of this isn't "context", it's just one part of an execution context. It's essentially a local variable that can be set by the call to any object and in strict mode, to any value at all.
Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.
I also thought of the SELECT DISTINCT...
thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.
So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY
clause.
Imagine you have the table customer_pets
like this:
+-----------------------+
| customer | pets |
+------------+----------+
| customer1 | 2 |
| customer2 | 3 |
| customer3 | 2 |
| customer4 | 2 |
| customer5 | 3 |
| customer6 | 4 |
+------------+----------+
then
SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets
would return:
+----------------------------+
| num_customers | pets |
+-----------------+----------+
| 3 | 2 |
| 2 | 3 |
| 1 | 4 |
+-----------------+----------+
as you need.
Here is a kind of snippet for you:
app.factory('Session', function($http) {
var Session = {
data: {},
saveSession: function() { /* save session data to db */ },
updateSession: function() {
/* load data from db */
$http.get('session.json').then(function(r) { return Session.data = r.data;});
}
};
Session.updateSession();
return Session;
});
Here is Plunker example how you can use that: http://plnkr.co/edit/Fg3uF4ukl5p88Z0AeQqU?p=preview
In GAS global variables are not what they are in other languages. They are not constants nor variables available in all routines.
I thought I could use global variables for consistency amongst functions and efficiency as well. But I was wrong as pointed out by some people here at SO.
Global variable will be evaluated at each execution of a script, so not just once every time you run your application.
Global variables CAN be changed in a script (so they are not constants that cannot be changed by accident), but will be reinitialized when another script will be invoked.
There is also a speed penalty on using global variables. If within a function you use the same global variable two or more times, it will be faster to assign a local variable and use that instead.
If you want to preserve variables between all functions in your application, it might be using a cacheService will be best. I found out that looping through all files and folders on a drive takes a LOT of time. But you can store info about files and folders within cache (or even properties) and speed up at least 100 times.
The only way I use global variables now is for some prefixes and for naming widgets.
One method I did with mine, is to "Add to Source Control", and select 'Git'.
I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!
I will give a practical example in scraping web data using python, a lot of the times you will get keys with no values, in those cases you will get errors if you use dictionary['key'], whereas dictionary.get('key', 'return_otherwise') has no problems.
Similarly, I would use ''.join(list) as opposed to list[0] if you try to capture a single value from a list.
hope it helps.
[Edit] Here is a practical example:
Say, you are calling an API, which returns a JOSN file you need to parse. The first JSON looks like following:
{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","submitdate_ts":1318794805,"users_id":"2674360","project_id":"1250499"}}
The second JOSN is like this:
{"bids":{"id":16210506,"submitdate":"2011-10-16 15:53:25","submitdate_f":"10\/16\/2011 at 21:53 CEST","submitdate_f2":"p\u0159ed 2 lety","users_id":"2674360","project_id":"1250499"}}
Note that the second JSON is missing the "submitdate_ts" key, which is pretty normal in any data structure.
So when you try to access the value of that key in a loop, can you call it with the following:
for item in API_call:
submitdate_ts = item["bids"]["submitdate_ts"]
You could, but it will give you a traceback error for the second JSON line, because the key simply doesn't exist.
The appropriate way of coding this, could be the following:
for item in API_call:
submitdate_ts = item.get("bids", {'x': None}).get("submitdate_ts")
{'x': None} is there to avoid the second level getting an error. Of course you can build in more fault tolerance into the code if you are doing scraping. Like first specifying a if condition
From Spring In Action
As you can see, this class is annotated with @Controller. On its own, @Controller doesn’t do much. Its primary purpose is to identify this class as a component for component scanning. Because HomeController is annotated with @Controller, Spring’s component scanning automatically discovers it and creates an instance of HomeController as a bean in the Spring application context.
In fact, a handful of other annotations (including @Component, @Service, and @Repository) serve a purpose similar to @Controller. You could have just as effectively annotated HomeController with any of those other annotations, and it would have still worked the same. The choice of @Controller is, however, more descriptive of this component’s role in the application.
You can use:
QString qs;
// do things
std::cout << qs.toStdString() << std::endl;
It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well. Here's reference documentation for QString
.
When I was in the UNIX world (using tcsh (sigh...)), I used to have all sorts of "find" aliases/scripts setup for searching for files. I think the default "find" syntax is a little clunky, so I used to have aliases/scripts to pipe "find . -print" into grep, which allows you to use regular expressions for searching:
# finds all .java files starting in current directory
find . -print | grep '\.java'
#finds all .java files whose name contains "Message"
find . -print | grep '.*Message.*\.java'
Of course, the above examples can be done with plain-old find, but if you have a more specific search, grep can help quite a bit. This works pretty well, unless "find . -print" has too many directories to recurse through... then it gets pretty slow. (for example, you wouldn't want to do this starting in root "/")
Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.
I've added IDs to html on the total price and on the buttons. Here is the jQuery.
$('#two').click(function(){
$('#count').val('2');
$('#total').text('Product price: $1000');
});
$('#four').click(function(){
$('#count').val('4');
$('#total').text('Product price: $2000');
});
List<String> objListColor = new List<String>() { "Red", "Blue", "Green", "Yellow" };
List<String> objListDirection = new List<String>() { "East", "West", "North", "South" };
Dictionary<String, List<String>> objDicRes = new Dictionary<String, List<String>>();
objDicRes.Add("Color", objListColor);
objDicRes.Add("Direction", objListDirection);
If you wanted to search some elements based on a regex, you can use the filter
function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.
$("input:text")
.filter(function() {
return this.value.match(/[^\d]/);
})
.addClass("inputError")
;
Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id
matches /[a-z]+_\d+/
$("[id]").filter(function() {
return this.id.match(/[a-z]+_\d+/);
});
You need to set a few extra flags so that curl sends the data as JSON.
$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url
-H
: custom header, next argument is expected to be header-X
: custom HTTP verb, next argument is expected to be verb-d
: sends the next argument as data in an HTTP POST requestLocalDate maxDate = dates.stream()
.max( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
LocalDate minDate = dates.stream()
.min( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
If you wish to update several git repositories in one command - i suggest that you read a little bit on repo.
About updating the repository, you can do it by:
git fetch
git rebase origin/master
OR
git pull --rebase
For more information about using GIT you can take a look on my GIT beginners guide
I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)
bottom: new TabBar(
controller: _controller,
isScrollable: true,
tabs:
moviesTitles.map((title) { return Tab(text: title)}).toList()
,
),
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Do you mean something like this:
HTML
<div class="row">
<div class="container">
<div class="col-md-4">
left content
</div>
<div class="col-md-4 col-md-offset-4">
<div class="yellow-background">
text
<div class="pull-right">right content</div>
</div>
</div>
</div>
</div>
CSS
.yellow-background {
background: blue;
}
.pull-right {
background: yellow;
}
A full example can be found on Codepen.
As stated in the documentation of Spyder, you need to install PyQt5
first.
Open a Command Prompt as Administrator, then run:
pip install pyqt5
pip install spyder
Then you can find the spyder3.exe
in the Python3.6/Scripts folder. You can also make a shortcut to it. No need for Anaconda.
rank() : It is used to rank a record within a group of rows.
dense_rank() : The DENSE_RANK function acts like the RANK function except that it assigns consecutive ranks.
Query -
select
ENAME,SAL,RANK() over (order by SAL) RANK
from
EMP;
Output -
+--------+------+------+
| ENAME | SAL | RANK |
+--------+------+------+
| SMITH | 800 | 1 |
| JAMES | 950 | 2 |
| ADAMS | 1100 | 3 |
| MARTIN | 1250 | 4 |
| WARD | 1250 | 4 |
| TURNER | 1500 | 6 |
+--------+------+------+
Query -
select
ENAME,SAL,dense_rank() over (order by SAL) DEN_RANK
from
EMP;
Output -
+--------+------+-----------+
| ENAME | SAL | DEN_RANK |
+--------+------+-----------+
| SMITH | 800 | 1 |
| JAMES | 950 | 2 |
| ADAMS | 1100 | 3 |
| MARTIN | 1250 | 4 |
| WARD | 1250 | 4 |
| TURNER | 1500 | 5 |
+--------+------+-----------+
To extend vlad2135's answer (read his first); that is how you set up Python debugging in Visual Studio Code with Don Jayamanne's great Python extension (which is a pretty full featured IDE for Python these days, and arguably one of Visual Studio Code's best language extensions, IMO).
Basically, when you click the gear icon, it creates a launch.json file in your .vscode
directory in your workspace. You can also make this yourself, but it's probably just simpler to let Visual Studio Code do the heavy lifting. Here's an example file:
You'll notice something cool after you generate it. It automatically created a bunch of configurations (most of mine are cut off; just scroll to see them all) with different settings and extra features for different libraries or environments (like Django).
The one you'll probably end up using the most is Python; which is a plain (in my case C)Python debugger and is easiest to work with settings wise.
I'll make a short walkthrough of the JSON attributes for this one, since the others use the pretty much same configuration with only different interpreter paths and one or two different other features there.
"launch"
, but changing it to "attach"
allows the debugger to attach to an already running Python process. Instead of changing it, add a configuration of type attach and use that.false
if you don't want it, true
otherwise."${workspaceRoot}"
is the root folder you opened up as your workspace (When you go over to the file icon, the base open folder). Another neat trick if you want to get your program running quickly, or you have multiple entry points to your program is to set this to "${file}"
which will start debugging at the file you have open and in focus in the moment you hit debug."${workspaceRoot}"
.python file.py [args]
into your terminal; passing each JSON string in the list to the program in order.You can go here for more information on the Visual Studio Code file variables you can use to configure your debuggers and paths.
You can go here for the extension's own documentation on launch options, with both optional and required attributes.
You can click the Add Configuration button at the bottom right if you don't see the config template already in the file. It'll give you a list to auto generate a configuration for most of the common debug processes out there.
Now, as per vlad's answer, you may add any breakpoints you need as per normal visual debuggers, choose which run configuration you want in the top left dropdown menu and you can tap the green arrow to the left to the configuration name to start your program.
Pro tip: Different people on your team use different IDEs and they probably don't need your configuration files. Visual Studio Code nearly always puts it's IDE files in one place (by design for this purpose; I assume), launch or otherwise so make sure to add directory .vscode/
to your .gitignore if this is your first time generating a Visual Studio Code file (this process will create the folder in your workspace if you don't have it already)!
I think this valid question is already answered here. I have tried it as well. My issue was simply using picture edit (from DevExpress). and this is how I got around it:
Thank you again. Chagbert
Okay, so first of all check if you are in the correct directory where your python script is located.
On the net, they say to run the command :
python3 your_file_name.py
But it doesn't work.
What worked for me however was:
python -u my_file_name.py
The Function adds gaussian , salt-pepper , poisson and speckle noise in an image
Parameters
----------
image : ndarray
Input image data. Will be converted to float.
mode : str
One of the following strings, selecting the type of noise to add:
'gauss' Gaussian-distributed additive noise.
'poisson' Poisson-distributed noise generated from the data.
's&p' Replaces random pixels with 0 or 1.
'speckle' Multiplicative noise using out = image + n*image,where
n is uniform noise with specified mean & variance.
import numpy as np
import os
import cv2
def noisy(noise_typ,image):
if noise_typ == "gauss":
row,col,ch= image.shape
mean = 0
var = 0.1
sigma = var**0.5
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
return noisy
elif noise_typ == "s&p":
row,col,ch = image.shape
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return out
elif noise_typ == "poisson":
vals = len(np.unique(image))
vals = 2 ** np.ceil(np.log2(vals))
noisy = np.random.poisson(image * vals) / float(vals)
return noisy
elif noise_typ =="speckle":
row,col,ch = image.shape
gauss = np.random.randn(row,col,ch)
gauss = gauss.reshape(row,col,ch)
noisy = image + image * gauss
return noisy
One of these will work...
<head>_x000D_
<meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
...or it can done with JavaScript:
window.location.href = 'https://example.com/';
_x000D_
Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:
var test = {}
test[2300] = 20;
console.log(test["2300"]);
Queue
is an interface that extends Collection
in Java. It has all the functions needed to support FIFO
architecture.
For concrete implementation you may use LinkedList
. LinkedList implements Deque
which in turn implements Queue
. All of these are a part of java.util
package.
For details about method with sample example you can refer FIFO based Queue implementation in Java.
PS: Above link goes to my personal blog that has additional details on this.
First of all
<input accept="image/*" name="file" ng-value="fileToUpload"_x000D_
value="{{fileToUpload}}" file-model="fileToUpload"_x000D_
set-file-data="fileToUpload = value;" _x000D_
type="file" id="my_file" />
_x000D_
1.2 create own directive,
.directive("fileModel",function() {_x000D_
return {_x000D_
restrict: 'EA',_x000D_
scope: {_x000D_
setFileData: "&"_x000D_
},_x000D_
link: function(scope, ele, attrs) {_x000D_
ele.on('change', function() {_x000D_
scope.$apply(function() {_x000D_
var val = ele[0].files[0];_x000D_
scope.setFileData({ value: val });_x000D_
});_x000D_
});_x000D_
}_x000D_
}_x000D_
})
_x000D_
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';
Then create separate function in controller to handle form submit call. like for e.g below code:
In service function handle "responseType" param purposely so that server should not throw "byteerror".
transformRequest, to modify request format with attached identity.
withCredentials : false, for HTTP authentication information.
in controller:_x000D_
_x000D_
// code this accordingly, so that your file object _x000D_
// will be picked up in service call below._x000D_
fileUpload.uploadFileToUrl(file); _x000D_
_x000D_
_x000D_
in service:_x000D_
_x000D_
.service('fileUpload', ['$http', 'ajaxService',_x000D_
function($http, ajaxService) {_x000D_
_x000D_
this.uploadFileToUrl = function(data) {_x000D_
var data = {}; //file object _x000D_
_x000D_
var fd = new FormData();_x000D_
fd.append('file', data.file);_x000D_
_x000D_
$http.post("endpoint server path to whom sending file", fd, {_x000D_
withCredentials: false,_x000D_
headers: {_x000D_
'Content-Type': undefined_x000D_
},_x000D_
transformRequest: angular.identity,_x000D_
params: {_x000D_
fd_x000D_
},_x000D_
responseType: "arraybuffer"_x000D_
})_x000D_
.then(function(response) {_x000D_
var data = response.data;_x000D_
var status = response.status;_x000D_
console.log(data);_x000D_
_x000D_
if (status == 200 || status == 202) //do whatever in success_x000D_
else // handle error in else if needed _x000D_
})_x000D_
.catch(function(error) {_x000D_
console.log(error.status);_x000D_
_x000D_
// handle else calls_x000D_
});_x000D_
}_x000D_
}_x000D_
}])
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
_x000D_
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
It seems in Septeber 2019, YouTube updated the values that are returned by get_video_info
.
Rather than data.url_encoded_fmt_stream_map
and data.adaptive_fmts
(as used in the other older examples) now we are looking for for data.formats
and data.adaptiveFormats
.
Anyways here is what you are all here for some code that loads a YouTube video into an <audio>
element. Try it on CodePen
// YouTube video ID
var videoID = "CMNry4PE93Y";
// Fetch video info (using a proxy to avoid CORS errors)
fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
if (response.ok) {
response.text().then(ytData => {
// parse response to find audio info
var ytData = parse_str(ytData);
var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
// get the URL for the audio file
var audioURL = getAdaptiveFormats[findAudioInfo].url;
// update the <audio> element src
var youtubeAudio = document.getElementById('youtube');
youtubeAudio.src = audioURL;
});
}
});
function parse_str(str) {
return str.split('&').reduce(function(params, param) {
var paramSplit = param.split('=').map(function(value) {
return decodeURIComponent(value.replace('+', ' '));
});
params[paramSplit[0]] = paramSplit[1];
return params;
}, {});
}
_x000D_
<audio id="youtube" controls></audio>
_x000D_
You can do something similar:
var tuple = Object.freeze({ name:'Bob', age:14 })
and then refer to name and age as attributes
tuple.name
tuple.age
You could use the copy()
function :
// Will copy foo/test.php to bar/test.php
// overwritting it if necessary
copy('foo/test.php', 'bar/test.php');
Quoting a couple of relevant sentences from its manual page :
Makes a copy of the file source to dest.
If the destination file already exists, it will be overwritten.
If you are running a custom named service, you should see two executables in your Tomcat/bin directory
In my case with Tomcat 8
08/14/2019 10:24 PM 116,648 Tomcat-Custom.exe
08/14/2019 10:24 PM 119,720 Tomcat-Customw.exe
2 File(s) 236,368 bytes
Running the "w" terminated executable will let you configure Xmx in the Java
tab
As mentioned in the answer from David Cullen, I've always seen recommendations to use a line like the following one:
element_present = EC.presence_of_element_located((By.ID, 'element_id'))
WebDriverWait(driver, timeout).until(element_present)
It was difficult for me to find somewhere all the possible locators that can be used with the By
, so I thought it would be useful to provide the list here.
According to Web Scraping with Python by Ryan Mitchell:
ID
Used in the example; finds elements by their HTML id attribute
CLASS_NAME
Used to find elements by their HTML class attribute. Why is this function
CLASS_NAME
not simplyCLASS
? Using the formobject.CLASS
would create problems for Selenium's Java library, where.class
is a reserved method. In order to keep the Selenium syntax consistent between different languages,CLASS_NAME
was used instead.
CSS_SELECTOR
Finds elements by their class, id, or tag name, using the
#idName
,.className
,tagName
convention.
LINK_TEXT
Finds HTML tags by the text they contain. For example, a link that says "Next" can be selected using
(By.LINK_TEXT, "Next")
.
PARTIAL_LINK_TEXT
Similar to
LINK_TEXT
, but matches on a partial string.
NAME
Finds HTML tags by their name attribute. This is handy for HTML forms.
TAG_NAME
Finds HTML tags by their tag name.
XPATH
Uses an XPath expression ... to select matching elements.
Most of the time @cer solution works but if in case its not working then try installing it in base R (NOT in R studio). As R studio runs base R executable in background so new package will be available in R studio as well. [my experience in macOS]
Check this
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
In the form designer add a new timer using the toolbox. In properties set "Enabled" equal to "True".
The set the DataGridView
to equal your new data in the timer
INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)
I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.
1. run the application using IDE's tomcat run config.
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too.