If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.
// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)
Maybe someone could post a comment to his post, because I cannot.
In order of activity, demos/examples available, and simplicity:
Related:
You are writing to the file prior to closing your filestream:
using(FileStream fs=new FileStream(path,FileMode.OpenOrCreate))
using (StreamWriter str=new StreamWriter(fs))
{
str.BaseStream.Seek(0,SeekOrigin.End);
str.Write("mytext.txt.........................");
str.WriteLine(DateTime.Now.ToLongTimeString()+" "+DateTime.Now.ToLongDateString());
string addtext="this line is added"+Environment.NewLine;
str.Flush();
}
File.AppendAllText(path,addtext); //Exception occurrs ??????????
string readtext=File.ReadAllText(path);
Console.WriteLine(readtext);
The above code should work, using the methods you are currently using. You should also look into the using
statement and wrap your streams in a using block.
If you are using the actuator module, you can shutdown the application via JMX
or HTTP
if the endpoint is enabled.
add to application.properties
:
endpoints.shutdown.enabled=true
Following URL will be available:
/actuator/shutdown
- Allows the application to be gracefully shutdown (not enabled by default).
Depending on how an endpoint is exposed, the sensitive parameter may be used as a security hint.
For example, sensitive endpoints will require a username/password when they are accessed over HTTP
(or simply disabled if web security is not enabled).
From the Spring boot documentation
Another alternative is the old school NET USER commands:
NET USER username "password" /ADD
OK - you can't set all the options but it's a lot less convoluted for simple user creation & easy to script up in Powershell.
NET LOCALGROUP "group" "user" /add
to set group membership.
In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.
Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html
If you start the Project using the maven-tomcat-plugin
/ maven-tomcat7-plugin
, you must place the Bundle.properties
, or even the Resource.properties
in src/main/webapp/WEB-INF/classes
. Dont ask why, its because how the plugin fake a tomcat.
If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:
echo '<p style="color: red; text-align: center">
Request has been sent. Please wait for my reply!
</p>';
Not a direct answer to your question, but if you use a Skip List, it is already sorted and has O(log N) search time.
Use tiles. It saved my life.
But if you can't, there's the include tag, making it similar to php.
The body tag might not actually do what you need it to, unless you have super simple content. The body tag is used to define the body of a specified element. Take a look at this example:
<jsp:element name="${content.headerName}"
xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:attribute name="lang">${content.lang}</jsp:attribute>
<jsp:body>${content.body}</jsp:body>
</jsp:element>
You specify the element name, any attributes that element might have ("lang" in this case), and then the text that goes in it--the body. So if
content.headerName = h1
,content.lang = fr
, andcontent.body = Heading in French
Then the output would be
<h1 lang="fr">Heading in French</h1>
You don't need the SELECT
DECLARE @LastChangeDate as date
SET @LastChangeDate = GetDate()
The documentation for WAITFOR()
doesn't explicitly lay out the required string format.
This will wait for 2 seconds:
WAITFOR DELAY '00:00:02';
The format is hh:mi:ss.mmm
.
Try using "uname". For example, in Linux: "uname -a".
According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.
BTW: $OSTYPE is also set to linux-gnu
here :)
There is a module on npm called mssqlhelper
You can install it to your project by npm i mssqlhelper
Example of connecting and performing a query:
var db = require('./index');
db.config({
host: '192.168.1.100'
,port: 1433
,userName: 'sa'
,password: '123'
,database:'testdb'
});
db.query(
'select @Param1 Param1,@Param2 Param2'
,{
Param1: { type : 'NVarChar', size: 7,value : 'myvalue' }
,Param2: { type : 'Int',value : 321 }
}
,function(res){
if(res.err)throw new Error('database error:'+res.err.msg);
var rows = res.tables[0].rows;
for (var i = 0; i < rows.length; i++) {
console.log(rows[i].getValue(0),rows[i].getValue('Param2'));
}
}
);
You can read more about it here: https://github.com/play175/mssqlhelper
:o)
What if you do this (as was suggested earlier):
new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000
In WinForms:
if( Form.ModifierKeys == Keys.Shift )
It sounds like a duplicate of Stack Overflow question Detect Shift key is pressed without using events in Windows Forms?.
I use iFrame to insert the content from another page and CSS mentioned above is NOT working as expected. I have to use the parameter scrolling="no" even if I use HTML 5 Doctype
The broken pipe error usually occurs if your request is blocked or takes too long and after request-side timeout, it'll close the connection and then, when the respond-side (server) tries to write to the socket, it will throw a pipe broken error.
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
I believe the pattern given in the question was by way of example only, and the goal was to match any pattern.
If you have a sed with the GNU extension allowing insertion of a newline in the pattern space, one suggestion is:
> set string = "This is a sample 123 text and some 987 numbers"
>
> set pattern = "[0-9][0-9]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
123
987
> set pattern = "[a-z][a-z]*"
> echo $string | sed "s/$pattern/\n&\n/g" | sed -n "/$pattern/p"
his
is
a
sample
text
and
some
numbers
These examples are with tcsh (yes, I know its the wrong shell) with CYGWIN. (Edit: For bash, remove set, and the spaces around =.)
On my MAC when I start boot2docker-vm on the terminal using
boot2docker start
I see the following
To connect the Docker client to the Docker daemon, please set:
export DOCKER_CERT_PATH=
export DOCKER_TLS_VERIFY=1
export DOCKER_HOST=tcp://:2376
After setting these environment variables I was able to run the build without the problem.
Update [2016-04-28] If you are using a the recent versions of docker you can do
eval $(docker-machine env)
will set the environment
(docker-machine env
will print the export statements)
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/".$news->photo);
if(file_exists($image_path)){
//File::delete($image_path);
File::delete( $image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','??? ??????? ??? ??');
}
if you do this i guess you might not get println message in console,
@IBAction func cancel(sender: AnyObject) {
if(self.presentingViewController){
self.dismissViewControllerAnimated(false, completion: nil)
println("cancel")
}
}
@IBAction func done(sender: AnyObject) {
if(self.presentingViewController){
self.dismissViewControllerAnimated(false, completion: nil)
println("done")
}
}
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")
For python3 where -1
indicate the value that to be decremented in each step
for n in range(6,0,-1):
print(n)
Try this:
<a onclick='$("#notification").fadeOut(300, function() { $(this).remove(); });' class="notificationClose "><img src="close.png"/></a>
I think your double quotes around the onclick
were making it not work. :)
EDIT: As pointed out below, inline javascript is evil and you should probably take this out of the onclick
and move it to jQuery's click()
event handler. That is how the cool kids are doing it nowadays.
By using below method you can convert java.math.BigDecimal to String.
BigDecimal bigDecimal = new BigDecimal("10.0001");
String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
System.out.println("bigDecimal value in String: "+bigDecimalString);
Output:
bigDecimal value in String: 10.0001
If someone is in search for a quick minimal solution,
import signal
# The code which crashes program on interruption
signal.signal(signal.SIGINT, call_this_function_if_interrupted)
# The code skipped if interrupted
The user agent string is a text that the browsers themselves send to the webserver to identify themselves, so that websites can send different content based on the browser or based on browser compatibility.
Mozilla is a browser rendering engine (the one at the core of Firefox) and the fact that Chrome and IE contain the string Mozilla/4 or /5 identifies them as being compatible with that rendering engine.
Use the number_format()
function to change how a number is displayed. It will return a string
, the type of the original variable is unaffected.
The answer by @ajcr explains how the dot
and matmul
(invoked by the @
symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.
To clarify the differences take a 4x4 array and return the dot
product and matmul
product with a 3x4x2 'stack of matricies' or tensor.
import numpy as np
fourbyfour = np.array([
[1,2,3,4],
[3,2,1,4],
[5,4,6,7],
[11,12,13,14]
])
threebyfourbytwo = np.array([
[[2,3],[11,9],[32,21],[28,17]],
[[2,3],[1,9],[3,21],[28,7]],
[[2,3],[1,9],[3,21],[28,7]],
])
print('4x4*3x4x2 dot:\n {}\n'.format(np.dot(fourbyfour,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))
The products of each operation appear below. Notice how the dot product is,
...a sum product over the last axis of a and the second-to-last of b
and how the matrix product is formed by broadcasting the matrix together.
4x4*3x4x2 dot:
[[[232 152]
[125 112]
[125 112]]
[[172 116]
[123 76]
[123 76]]
[[442 296]
[228 226]
[228 226]]
[[962 652]
[465 512]
[465 512]]]
4x4*3x4x2 matmul:
[[[232 152]
[172 116]
[442 296]
[962 652]]
[[125 112]
[123 76]
[228 226]
[465 512]]
[[125 112]
[123 76]
[228 226]
[465 512]]]
Actually you can set some properties of a view's layer through interface builder. I know that I can set a layer's borderWidth and cornerRadius through xcode. borderColor doesn't work, probably because the layer wants a CGColor instead of a UIColor.
You might have to use Strings instead of numbers, but it works!
layer.cornerRadius
layer.borderWidth
layer.borderColor
Update: layer.masksToBounds = true
if (($num >= $lower_boundary) && ($num <= $upper_boundary)) {
You may want to adjust the comparison operators if you want the boundary values not to be valid.
Trying to answer it from Linux Kernel's OS View
A program becomes a process when launched into memory. A process has its own address space meaning having various segments in memory such as .text
segement for storing compiled code, .bss
for storing uninitialized static or global variables, etc.
Each process would have its own program counter and user-space stack.
Inside kernel, each process would have its own kernel stack (which is separated from user space stack for security issues) and a structure named task_struct
which is generally abstracted as the process control block, storing all the information regarding the process such as its priority, state,(and a whole lot of other chunk).
A process can have multiple threads of execution.
Coming to threads, they reside inside a process and share the address space of the parent process along with other resources which can be passed during thread creation such as filesystem resources, sharing pending signals, sharing data(variables and instructions) therefore making threads lightweight and hence allowing faster context switching.
Inside kernel, each thread has its own kernel stack along with the task_struct
structure which defines the thread. Therefore kernel views threads of same process as different entities and are schedulable in themselves. Threads in same process share a common id called as thread group id(tgid
), also they have a unique id called as the process id (pid
).
Enums are not actual classes, even if they look like it. Internally, they are treated just like their underlying type (by default Int32). Therefore, you can only do this by "copying" single values from one enum to another and casting them to their integer number to compare them for equality.
Set the g
modifier for a global match:
/…/g
Use this snippet:
@echo off
echo something
echo.
echo press enter to exit
pause >nul
exit
Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.
In fact, i have such a setup myself.
Process is to clean up and then reinstall with the following commands:
rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install )"
Notes:
curl | bash (or ruby)
commands before running themcheck pyplot
docs. For completeness,
import numpy as np
import matplotlib.pyplot as plt
#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
you can do this:
file= open(r'D:\\zzzz\\names2.txt')
file_split=set(file.read().split())
print(len(file_split))
You use File.separator
because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.
Usually, you would also have a header file that you include in your code to access the symbols.
As an extention to @Seb Kade's answer, you can fully control the colours of the selected and unselected rows using the following Style
:
<Style TargetType="{x:Type DataGridRow}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />
</Style.Resources>
</Style>
You can of course enter whichever colours you prefer. This Style
will also work for other collection items such as ListBoxItem
s (if you replace TargetType="{x:Type DataGridRow}"
with TargetType="{x:Type ListBoxItem}"
for instance).
All the above solutions are fine. And here I'm gonna combine all the solutions so that it should work for all the situations.
For Linux and Mac
sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql
For Windows
download atom or notepad++, open your dump sql file with atom or notepad++, press Ctrl+F
search the word DEFINER, and remove the line DEFINER=admin
@%
(or may be little different for you) from everywhere and save the file.
As for example
before removing that line: CREATE DEFINER=admin
@%
PROCEDURE MyProcedure
After removing that line: CREATE PROCEDURE MyProcedure
SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;
You could use the Laravel query builder, but this is not the best way to do it.
Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.
DB::table('users')
->where('email', $userEmail) // find your user by their email
->limit(1) // optional - to ensure only one record is updated.
->update(array('member_type' => $plan)); // update the record in the DB.
If you have multiple fields to update you can simply add more values to that array at the end.
I'm not sure how you could just check if something isn't undefined and at the same time get an error that it is undefined. What browser are you using?
You could check in the following way (extra = and making length a truthy evaluation)
if (typeof(sub.from) !== 'undefined' && sub.from.length) {
[update]
I see that you reset sub and thereby reset sub.from but fail to re check if sub.from exist:
for (var i = 0; i < sub.from.length; i++) {//<== assuming sub.from.exist
mainid = sub.from[i]['id'];
var sub = afcHelper_Submissions[mainid]; // <== re setting sub
My guess is that the error is not on the if statement but on the for(i...
statement. In Firebug you can break automatically on an error and I guess it'll break on that line (not on the if statement).
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
If using the DDMS to refocus doesn't work, try closing and restarting LogCat. That helped me.
This should make your TextView bold, underlined and italic at the same time.
strings.xml
<resources>
<string name="register"><u><b><i>Copyright</i></b></u></string>
</resources>
To set this String to your TextView, do this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/register" />
or In JAVA,
TextView textView = new TextView(this);
textView.setText(R.string.register);
Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So in that case SpannableString comes into action.
String tempString="Copyright";
TextView text=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(tempString);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0, spanString.length(), 0);
text.setText(spanString);
OUTPUT
Using an offset to calculate Timezone is a wrong approach, and you will always encounter problems. Time zones and daylight saving rules may change on several occasions during a year, and It's difficult to keep up with changes.
To get the system's IANA timezone in JavaScript, you should use
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
_x000D_
ecma-402/1.0 says that timeZone
may be undefined if not provided to constructor. However, future draft (3.0) fixed that issue by changing to system default timezone.
In this version of the ECMAScript Internationalization API, the
timeZone
property will remain undefined if notimeZone
property was provided in the options object provided to theIntl.DateTimeFormat
constructor. However, applications should not rely on this, as future versions may return a String value identifying the host environment’s current time zone instead.
in ecma-402/3.0 which is still in a draft it changed to
In this version of the ECMAScript 2015 Internationalization API, the
timeZone
property will be the name of the default time zone if notimeZone
property was provided in the options object provided to theIntl.DateTimeFormat
constructor. The previous version left thetimeZone
property undefined in this case.
Here's a reusable function for getting the values into an array. It takes prototypes into account too.
Object.values = function (obj) {
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
}
@littleguy23 That is correct, but you don't want to do it to multi select. So just a small change to the code:
$(document).ready(function() {
// Select - Single
$('select:not([multiple])').material_select();
});
Just pass the array to the Set constructor. The Set constructor accepts an iterable
parameter. The Array object implements the iterable
protocol, so its a valid parameter.
var arr = [55, 44, 65];_x000D_
var set = new Set(arr);_x000D_
console.log(set.size === arr.length);_x000D_
console.log(set.has(65));
_x000D_
Simple Import os package and run below command.
import os
os.system("python test.py")
Instead of specifying a deployment target in pod post install, you can delete the pod deployment target, which causes the deployment target to be inherited from the podfile platform.
You may need to run pod install for the effect to take place.
platform :ios, '12.0'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end
The name of the public class within a file has to be the same as the name of that file.
So if your file declares class WeatherArray, it needs to be named WeatherArray.java
Simply you can use web.xml to add error code and 404 error page. But make sure 404 error page must not locate under WEB-INF.
<error-page>
<error-code>404</error-code>
<location>/404.html</location>
</error-page>
This is the simplest way to do it but this have some limitation. Suppose if you want to add the same style for this page that you added other pages. In this way you can't to that. You have to use the @ResponseStatus(value = HttpStatus.NOT_FOUND)
for c in np.hsplit(array, array.shape[1]):
some_fun(c)
j[0];
dereferences a pointer to int
, so its type is int
.
(*j)[0]
has no type. *j
dereferences a pointer to an int
, so it returns an int
, and (*j)[0]
attempts to dereference an int
. It's like attempting int x = 8; x[0];
.
You can simply define the key to use directly when running the command:
ansible-playbook \
\ # Super verbose output incl. SSH-Details:
-vvvv \
\ # The Server to target: (Keep the trailing comma!)
-i "000.000.0.000," \
\ # Define the key to use:
--private-key=~/.ssh/id_rsa_ansible \
\ # The `env` var is needed if `python` is not available:
-e 'ansible_python_interpreter=/usr/bin/python3' \ # Needed if `python` is not available
\ # Dry–Run:
--check \
deploy.yml
Copy/ Paste:
ansible-playbook -vvvv --private-key=/Users/you/.ssh/your_key deploy.yml
Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule
.
var img = new Image();
$(img).load(function(){
$('.container').append($(this));
}).attr({
src: someRemoteImage
}).error(function(){
//do something if image cannot load
});
IIS will create it again AFAIK.
With lambda function
df['column'] = df['column'].apply(lambda x : x if x > 0 else 0)
I think I've found an elegant (minimum js) solution for a similar problem:
Using jQuery, you can trigger hover on body (or any other element), using .mouseover()
So I simply attach a this handler to the element's ontouchend
event like so:
var unhover = function() {_x000D_
$("body").mousover(); _x000D_
};
_x000D_
.hoverable {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: teal;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.hoverable:hover {_x000D_
background: pink;_x000D_
}
_x000D_
<div class="hoverable" ontouchend={unhover}></div>
_x000D_
This, however, only removes :hover pseudoclass from the element after some other touch event has been triggered, like swipe or another touch
You are trying to group code according to struct. C grouping is by file. You put all the functions and internal variables in a header or a header and a object ".o" file compiled from a c source file.
It is not necessary to reinvent object-orientation from scratch for a C program, which is not an object oriented language.
I have seen this before. It is a strange thing. Coders, some of them, have an aversion to passing an object they want to change into a function to change it, even though that is the standard way to do so.
I blame C++, because it hid the fact that the class object is always the first parameter in a member function, but it is hidden. So it looks like it is not passing the object into the function, even though it is.
Client.addClient(Client& c); // addClient first parameter is actually
// "this", a pointer to the Client object.
C is flexible and can take passing things by reference.
A C function often returns only a status byte or int and that is often ignored. In your case a proper form might be
err = addClient( container_t cnt, client_t c);
if ( err != 0 )
{ fprintf(stderr, "could not add client (%d) \n", err );
addClient would be in Client.h or Client.c
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
Update April 2019
Changelong for JAXB releases is at https://javaee.github.io/jaxb-v2/doc/user-guide/ch02.html
excerpts:
4.1. Changes between 2.3.0.1 and 2.4.0
JAXB RI is now JPMS modularized:
All modules have native module descriptor.
Removed jaxb-core module, which caused split package issue on JPMS.
RI binary bundle now has single jar per dependency instead of shaded fat jars.
Removed runtime class weaving optimization.
4.2. Changes between 2.3.0 and 2.3.0.1
Removed legacy technology dependencies:
com.sun.xml.bind:jaxb1-impl
net.java.dev.msv:msv-core
net.java.dev.msv:xsdlib
com.sun.xml.bind.jaxb:isorelax
4.3. Changes between 2.2.11 and 2.3.0
Adopt Java SE 9:
JAXB api can now be loaded as a module.
JAXB RI is able to run on Java SE 9 from the classpath.
Addes support for java.util.ServiceLoader mechanism.
Security fixes
Authoritative link is at https://github.com/eclipse-ee4j/jaxb-ri#maven-artifacts
Maven coordinates for JAXB artifacts
jakarta.xml.bind:jakarta.xml.bind-api: API classes for JAXB. Required to compile against JAXB.
org.glassfish.jaxb:jaxb-runtime: Implementation of JAXB, runtime used for serialization and deserialization java objects to/from xml.
JAXB fat-jar bundles:
com.sun.xml.bind:jaxb-impl: JAXB runtime fat jar.
In contrast to org.glassfish.jaxb artifacts, these jars have all dependency classes included inside. These artifacts does not contain JPMS module descriptors. In Maven projects org.glassfish.jaxb artifacts are supposed to be used instead.
org.glassfish.jaxb:jaxb-runtime:jar:2.3.2 pulls in:
[INFO] +- org.glassfish.jaxb:jaxb-runtime:jar:2.3.2:compile
[INFO] | +- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.2:compile
[INFO] | +- org.glassfish.jaxb:txw2:jar:2.3.2:compile
[INFO] | +- com.sun.istack:istack-commons-runtime:jar:3.0.8:compile
[INFO] | +- org.jvnet.staxex:stax-ex:jar:1.8.1:compile
[INFO] | +- com.sun.xml.fastinfoset:FastInfoset:jar:1.2.16:compile
[INFO] | \- jakarta.activation:jakarta.activation-api:jar:1.2.1:compile
Original Answer
Following Which artifacts should I use for JAXB RI in my Maven project? in Maven, you can use a profile like:
<profile>
<id>java-9</id>
<activation>
<jdk>9</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</profile>
Dependency tree shows:
[INFO] +- org.glassfish.jaxb:jaxb-runtime:jar:2.3.0:compile
[INFO] | +- org.glassfish.jaxb:jaxb-core:jar:2.3.0:compile
[INFO] | | +- javax.xml.bind:jaxb-api:jar:2.3.0:compile
[INFO] | | +- org.glassfish.jaxb:txw2:jar:2.3.0:compile
[INFO] | | \- com.sun.istack:istack-commons-runtime:jar:3.0.5:compile
[INFO] | +- org.jvnet.staxex:stax-ex:jar:1.7.8:compile
[INFO] | \- com.sun.xml.fastinfoset:FastInfoset:jar:1.2.13:compile
[INFO] \- javax.activation:activation:jar:1.1.1:compile
To use this in Eclipse, say Oxygen.3a Release (4.7.3a) or later, Ctrl-Alt-P, or right-click on the project, Maven, then select the profile.
I wrote a Tester
class which can test the performance:
public class Tester
{
public static void main(String[] args)
{
String text = "";
int loopCount = 10000000;
long startTime, endTime, duration1, duration2;
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.equals("");
}
endTime = System.nanoTime();
duration1 = endTime - startTime;
System.out.println(".equals(\"\") duration " +": \t" + duration1);
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.isEmpty();
}
endTime = System.nanoTime();
duration2 = endTime - startTime;
System.out.println(".isEmpty() duration "+": \t\t" + duration2);
System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
}
}
I found that using .isEmpty()
took around half the time of .equals("")
.
I believe that the real answer to your question is that they are/were independent projects and there was no centrally coordinated goal. They were in different spaces early on and have grown to overlap with time as both projects expand.
Paraphrased from the Hadoop O'Reilly book:
Pig: a dataflow language and environment for exploring very large datasets.
Hive: a distributed data warehouse
I had the same problem and even after turning the symbol loading off, the module loading in Visual Studio was terribly slow.
The solution was to turn off the antivirus software (in my case NOD32) or better yet, to add exceptions to it so that it ignores the paths from which your process is loading assemblies (in my case it is the GAC folder and the Temporary ASP.NET Files folder).
I 've used it in a function that returned the next character position in an utf-8 string:
char *next_utf8_character(const char *txt)
{
if (!txt || *txt == '\0')
return txt;
do {
txt++;
} while (((signed char) *txt) < 0 && (((unsigned char) *txt) & 0xc0) == 0xc0)
return (char *)txt;
}
Note that, this function is written from mind and not tested. The point is that you have to do the first step anyway and you have to do it before you can evaluate the condition.
Uninstallation :
sudo /Library/PostgreSQL/9.6/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
Removing the data file :
sudo rm -rf /Library/PostgreSQL
Removing the configs :
sudo rm /etc/postgres-reg.ini
And thats it.
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
The tab character is \t
. Notice the use of "
instead of '
.
$chunk = "abc\tdef\tghi";
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
...
\t horizontal tab (HT or 0x09 (9) in ASCII)
Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.
I did not have a servlet-api.jar in the application's WEB-INF/lib directory (or any other jar there). The problem was that in WEB-INF/web.xml I had this...
...
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.bizooka.net.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
...
...according to a tutorial. Removing that still allowed the servlet to function, and did not get the error.
You can try with this:
WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID as UserID FROM Articles A
Inner Join Users U
on A.userId = U.userId
Group By A.userId , U.userId ),
B as (Select us.registrationDate,
CASE
WHEN CTE_A.articleNumber < 2 THEN 'Ama'
WHEN CTE_A.articleNumber < 5 THEN 'SemiAma'
WHEN CTE_A.articleNumber < 7 THEN 'Good'
WHEN CTE_A.articleNumber < 9 THEN 'Better'
WHEN CTE_A.articleNumber < 12 THEN 'Best'
ELSE 'Outstanding'
END as Ranking,
us.hobbies, etc...
FROM USERS Us Inner Join CTE_A
on CTE_A.UserID=us.UserID)
Select * from B
If compileOptions doesn't work, try this
Disable 'Instant Run'.
Android Studio -> File -> Settings -> Build, Execution, Deployment -> Instant Run -> Disable checkbox
I like List comprehensions because of their Math (Set) syntax. So how about this:
L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]
Basically, if you enumerate over a list, you'll get the index x
and the value y
. What I'm doing here is putting the value y
into the output list (even or odd) and using the index x
to find out if that point is odd (x%2 != 0
).
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
difference is that int the inner(equi/default)join and natural join that in the natuarl join common column win will be display in single time but inner/equi/default/simple join the common column will be display double time.
document.activeElement.blur();
Works wrong on IE9 - it blurs the whole browser window if active element is document body. Better to check for this case:
if (document.activeElement != document.body) document.activeElement.blur();
As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0.
But if you still want to get inverse matrix, you can use np.linalg.pinv
, which leverages SVD to approximate initial matrix.
I had this same issue now and found that my sub-projects 'Public Header Folder Path' was set to an incorrect path (when compared with what my main project was using as its 'Header Search Path' and 'User Header Search Path').
e.g.
My main project had the following:
And the same for the User Header Search Paths
Whereas my sub-project (dependency) had the following:
Changing the 'Public Header Folder Path' to "../../Headers/BoxSDK" fixed the problem since the main project was already searching that folder ('../../Headers').
PS: I took some good screenshots, but I am not allowed to post an answer with images until I hit reputation 10 :(
In my case, simply removing the tc.log in /var/lib/mysql was enough to start mariadb/mysql again.
You can test-drive this code exactly as is using the public GitHub API (don't go over the request limit):
public class App {
public static void main(String[] args) throws IOException {
CloseableHttpClient client = HttpClients.custom().build();
// (1) Use the new Builder API (from v4.3)
HttpUriRequest request = RequestBuilder.get()
.setUri("https://api.github.com")
// (2) Use the included enum
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
// (3) Or your own
.setHeader("Your own very special header", "value")
.build();
CloseableHttpResponse response = client.execute(request);
// (4) How to read all headers with Java8
List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
httpHeaders.stream().forEach(System.out::println);
// close client and response
}
}
Most shortest code:
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'};
[~,ind]=ismember('KU', strs)
But it returns only first position in strs
. If element not found then ind=0
.
Remove key and then add again the modified key, value pair as shown below :
JSONObject js = new JSONObject();
js.put("name", "rai");
js.remove("name");
js.put("name", "abc");
I haven't used your example; but conceptually its same.
Try below:
<Spinner
android:id="@+id/YourSpinnerId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="Gender" />
Using typing so you can verify data using mypy static analysis tool:
from typing import Iterator, Any, Iterable, TypeVar, Tuple
T_ = TypeVar('T_')
Pairs_Iter = Iterator[Tuple[T_, T_]]
def legs(iterable: Iterator[T_]) -> Pairs_Iter:
begin = next(iterable)
for end in iterable:
yield begin, end
begin = end
Instead of recursive CTEs and while loops, has anyone considered a more set-based approach? Note that this function was written for the question, which was based on SQL Server 2008 and comma as the delimiter. In SQL Server 2016 and above (and in compatibility level 130 and above), STRING_SPLIT()
is a better option.
CREATE FUNCTION dbo.SplitString
(
@List nvarchar(max),
@Delim nvarchar(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_columns) AS x WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], DATALENGTH(@Delim)/2) = @Delim
) AS y
);
GO
If you want to avoid the limitation of the length of the string being <= the number of rows in sys.all_columns
(9,980 in model
in SQL Server 2017; much higher in your own user databases), you can use other approaches for deriving the numbers, such as building your own table of numbers. You could also use a recursive CTE in cases where you can't use system tables or create your own:
CREATE FUNCTION dbo.SplitString
(
@List nvarchar(max),
@Delim nvarchar(255)
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN ( WITH n(n) AS (SELECT 1 UNION ALL SELECT n+1
FROM n WHERE n <= LEN(@List))
SELECT [Value] = SUBSTRING(@List, n,
CHARINDEX(@Delim, @List + @Delim, n) - n)
FROM n WHERE n <= LEN(@List)
AND SUBSTRING(@Delim + @List, n, DATALENGTH(@Delim)/2) = @Delim
);
GO
But you'll have to append OPTION (MAXRECURSION 0)
(or MAXRECURSION <longest possible string length if < 32768>
) to the outer query in order to avoid errors with recursion for strings > 100 characters. If that is also not a good alternative then see this answer as pointed out in the comments.
(Also, the delimiter will have to be NCHAR(<=1228)
. Still researching why.)
More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:
Instead of using local imports, you may import the entire module instead of the particular object. Then, in your app
module, call mod_login.mod_login
app.py
from flask import Flask
import mod_login
# ...
do_stuff_with(mod_login.mod_login)
mod_login.py
from app import app
mod_login = something
INSERT INTO table
SELECT 'jonny', NULL
FROM dual -- Not Oracle? No need for dual, drop that line
WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
-- anything as EXISTS only checks existence
FROM table
WHERE name = 'jonny'
)
For that I would use JSON.NET to do the low-level parsing of the JSON stream and then build up the object hierarchy out of instances of the ExpandoObject
class.
I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, "android:state_selected"
, that you must use. Use a state drawable for the background of your list item, and use a different state drawable for listSelector
of your list:
list_row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@drawable/listitem_background"
>
...
</LinearLayout>
listitem_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/android:transparent" />
<item android:drawable="@drawable/listitem_normal" />
</selector>
layout.xml that includes the ListView:
...
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listitem_selector"
/>
...
listitem_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" />
<item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>
try this:
((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)
it works in my case.
I used CIFAR10 format instead of STL10 and code came out like
filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:
tf.train.start_queue_runners(sess=sess)
result = sess.run(read_input.uint8image)
img = Image.fromarray(result, "RGB")
img.save('my.jpg')
The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.
Try something like this:
var node=document.createElement("LI");
var textnode=document.createTextNode(firstname);
node.appendChild(textnode);
document.getElementById("demo").appendChild(node);
You can create a list of objects in one line using a list comprehension.
class MyClass(object): pass
objs = [MyClass() for i in range(10)]
print(objs)
width
and height
are used when going the css route.
<!DOCTYPE html>
<html>
<head>
<title>Setting Width and Height on Textareas</title>
<style>
.comments { width: 300px; height: 75px }
</style>
</head>
<body>
<textarea class="comments"></textarea>
</body>
</html>
The NoReverseMatch
error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
To start debugging it, you need to start by disecting the error message given to you.
NoReverseMatch at /my_url/
This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched
Reverse for 'my_url_name'
This is the name of the url that it cannot find
with arguments '()' and
These are the non-keyword arguments its providing to the url
keyword arguments '{}' not found.
These are the keyword arguments its providing to the url
n pattern(s) tried: []
These are the patterns that it was able to find in your urls.py files that it tried to match against
Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.
Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name
. Again, this is probably in a place you've recently changed.
Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.
urls.py
(e.g. app_name = 'my_app'
) or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp')
, then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %}
or reverse('myapp:my_url_name')
.The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding ()
brackets in the url pattern.
Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.
If they aren't correct:
The value is missing or an empty string
This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.
The keyword argument has a typo
Correct this either in the url pattern, or in the url you're constructing.
If they are correct:
Debug the regex
You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.
Common Mistakes:
Matching against the .
wild card character or any other regex characters
Remember to escape the specific characters with a \
prefix
Only matching against lower/upper case characters
Try using either a-Z
or \w
instead of a-z
or A-Z
Check that pattern you're matching is included within the patterns tried
If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS
setting (or the ordering of the apps within INSTALLED_APPS
may need looking at)
In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.
If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS
setting if applicable.
For client side files, you cannot get a list of files in a user's local directory.
If the user has provided uploaded files, you can access them via their input
element.
<input type="file" name="client-file" id="get-files" multiple />
<script>
var inp = document.getElementById("get-files");
// Access and handle the files
for (i = 0; i < inp.files.length; i++) {
let file = inp.files[i];
// do things with file
}
</script>
You should look into require.js or head.js for this.
Use InvariantCulture. The decimal separator is always "." eventually you can replace "," by "." When you display the result , use your local culture. But internally use always invariant culture
TryParse does not allway work as we would expect There are change request in .net in this area:
SOLVING
Address already in use — bind(2)” 500 error in Ruby on Rails
Recently I tried running a Rails app on a production server. Not only did it not work, but it broke my localhost:3000 development server as well. Localhost would only load a blank white page or a 500 error.
To solve this, I used two quick commands. If these don’t return a result, you may need to look elsewhere for a solution, but this is a good quick fix.
lsof -wni tcp:3000
ruby 52179 rachelchervin 50u IPv6 0x...7aa3 0t0 TCP [::1]:hbci (LISTEN) ruby 52179 rachelchervin 51u IPv4 0x...c7bb 0t0 TCP 127.0.0.1:hbci (LISTEN) ruby 52180 rachelchervin 50u IPv6 0x...7aa3 0t0 TCP [::1]:hbci (LISTEN) ruby 52180 rachelchervin 51u IPv4 0x...c7bb 0t0 TCP 127.0.0.1:hbci (LISTEN)
This command shows all of my currently running processes and their PIDs (process IDs) on the 3000 port. Because there are existing running processes that did not close correctly, my new :3000 server can’t start, hence the 500 error.
kill 52179
kill 52180
rails s
I used the Linux kill command to manually stop the offending processes. If you have more than 4, simply use kill on any PIDs until the first command comes back blank. Then, try restarting your localhost:3000 server again. This will not damage your computer! It simply kills existing ruby processes on your localhost port. A new server will start these processes all over again. Good luck!
Does this do what you want?
SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND ( PropertyValue is NULL
or PropertyValue = '' );
You can use StringUtils.swapCase()
from org.apache.commons
@ryenus, You need to loop through the result. This is how I'd do it in vbscript;
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load("kids.xml")
'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
Wscript.Echo c.text
Next
If use data from json and use Datatable v 1.10.19, you can do this:
$(document).ready(function() {
$('#example').dataTable( {
columns= [
{
"data": "name_data",
"visible": false
}
]
});
});
if you want the color to change when you have simply add the :hover
pseudo
div.e:hover {
background-color:red;
}
Garbage collection is overrated
Many people consider the introduction of garbage collection in Java one of the biggest improvements compared to C++. I consider the introduction to be very minor at best, well written C++ code does all the memory management at the proper places (with techniques like RAII), so there is no need for a garbage collector.
Now that Javascript has lookbehind (as of ES2018), on newer environments, you can avoid groups entirely in situations like these. Rather, lookbehind for what comes before the group you were capturing, and lookahead for what comes after, and replace with just !NEW_ID!
:
const str = 'name="some_text_0_some_text"';
console.log(
str.replace(/(?<=name="\w+)\d+(?=\w+")/, '!NEW_ID!')
);
_x000D_
With this method, the full match is only the part that needs to be replaced.
(?<=name="\w+)
- Lookbehind for name="
, followed by word characters (luckily, lookbehinds do not have to be fixed width in Javascript!)\d+
- Match one or more digits - the only part of the pattern not in a lookaround, the only part of the string that will be in the resulting match(?=\w+")
- Lookahead for word characters followed by "
`Keep in mind that lookbehind is pretty new. It works in modern versions of V8 (including Chrome, Opera, and Node), but not in most other environments, at least not yet. So while you can reliably use lookbehind in Node and in your own browser (if it runs on a modern version of V8), it's not yet sufficiently supported by random clients (like on a public website).
Whilst more of a workaround, if you're running an Intel Mac, you could go the virtualisation route - at least then you can run the same tools.
I would agree with Benjamin, either install MAMP or MacPorts (http://www.macports.org/). Keeping your PHP install separate is simpler and avoids messing up the core PHP install if you make any mistakes!
MacPorts is a bit better for installing other software, such as ImageMagick. See a full list of available ports at http://www.macports.org/ports.php
MAMP just really does PHP, Apache and MySQL so any future PHP modules you want will need to be manually enabled. It is incredibly easy to use though.
The way to check for null is to check for it:
DataRow[] myResultSet = myDataTable.Select("[COLUMN NAME] is null");
You can use and
and or
in the Select
statement.
In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
will always return at that point. However:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
will only return if it goes into that if
statement.
A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.
- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file
If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)
- hosts: web_servers
serial: 1
tasks:
- local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file
Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs
In list comprehension the loop variable i becomes global. After the iteration in the for loop it is a reference to the last element in your list.
If you want all matches then assign the list to a variable:
filtered = [ i for i in my_list if i=='two']
If you want only the first match you could use a function generator
try:
m = next( i for i in my_list if i=='two' )
except StopIteration:
m = None
According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras
you can do :
first test if you have h5py installed by running the
import h5py
if you dont have errors while importing h5py you are good to save:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
If you need to install h5py http://docs.h5py.org/en/latest/build.html
And in my case of a parent/child state. all the parameters declared in child state has to be known by the parent state
.state('full', {
url: '/full',
templateUrl: 'js/content/templates/FullReadView.html',
params: { opmlFeed:null, source:null },
controller: 'FullReadCtrl'
})
.state('full.readFeed', {
url: '/readFeed',
views: {
'full': {
templateUrl: 'js/content/templates/ReadFeedView.html',
params: { opmlFeed:null, source:null },
controller: 'ReadFeedCtrl'
}
}
})
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
Another workaround, not beautiful buy workable.
I have an XML file with an element called "MEMDES" with two attribute as "GRADE" and "SPD" to record the RAM module information. There are lot of dupelicate items in SPD.
So here is the code I use to remove the dupelicated items:
IEnumerable<XElement> MList =
from RAMList in PREF.Descendants("MEMDES")
where (string)RAMList.Attribute("GRADE") == "DDR4"
select RAMList;
List<string> sellist = new List<string>();
foreach (var MEMList in MList)
{
sellist.Add((string)MEMList.Attribute("SPD").Value);
}
foreach (string slist in sellist.Distinct())
{
comboBox1.Items.Add(slist);
}
Check out these docs:
If you started it in a terminal you should be ok with a ctrl + 'c'
-- this will do a clean shutdown.
However, if you are using launchctl there are specific instructions for that which will vary depending on how it was installed.
If you are using Homebrew it would be launchctl stop homebrew.mxcl.mongodb
If anyone else gets here because they're trying to set up a Jenkins slave, then you need to set the url of the host to the one it's actually using.
On the host, go to Manage Jenkins > Configure System and edit "Jenkins URL"
$cRepo = $em->getRepository('KaleLocationBundle:Country');
// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));
You can achieve this using XML notation and the MethodInvokingFactoryBean
. For an example look here.
private static StaticBean staticBean;
public void setStaticBean(StaticBean staticBean) {
StaticBean.staticBean = staticBean;
}
You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.
Note testing can also be more difficult with this approach.
Try this in your code:
import Foo from './Foo';
import Bar from './Bar';
// without default
export {
Foo,
Bar,
}
Btw, you can also do it this way:
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'
// and import somewhere..
import Baz, { Foo, Bar } from './bundle'
Using export
export const MyFunction = () => {}
export const MyFunction2 = () => {}
const Var = 1;
const Var2 = 2;
export {
Var,
Var2,
}
// Then import it this way
import {
MyFunction,
MyFunction2,
Var,
Var2,
} from './foo-bar-baz';
The difference with export default
is that you can export something, and apply the name where you import it:
// export default
export default class UserClass {
constructor() {}
};
// import it
import User from './user'
if a device has an SD card, you use:
Environment.getExternalStorageState()
if you don't have an SD card, you use:
Environment.getDataDirectory()
if there is no SD card, you can create your own directory on the device locally.
//if there is no SD card, create new directory objects to make directory on device
if (Environment.getExternalStorageState() == null) {
//create new file directory object
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}// end of SD card checking
add permissions on your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Happy coding..
I got this error while running unit tests on inmemory caching I was setting up. It flooded the cache. After invalidating the cache and restarting the VM, it worked fine.
document.ready
is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all the content.
window.onload
fires later (or at the same time in the worst/failing cases) when images and such are loaded. So, if you're using image dimensions for example, you often want to use this instead.
Also read a related question:
Difference between $(window).load() and $(document).ready() functions
Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.
public class TypedProperty<T> : Property where T : IConvertible
{
public T TypedValue
{
get
{
if (base.Value == null) return default(T);
var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
return (T)Convert.ChangeType(base.Value, type);
}
set { base.Value = value.ToString(); }
}
}
For JavaScript use this function:
function disableselect(e) {return false}
document.onselectstart = new Function (return false)
document.onmousedown = disableselect
to enable the selection use this:
function reEnable() {return true}
and use this function anywhere you want:
document.onclick = reEnable
Don't forget to return
the mapped array , like:
lapsList() {
return this.state.laps.map((data) => {
return (
<View><Text>{data.time}</Text></View>
)
})
}
Reference for the map()
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
Here's a working example, which is a fork of this answer:
$(document).ready(function(){
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
}
);
} else {
// user is not logged in
}
});
});
I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:
$(document).ready(function() {
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
FB.api('/me/likes/'+page_id, function(response) {
if (response.data[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
});
} else {
// user is not logged in
}
});
});?
Use:
c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
<script type="text/javascript">
(function(){
var d="text/javascript",e="text/css",f="stylesheet",g="script",h="link",k="head",l="complete",m="UTF-8",n=".";
function p(b){
var a=document.getElementsByTagName(k)[0];
a||(a=document.body.parentNode.appendChild(document.createElement(k)));
a.appendChild(b)}
function _loadJs(b){
var a=document.createElement(g);
a.type=d;
a.charset=m;
a.src=b;
p(a)}
function _loadCss(b){
var a=document.createElement(h);
a.type=e;
a.rel=f;
a.charset=m;
a.href=b;
p(a)}
function _isNS(b){
b=b.split(n);
for(var a=window,c=0;c<b.length;++c)
if(!(a=a[b[c]])) return ! 1;
return ! 0}
function _setupNS(b){
b=b.split(n);
for(var a=window,c=0;c<b.length;++c)
a.hasOwnProperty?a.hasOwnProperty(b[c])?a=a[b[c]]:a=a[b[c]]={}:a=a[b[c]]||(a[b[c]]={});
return a}
window.addEventListener&&"undefined"==typeof document.readyState&&window.addEventListener("DOMContentLoaded",function(){document.readyState=l},!1);
if (_isNS('google.translate.Element')){return}
(function(){
var c=_setupNS('google.translate._const');
c._cl='en';
c._cuc='googleTranslateElementInit1';
c._cac='';
c._cam='';
c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
var h='translate.googleapis.com';
var s=(true?'https':window.location.protocol=='https:'?'https':'http')+'://';
var b=s+h;
c._pah=h;
c._pas=s;
c._pbi=b+'/translate_static/img/te_bk.gif';
c._pci=b+'/translate_static/img/te_ctrl3.gif';
c._pli=b+'/translate_static/img/loading.gif';
c._plla=h+'/translate_a/l';
c._pmi=b+'/translate_static/img/mini_google.png';
c._ps=b+'/translate_static/css/translateelement.css';
c._puh='translate.google.com';
_loadCss(c._ps);
_loadJs(b+'/translate_static/js/element/main.js');
})();
})();
</script>
I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:
git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port
In Java 11+ it's possible with variables too. The only condition is it must be a constant.
For Example:
final String LEFT = "left";
final String RIGHT = "right";
final String UP = "up";
final String DOWN = "down";
String var = ...;
switch (var) {
case LEFT:
case RIGHT:
case DOWN:
default:
return 0;
}
PS. I've not tried this with earlier jdks. So please update the answer if it's supported there too.
From the now unavailable internet archive:
Go to Edit -> Preferences -> SQL Editor and set to a higher value this parameter: DBMS connection read time out (in seconds). For instance: 86400.
Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.
java.lang
does not contain a class called StringUtils
. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.
Here is my solution in windows
git filter-branch --tree-filter "rm -f 'filedir/filename'" HEAD
git push --force
make sure that the path is correct otherwise it won't work
I hope it helps
You can using SXSSFWorkbook implementation of Workbook, if you use style in your excel ,You can caching style by Flyweight Pattern
to improve your performance.
another way to check in realtime textField source :
@IBOutlet var textField1 : UITextField = UITextField()
override func viewDidLoad()
{
....
self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
}
func yourNameFunction(sender: UITextField) {
if sender.text.isEmpty {
// textfield is empty
} else {
// text field is not empty
}
}
The suggestion from @Dawood is good if that works for you.
If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/
CSS
p, h2 {
padding-left:10px;
}
create directory in /res/anim and create bottom_to_original.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="1500"
android:fromYDelta="100%"
android:toYDelta="1%" />
</set>
JAVA:
LinearLayout ll = findViewById(R.id.ll);
Animation animation;
animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.sample_animation);
ll .setAnimation(animation);
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
You are somehow using wrong AWS Credentials (AccessKey and SecretKey) of AWS Account. So make sure they are correct else you need to create new and use them - in that case may be @Prakash answer is good for you
imho there are two cases for branches that were forgot to close
Case 1: branch was not merged into default
in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.
hg up myBranch
hg commit --close-branch
Case 2: branch was merged into default
This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.
in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!
hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch
Hope this helps future readers.
I saw another question on just this topic recently (streaming pdf into iframe using dataurl only works in chrome).
I've constructed pdfs in the ast and streamed them to the browser. I was creating them first with fdf, then with a pdf class I wrote myself - in each case the pdf was created from data retrieved from a COM object based on a couple of of GET params passed in via the url.
From looking at your data sent recieved in the ajax call, it looks like you're nearly there. I haven't played with the code for a couple of years now and didn't document it as well as I'd have cared to, but - I think all you need to do is set the target of an iframe to be the url you get the pdf from. Though this may not work - the file that oututs the pdf may also have to outut a html response header first.
In a nutshell, this is the output code I used:
//We send to a browser
header('Content-Type: application/pdf');
if(headers_sent())
$this->Error('Some data has already been output, can\'t send PDF file');
header('Content-Length: '.strlen($this->buffer));
header('Content-Disposition: inline; filename="'.$name.'"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
echo $this->buffer;
So, without seeing the full response text fro the ajax call I can't really be certain what it is, though I'm inclined to think that the code that outputs the pdf you're requesting may only be doig the equivalent of the last line in the above code. If it's code you have control over, I'd try setting the headers - then this way the browser can just deal with the response text - you don't have to bother doing a thing to it.
I simply constructed a url for the pdf I wanted (a timetable) then created a string that represented the html for an iframe of the desired sie, id etc that used the constructed url as it's src. As soon as I set the inner html of a div to the constructed html string, the browser asked for the pdf and then displayed it when it was received.
function showPdfTt(studentId)
{
var url, tgt;
title = byId("popupTitle");
title.innerHTML = "Timetable for " + studentId;
tgt = byId("popupContent");
url = "pdftimetable.php?";
url += "id="+studentId;
url += "&type=Student";
tgt.innerHTML = "<iframe onload=\"centerElem(byId('box'))\" src='"+url+"' width=\"700px\" height=\"500px\"></iframe>";
}
EDIT: forgot to mention - you can send binary pdf's in this manner. The streams they contain don't need to be ascii85 or hex encoded. I used flate on all the streams in the pdf and it worked fine.
I wasn't able to do this:
UPDATE users SET created = NULL WHERE created = '0000-00-00 00:00:00'
(on MySQL 5.7.13).
I kept getting the Incorrect datetime value: '0000-00-00 00:00:00'
error.
Strangely, this worked: SELECT * FROM users WHERE created = '0000-00-00 00:00:00'
. I have no idea why the former fails and the latter works... maybe a MySQL bug?
At any case, this UPDATE query worked:
UPDATE users SET created = NULL WHERE CAST(created AS CHAR(20)) = '0000-00-00 00:00:00'
In my case the "bind-address" setting was the problem. Commenting this setting in my.cnf
did not help, because in my case mysql set the default to 127.0.0.1 for some reason.
To verify what setting MySql is currently using, open the command line on your local box:
mysql -h localhost -u myname -pmypass mydb
Read out the current setting:
Show variables where variable_name like "bind%"
You should see 0.0.0.0 here if you want to allow access from all hosts. If this is not the case, edit your /etc/mysql/my.cnf
and set bind-address under the [mysqld] section:
bind-address=0.0.0.0
Finally restart your MySql server to pick up the new setting:
sudo service mysql restart
Try again and check if the new setting has been picked up.
The necessary method is Mockito#verify:
public static <T> T verify(T mock,
VerificationMode mode)
mock
is your mocked object and mode
is the VerificationMode
that describes how the mock should be verified. Possible modes are:
verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");
You'll need these static imports from the Mockito
class in order to use the verify
method and these verification modes:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
So in your case the correct syntax will be:
Mockito.verify(mock, times(4)).send()
This verifies that the method send
was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.
If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode
. A simple
verify(mock).someMethod("was called once");
would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");
.
It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");
, but we can write
verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");
instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.
Just use:
for (int i = 0; i < v.size(); i++)
{
v[i] -= valueToSubstract;
}
Or its equivalent (and more readable?):
for (int i = 0; i < v.size(); i++)
v[i] = v[i] - valueToSubstract;
The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.
I think the article is now here: new location
The link shown here was dead.
basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:
Image playbutton;
try
{
playbutton = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
Image frame;
try
{
frame = Image.FromFile(/*somekindofpath*/);
}
catch (Exception ex)
{
return;
}
using (frame)
{
using (var bitmap = new Bitmap(width, height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(frame,
new Rectangle(0,
0,
width,
height),
new Rectangle(0,
0,
frame.Width,
frame.Height),
GraphicsUnit.Pixel);
canvas.DrawImage(playbutton,
(bitmap.Width / 2) - (playbutton.Width / 2),
(bitmap.Height / 2) - (playbutton.Height / 2));
canvas.Save();
}
try
{
bitmap.Save(/*somekindofpath*/,
System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception ex) { }
}
}
Here's one xmlstarlet use case to extract data from nested elements elem1, elem2 to one line of text from this type of XML (also showing how to handle namespaces):
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<mydoctype xmlns="http://xml-namespace-uri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml-namespace-uri http://xsd-uri" format="20171221A" date="2018-05-15">
<elem1 time="0.586" length="10.586">
<elem2 value="cue-in" type="outro" />
</elem1>
</mydoctype>
The output will be
0.586 10.586 cue-in outro
In this snippet, -m matches the nested elem2, -v outputs attribute values (with expressions and relative addressing), -o literal text, -n adds a newline:
xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2' \
-v ../@time -o " " -v '../@time + ../@length' -o " " -v @value -o " " -v @type -n file.xml
If more attributes are needed from elem1, one can do it like this (also showing the concat() function):
xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2/..' \
-v 'concat(@time, " ", @time + @length, " ", ns:elem2/@value, " ", ns:elem2/@type)' -n file.xml
Note the (IMO unnecessary) complication with namespaces (ns, declared with -N), that had me almost giving up on xpath and xmlstarlet, and writing a quick ad-hoc converter.
You might want to try this approach:
var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);
console.log(jsonData[0].name)
Update 03-Oct-19
new script that displays 10second countdown then launches chrome/chromiumn in fullscreen kiosk mode.
more updates to chrome required script update to allow autoplaying video with audio. Note --overscroll-history-navigation=0 isn't working currently will need to disable this flag by going to chrome://flags/#overscroll-history-navigation in your browser and setting to disabled.
@echo off
echo Countdown to application launch...
timeout /t 10
"C:\Program Files (x86)\chrome-win32\chrome.exe" --chrome --kiosk http://localhost/xxxx --incognito --disable-pinch --no-user-gesture-required --overscroll-history-navigation=0
exit
might need to set chrome://flags/#autoplay-policy if running an older version of chrome (60 below)
Update 11-May-16
There have been many updates to chrome since I posted this and have had to alter the script alot to keep it working as I needed.
Couple of issues with newer versions of chrome:
Because of the restore error switched out to incognito mode as this launches a clear version all the time and does not save what the user was viewing and so if it crashes there is nothing to restore. Also the auto up in newer versions of chrome being a pain to try and disable I switched out to use chromium as it does not auto update and still gives all the modern features of chrome. Note make sure you download the top version of chromium this comes with all audio and video codecs as the basic version of chromium does not support all codecs.
@echo off echo Step 1 of 2: Waiting a few seconds before starting the Kiosk... "C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL echo Step 2 of 5: Waiting a few more seconds before starting the browser... "C:\windows\system32\ping" -n 5 -w 1000 127.0.0.1 >NUL echo Final 'invisible' step: Starting the browser, Finally... "C:\Program Files (x86)\Google\Chromium\chrome.exe" --chrome --kiosk http://127.0.0.1/xxxx --incognito --disable-pinch --overscroll-history-navigation=0 exit
Outdated
I use this for exhibitions to lock down screens. I think its what your looking for.
Next part is the script that I use to start close and restart chrome again in kiosk mode. The locations is where I have chrome installed so it might be abit different for you depending on your install.
Open your text editor of choice or just notepad and past the below code in, make sure its in the same format/order as below. Save it to your desktop as what ever you like so for this example chrome_startup_script.txt next right click it and rename, remove the txt from the end and put in bat instead. double click this to launch the script to see if its working correctly.
A command line box should appear and run through the script, chrome will start and then close down the reason to do this is to remove any error reports such as if the pc crashed, when chrome starts again without this it would show the yellow error bar at the top saying chrome did not shut down properly would you like to restore it. After a few seconds chrome should start again and in kiosk mode and will point to what ever homepage you have set.
@echo off
echo Step 1 of 5: Waiting a few seconds before starting the Kiosk...
"C:\windows\system32\ping" -n 31 -w 1000 127.0.0.1 >NUL
echo Step 2 of 5: Starting browser as a pre-start to delete error messages...
"C:\google_homepage.url"
echo Step 3 of 5: Waiting a few seconds before killing the browser task...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Step 4 of 5: Killing the browser task gracefully to avoid session restore...
Taskkill /IM chrome.exe
echo Step 5 of 5: Waiting a few seconds before restarting the browser...
"C:\windows\system32\ping" -n 11 -w 1000 127.0.0.1 >NUL
echo Final 'invisible' step: Starting the browser, Finally...
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --kiosk --overscroll-history-navigation=0"
exit
Note: The number after the -n of the ping is the amount of seconds (minus one second) to wait before starting the link (or application in the next line)
Finally if this is all working then you can drag and drop the .bat file into the startup folder in windows and this script will launch each time windows starts.
Update:
With recent versions of chrome they have really got into enabling touch gestures, this means that swiping left or right on a touchscreen will cause the browser to go forward or backward in history. To prevent this we need to disable the history navigation on the back and forward buttons to do that add the following --overscroll-history-navigation=0
to the end of the script.
If you want them gone by default, you can set:
Chart.defaults.scale.gridLines.display = false;
activate env by the Following Command
source pathetoYourEnv/bin/activate
then run command
python manage.py runserver
Eclipse has got the concept of incremental builds.This is incredibly useful as it saves a lot of time.
How is this Useful
Say you just changed a single .java file. The incremental builders will be able to compile the code without having to recompile everything(which will take more time).
Now what's the problem with Maven Plugins
Most of the maven plugins aren't designed for incremental builds and hence it creates trouble for m2e. m2e doesn't know if the plugin goal is something which is crucial or if it is irrelevant. If it just executes every plugin when a single file changes, it's gonna take lots of time.
This is the reason why m2e relies on metadata information to figure out how the execution should be handled. m2e has come up with different options to provide this metadata information and the order of preference is as below(highest to lowest)
1,2 refers to specifying pluginManagement section in the tag of your pom file or any of it's parents. M2E reads this configuration to configure the project.Below snippet instructs m2e to ignore the jslint
and compress
goals of the yuicompressor-maven-plugin
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>net.alchim31.maven</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>compress</goal>
<goal>jslint</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
3) In case you don't prefer polluting your pom file with this metadata, you can store this in an external XML file(option 3). Below is a sample mapping file which instructs m2e to ignore the jslint
and compress
goals of the yuicompressor-maven-plugin
<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>net.alchim31.maven</groupId>
<artifactId>yuicompressor-maven-plugin</artifactId>
<versionRange>[1.0,)</versionRange>
<goals>
<goal>compress</goal>
<goal>jslint</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
4) In case you don't like any of these 3 options, you can use an m2e connector(extension) for the maven plugin.The connector will in turn provide the metadata to m2e. You can see an example of the metadata information within a connector at this link . You might have noticed that the metadata refers to a configurator. This simply means that m2e will delegate the responsibility to that particular java class supplied by the extension author.The configurator can configure the project(like say add additional source folders etc) and decide whether to execute the actual maven plugin during an incremental build(if not properly managed within the configurator, it can lead to endless project builds)
Refer these links for an example of the configuratior(link1,link2). So in case the plugin is something which can be managed via an external connector then you can install it. m2e maintains a list of such connectors contributed by other developers.This is known as the discovery catalog. m2e will prompt you to install a connector if you don't already have any lifecycle mapping metadata for the execution through any of the options(1-6) and the discovery catalog has got some extension which can manage the execution.
The below image shows how m2e prompts you to install the connector for the build-helper-maven-plugin. .
5)m2e encourages the plugin authors to support incremental build and supply lifecycle mapping within the maven-plugin itself.This would mean that users won't have to use any additional lifecycle mappings or connectors.Some plugin authors have already implemented this
6) By default m2e holds the lifecycle mapping metadata for most of the commonly used plugins like the maven-compiler-plugin and many others.
Now back to the question :You can probably just provide an ignore life cycle mapping in 1, 2 or 3 for that specific goal which is creating trouble for you.
You can try to apply new architecture approach anounced at Google I/O 2017.
It also includes new ORM library called Room
It contains three main components: @Entity, @Dao and @Database
User.java
@Entity
public class User {
@PrimaryKey
private int uid;
@ColumnInfo(name = "first_name")
private String firstName;
@ColumnInfo(name = "last_name")
private String lastName;
// Getters and setters are ignored for brevity,
// but they're required for Room to work.
}
UserDao.java
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
@Query("SELECT * FROM user WHERE first_name LIKE :first AND "
+ "last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
@Insert
void insertAll(User... users);
@Delete
void delete(User user);
}
AppDatabase.java
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
Creates a copy of the ArrayObject
<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;
// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);
?>
from https://www.php.net/manual/en/arrayobject.getarraycopy.php
This should work in Matlab:
set(gca, 'XAxisLocation', 'origin')
Options are: bottom, top, origin.
For Y.axis:
YAxisLocation; left, right, origin
To achieve the requirement from the question, we can put classes into interface:
public interface Shapes {
class AShape{
}
class ZShape{
}
}
and then use as author tried before:
public class Test {
public static void main(String[] args) {
Shape s = new Shapes.ZShape();
}
}
If we looking for the proper "logical" solution, should be used fabric
design pattern
OK, there are two ways of doing that:
// GLOBAL_CONCURRENT_QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE
{
dispatch_queue_t globalConcurrentQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalConcurrentQ, ^{
// DATA PROCESSING 1
sleep(1);
NSLog(@"Hello world chekpoint 1");
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 1
sleep(1);
NSLog(@"Hello world chekpoint 2");
});
/* the control to come here after UI UPDATION 1 */
sleep(1);
NSLog(@"Hello world chekpoint 3");
// DATA PROCESSING 2
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 2
sleep(1);
NSLog(@"Hello world chekpoint 4");
});
/* the control to come here after UI UPDATION 2 */
sleep(1);
NSLog(@"Hello world chekpoint 5");
// DATA PROCESSING 3
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 3
sleep(1);
NSLog(@"Hello world chekpoint 6");
});
});
}
// SERIAL QUEUE
- (void)doCalculationsAndUpdateUIsWith_GlobalQUEUE
{
dispatch_queue_t serialQ = dispatch_queue_create("com.example.MyQueue", NULL);
dispatch_async(serialQ, ^{
// DATA PROCESSING 1
sleep(1);
NSLog(@"Hello world chekpoint 1");
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 1
sleep(1);
NSLog(@"Hello world chekpoint 2");
});
sleep(1);
NSLog(@"Hello world chekpoint 3");
// DATA PROCESSING 2
dispatch_sync(dispatch_get_main_queue(), ^{
// UI UPDATION 2
sleep(1);
NSLog(@"Hello world chekpoint 4");
});
});
}
What is your output when you do java -version
? This will tell you what version the running JVM is.
The Unsupported major.minor version 51.0 error could mean:
Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor
error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)
See: http://www.java.com/en/download/manual.jsp (7 Update 25 )
and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)
for the latest version of the JRE and JDK respectively.
EDIT:
Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.
Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.
I don't know if this is new in sklearn
or pandas
, but I'm able to pass the data frame directly to sklearn
without converting the data frame to a numpy array or any other data types.
from sklearn import linear_model
reg = linear_model.LinearRegression()
reg.fit(df[['B', 'C']], df['A'])
>>> reg.coef_
array([ 4.01182386e-01, 3.51587361e-04])
give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="click me"
android:layout_weight="0.5"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Hello World"
android:layout_weight="0.5"/>
</LinearLayout>
Updated 2018
See if this example helps: http://bootply.com/mQh8DyRfWY
The brand is centered using..
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
top: 0;
text-align: center;
margin: auto;
}
Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner
.
EDIT - Another approach is using transform: translateX(-50%);
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
http://www.bootply.com/V7vKDfk46G
In Bootstrap 4, mx-auto
or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.
Also see:
No. The method for appending an entire sequence is list.extend()
.
>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]
You can also find dependencies version details in package.json file as following:
You can use wc -l
to figure out the total # of lines.
You can then combine head
and tail
to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:
tail -1562 MyHugeLogFile.log | head -838 | ....
Or there's probably an easier way using sed
or awk
.
Just a note to add to this post. Later versions of R
seem to have buried Rscript
somewhat. For R 3.1.2-1 on OSX downloaded Jan 2015 I found Rscript
in
/sw/Library/Frameworks/R.framework/Versions/3.1/Resources/bin/Rscript
So, instead of something like #! /sw/bin/Rscript
, I needed to use the following at the top of my script.
#! /sw/Library/Frameworks/R.framework/Versions/3.1/Resources/bin/Rscript
The locate Rscript
might be helpful to you.
<bean id="someBean"
class="com.somePackage.SomeClass">
<property name="myList">
<list value-type="com.somePackage.TypeForList">
<ref bean="someBeanInTheList"/>
<ref bean="someOtherBeanInTheList"/>
<ref bean="someThirdBeanInTheList"/>
</list>
</property>
</bean>
And in SomeClass:
class SomeClass {
List<TypeForList> myList;
@Required
public void setMyList(List<TypeForList> myList) {
this.myList = myList;
}
}
Try to update @angular/core
using ng update @angular/cli @angular/core
I was trying to make the calendar selects a date by default and highlights it for the user. However, i tried using all the options above but i only managed to set the calendar's selected date.
protected void Page_Load(object sender, EventArgs e)
Calendar1.SelectedDate = DateTime.Today;
}
the previous code did NOT highlight the selection, although it set the SelectedDate to today.
However, to select and highlight the following code will work properly.
protected void Page_Load(object sender, EventArgs e)
{
DateTime today = DateTime.Today;
Calendar1.TodaysDate = today;
Calendar1.SelectedDate = Calendar1.TodaysDate;
}
check this link: http://msdn.microsoft.com/en-us/library/8k0f6h1h(v=VS.85).aspx
If you find yourself writing the above solution as often as I do then you could implement it as a generic:
public static int GetEnumEntries<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}
Simply You can do it
import time
delay=60*15 ###for 15 minutes delay
close_time=time.time()+delay
while True:
##bla bla
###bla bla
if time.time()>close_time
break
The Maven manual says to do this:
mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
Here is a source:
Code:
<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
header('Location: http://detectmobilebrowser.com/mobile');
?>
I've been recently working on it. Check out this jsFiddle test, try it yourself changing the width of the base table to check the behavior).
The solution is to embedded a table into another:
<table style="width: 200px;border:0;border-collapse:collapse">
<tbody>
<tr>
<td style="width: 100%;">
<table style="width: 100%;border:0;border-collapse:collapse">
<tbody>
<tr>
<td>
<div style="position: relative;overflow:hidden">
<p> </p>
<p style="overflow:hidden;text-overflow: ellipsis;position: absolute; top: 0pt; left: 0pt;width:100%">This cells has more content</p>
</div>
</td>
</tr>
</tbody>
</table>
</td>
<td style="white-space:nowrap">Less content here</td>
</tr>
</tbody>
</table>
Is Fred now happy with Celldito's expansion?
This situation occured if there are object in repository, which creates by current transaction.
Simple scenario:
Same thing when adding same files from two working copies.
On checking add the value for checkbox and on dechecking subtract the value
$('#myDiv').change(function() {_x000D_
var values = 0.00;_x000D_
{_x000D_
$('#myDiv :checked').each(function() {_x000D_
//if(values.indexOf($(this).val()) === -1){_x000D_
values=values+parseFloat(($(this).val()));_x000D_
// }_x000D_
});_x000D_
console.log( parseFloat(values));_x000D_
}_x000D_
});
_x000D_
<div id="myDiv">_x000D_
<input type="checkbox" name="type" value="4.00" />_x000D_
<input type="checkbox" name="type" value="3.75" />_x000D_
<input type="checkbox" name="type" value="1.25" />_x000D_
<input type="checkbox" name="type" value="5.50" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
Read committed is an isolation level that guarantees that any data read was committed at the moment is read. It simply restricts the reader from seeing any intermediate, uncommitted, 'dirty' read. It makes no promise whatsoever that if the transaction re-issues the read, will find the Same data, data is free to change after it was read.
Repeatable read is a higher isolation level, that in addition to the guarantees of the read committed level, it also guarantees that any data read cannot change, if the transaction reads the same data again, it will find the previously read data in place, unchanged, and available to read.
The next isolation level, serializable, makes an even stronger guarantee: in addition to everything repeatable read guarantees, it also guarantees that no new data can be seen by a subsequent read.
Say you have a table T with a column C with one row in it, say it has the value '1'. And consider you have a simple task like the following:
BEGIN TRANSACTION;
SELECT * FROM T;
WAITFOR DELAY '00:01:00'
SELECT * FROM T;
COMMIT;
That is a simple task that issue two reads from table T, with a delay of 1 minute between them.
If you follow the logic above you can quickly realize that SERIALIZABLE transactions, while they may make life easy for you, are always completely blocking every possible concurrent operation, since they require that nobody can modify, delete nor insert any row. The default transaction isolation level of the .Net System.Transactions
scope is serializable, and this usually explains the abysmal performance that results.
And finally, there is also the SNAPSHOT isolation level. SNAPSHOT isolation level makes the same guarantees as serializable, but not by requiring that no concurrent transaction can modify the data. Instead, it forces every reader to see its own version of the world (it's own 'snapshot'). This makes it very easy to program against as well as very scalable as it does not block concurrent updates. However, that benefit comes with a price: extra server resource consumption.
Supplemental reads:
In my Spring Boot app I resolved a similar type of issue like this:
@Autowired
private EntityManager entityManager;
public User findByEmail(String email) {
User user = null;
Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email=:email");
query.setParameter("email", email);
try {
user = (User) query.getSingleResult();
} catch (Exception e) {
// Handle exception
}
return user;
}
OK.. We needed to compare a dynamic number of product names...
There's probably a better way... but this works for me...
... because....Strings are just Arrays of characters.... :>}
// Compare Strings ... Return Matching Text and Differences with Product IDs...
// From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";
$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";
$ProductNames = array(
$productID1 => $productName1,
$productID2 => $productName2
);
function compareNames($ProductNames){
// Convert NameStrings to Arrays...
foreach($ProductNames as $id => $product_name){
$Package1[$id] = explode(" ",$product_name);
}
// Get Matching Text...
$Matching = call_user_func_array('array_intersect', $Package1 );
$MatchingText = implode(" ",$Matching);
// Get Different Text...
foreach($Package1 as $id => $product_name_chunks){
$Package2 = array($product_name_chunks,$Matching);
$diff = call_user_func_array('array_diff', $Package2 );
$DifferentText[$id] = trim(implode(" ", $diff));
}
$results[$MatchingText] = $DifferentText;
return $results;
}
$Results = compareNames($ProductNames);
print_r($Results);
// Gives us this...
[EcoPlus Premio Jet]
[abc123] => 600
[xyz789] => 800
I made this helper method in case someone need start and end position from a String.
public static TextView createLink(TextView targetTextView, String completeString,
String partToClick, ClickableSpan clickableAction) {
SpannableString spannableString = new SpannableString(completeString);
// make sure the String is exist, if it doesn't exist
// it will throw IndexOutOfBoundException
int startPosition = completeString.indexOf(partToClick);
int endPosition = completeString.lastIndexOf(partToClick) + partToClick.length();
spannableString.setSpan(clickableAction, startPosition, endPosition,
Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
targetTextView.setText(spannableString);
targetTextView.setMovementMethod(LinkMovementMethod.getInstance());
return targetTextView;
}
And here is how you use it
private void initSignUp() {
String completeString = "New to Reddit? Sign up here.";
String partToClick = "Sign up";
ClickableTextUtil
.createLink(signUpEditText, completeString, partToClick,
new ClickableSpan() {
@Override
public void onClick(View widget) {
// your action
Toast.makeText(activity, "Start Sign up activity",
Toast.LENGTH_SHORT).show();
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
// this is where you set link color, underline, typeface etc.
int linkColor = ContextCompat.getColor(activity, R.color.blumine);
ds.setColor(linkColor);
ds.setUnderlineText(false);
}
});
}
Try this
UPDATE `table` SET `uid` = CASE
WHEN id = 1 THEN 2952
WHEN id = 2 THEN 4925
WHEN id = 3 THEN 1592
ELSE `uid`
END
WHERE id in (1,2,3)
For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.
String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
In .NET 4.0, the Lambda Expression can be applied to the global filter as such
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
@fthiella 's solution is very elegant.
If in future you want show more than user_id
you could use joins, and there in one line could be all data you need.
If you want to use AND
conditions, and the conditions are in multiple lines in your table, you can use JOINS
example:
SELECT `w_name`.`user_id`
FROM `wp_usermeta` as `w_name`
JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id`
AND `w_name`.`meta_key` = 'first_name'
AND `w_year`.`meta_key` = 'yearofpassing'
JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id
AND `w_city`.`meta_key` = 'u_city'
JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id`
AND `w_course`.`meta_key` = 'us_course'
WHERE
`w_name`.`meta_value` = '$us_name' AND
`w_year`.meta_value = '$us_yearselect' AND
`w_city`.`meta_value` = '$us_reg' AND
`w_course`.`meta_value` = '$us_course'
Other thing: Recommend to use prepared statements, because mysql_*
functions is not SQL injection save, and will be deprecated.
If you want to change your code the less as possible, you can use mysqli_
functions:
http://php.net/manual/en/book.mysqli.php
Recommendation:
Use indexes in this table. user_id
highly recommend to be and index, and recommend to be the meta_key
AND meta_value
too, for faster run of query.
The explain:
If you use AND
you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.
Tests: Table Data:
PRIMARY INDEX
int varchar(255) varchar(255)
/ \ |
+---------+---------------+-----------+
| user_id | meta_key | meta_value|
+---------+---------------+-----------+
| 1 | first_name | Kovge |
+---------+---------------+-----------+
| 1 | yearofpassing | 2012 |
+---------+---------------+-----------+
| 1 | u_city | GaPa |
+---------+---------------+-----------+
| 1 | us_course | PHP |
+---------+---------------+-----------+
The result of Query with $us_name='Kovge'
$us_yearselect='2012'
$us_reg='GaPa'
, $us_course='PHP'
:
+---------+
| user_id |
+---------+
| 1 |
+---------+
So it should works.
Here is a fast solution for C that works in GCC and Clang; ready to be copied and pasted.
#include <limits.h>
unsigned int fls(const unsigned int value)
{
return (unsigned int)1 << ((sizeof(unsigned int) * CHAR_BIT) - __builtin_clz(value) - 1);
}
unsigned long flsl(const unsigned long value)
{
return (unsigned long)1 << ((sizeof(unsigned long) * CHAR_BIT) - __builtin_clzl(value) - 1);
}
unsigned long long flsll(const unsigned long long value)
{
return (unsigned long long)1 << ((sizeof(unsigned long long) * CHAR_BIT) - __builtin_clzll(value) - 1);
}
And a little improved version for C++.
#include <climits>
constexpr unsigned int fls(const unsigned int value)
{
return (unsigned int)1 << ((sizeof(unsigned int) * CHAR_BIT) - __builtin_clz(value) - 1);
}
constexpr unsigned long fls(const unsigned long value)
{
return (unsigned long)1 << ((sizeof(unsigned long) * CHAR_BIT) - __builtin_clzl(value) - 1);
}
constexpr unsigned long long fls(const unsigned long long value)
{
return (unsigned long long)1 << ((sizeof(unsigned long long) * CHAR_BIT) - __builtin_clzll(value) - 1);
}
The code assumes that value
won't be 0
. If you want to allow 0, you need to modify it.
Realizing that "applying" "nlargest" to groupby object works just as fine:
Additional advantage - also can fetch top n values if required:
In [85]: import pandas as pd
In [86]: df = pd.DataFrame({
...: 'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4','MM4'],
...: 'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
...: 'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
...: 'count' : [3,2,5,8,10,1,2,2,7]
...: })
## Apply nlargest(1) to find the max val df, and nlargest(n) gives top n values for df:
In [87]: df.groupby(["sp", "mt"]).apply(lambda x: x.nlargest(1, "count")).reset_index(drop=True)
Out[87]:
count mt sp val
0 3 S1 MM1 a
1 5 S3 MM1 cb
2 8 S3 MM2 mk
3 10 S4 MM2 bg
4 7 S2 MM4 uyi