It sounds like you answered your own question. get_class
will get you the class name. It is procedural and maybe that is what is causing the confusion. Take a look at the php documentation for get_class
Here is their example:
<?php
class foo
{
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}
// create an object
$bar = new foo();
// external call
echo "Its name is " , get_class($bar) , "\n"; // It's name is foo
// internal call
$bar->name(); // My name is foo
To make it more like your example you could do something like:
<?php
class MyClass
{
public static function getClass()
{
return get_class();
}
}
Now you can do:
$className = MyClass::getClass();
This is somewhat limited, however, because if my class is extended it will still return 'MyClass'. We can use get_called_class
instead, which relies on Late Static Binding, a relatively new feature, and requires PHP >= 5.3.
<?php
class MyClass
{
public static function getClass()
{
return get_called_class();
}
public static function getDefiningClass()
{
return get_class();
}
}
class MyExtendedClass extends MyClass {}
$className = MyClass::getClass(); // 'MyClass'
$className = MyExtendedClass::getClass(); // 'MyExtendedClass'
$className = MyExtendedClass::getDefiningClass(); // 'MyClass'
You can use the Chrome DevTools Utilities API copy()
command for copying the string representation of the specified object to the clipboard.
If you have lots of objects then you can actually JSON.stringify() all your objects and keep on appending them to a string. Now use copy()
method to copy the complete string to clipboard.
A persistent context represents the entities which hold data and are qualified to be persisted in some persistent storage like a database. Once we commit
a transaction under a session which has these entities attached with, Hibernate flushes the persistent context and changes(insert/save, update or delete) on them are persisted in the persistent storage.
Exception
is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception
must handle or declare it.
The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.
Example:
java.sql.Connection conn = <connect procedure>;
conn.close();
try {
conn.getMetaData();
} catch (Exception e) {
System.out.println("Connection is closed");
}
Heres how this code looks:
Heres my drag and drop code:
var boxView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.blackColor()
addSavingPhotoView()
//Custom button to test this app
var button = UIButton(frame: CGRect(x: 20, y: 20, width: 20, height: 20))
button.backgroundColor = UIColor.redColor()
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
}
func addSavingPhotoView() {
// You only need to adjust this frame to move it anywhere you want
boxView = UIView(frame: CGRect(x: view.frame.midX - 90, y: view.frame.midY - 25, width: 180, height: 50))
boxView.backgroundColor = UIColor.whiteColor()
boxView.alpha = 0.8
boxView.layer.cornerRadius = 10
//Here the spinnier is initialized
var activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
activityView.startAnimating()
var textLabel = UILabel(frame: CGRect(x: 60, y: 0, width: 200, height: 50))
textLabel.textColor = UIColor.grayColor()
textLabel.text = "Saving Photo"
boxView.addSubview(activityView)
boxView.addSubview(textLabel)
view.addSubview(boxView)
}
func buttonAction(sender:UIButton!) {
//When button is pressed it removes the boxView from screen
boxView.removeFromSuperview()
}
Here is an open source version of this: https://github.com/goktugyil/CozyLoadingActivity
SHOW TABLES
mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1 |
| t2 |
| t3 |
+----------------+
3 rows in set (0.00 sec)
SHOW TABLES IN db_name
mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3 |
| t4 |
| t5 |
+----------------------+
3 rows in set (0.00 sec)
mysql> SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3 |
| t4 |
| t5 |
+------------+
3 rows in set (0.02 sec)
you have fetched just 1 row. fix like this:
while ( $tables = $result->fetch_array())
{
echo $tmp[0]."<br>";
}
and I think, information_schema would be better than SHOW TABLES
SELECT TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'your database name'
while ( $tables = $result->fetch_assoc())
{
echo $tables['TABLE_NAME']."<br>";
}
I was able to solve this problem by cleaning my build.
Top menu -> Product -> Clean Or keyboard shortcut: Shift+Cmd+K
Here is a properly described article and also a sample with code. JS coordinates
As per requirement. below is code which is posted at last in that article. Need to call getOffset function and pass html element which returns its top and left values.
function getOffsetSum(elem) {
var top=0, left=0
while(elem) {
top = top + parseInt(elem.offsetTop)
left = left + parseInt(elem.offsetLeft)
elem = elem.offsetParent
}
return {top: top, left: left}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect()
var body = document.body
var docElem = document.documentElement
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
var clientTop = docElem.clientTop || body.clientTop || 0
var clientLeft = docElem.clientLeft || body.clientLeft || 0
var top = box.top + scrollTop - clientTop
var left = box.left + scrollLeft - clientLeft
return { top: Math.round(top), left: Math.round(left) }
}
function getOffset(elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem)
} else {
return getOffsetSum(elem)
}
}
After having this problem on remote servers (production, test, qa, staging, etc), but not on local development workstations, I found that the Application Pool was configured with a RequestLimit other than 0.
This caused the app pool to give up and reply with the exception noted in the question.
Somewhere along the way my installshield project had its App pool definition changed to use "3" (probably just a mis-click or mis-type).
The simplest solution would be to open Visual Studio, deactivate the TFS Plugin in Tools > Options > Source control and reopen the solution you want to clean. Visual Studio will ask to remove source controls bindings
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
I have tried the following command on Ubuntu and its working for me
sudo apt-get install php7.0-mysql
Thanks
The function pthread_mutex_lock()
either acquires the mutex for the calling thread or blocks the thread until the mutex can be acquired. The related pthread_mutex_unlock()
releases the mutex.
Think of the mutex as a queue; every thread that attempts to acquire the mutex will be placed on the end of the queue. When a thread releases the mutex, the next thread in the queue comes off and is now running.
A critical section refers to a region of code where non-determinism is possible. Often this because multiple threads are attempting to access a shared variable. The critical section is not safe until some sort of synchronization is in place. A mutex lock is one form of synchronization.
I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:
http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes
It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.
Options +ExecCGI
addhandler x-httpd-php5-cgi .php
char c = 'a';
String a = Integer.toHexString(c); // gives you---> a = "61"
HTML
<a href="#top">Top</a>
<a href="#middle">Middle</a>
<a href="#bottom">Bottom</a>
<div id="top"><a href="top"></a>Top</div>
<div id="middle"><a href="middle"></a>Middle</div>
<div id="bottom"><a href="bottom"></a>Bottom</div>
CSS
#top,#middle,#bottom{
height: 600px;
width: 300px;
background: green;
}
Example http://jsfiddle.net/x4wDk/
I tried every method listed here and in Android adb devices unauthorized
What eventually worked for me was the option just below USB Debugging 'Revoke auths'
(Editor's Note: This answer was correct in May 2013 for Android Studio v0.1, but is no longer accurate as of July 2014, since the mentioned menu option does not exist anymore -- see this answer for up-to-date alternative).
First you will have to mark it as excluded. Then on right click you will be able to delete the project.
Is there a way in which I can update the plot just by adding more point[s] to it...
There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.
Each method basically sets the data
property of the object being drawn, so doesn't require clearing the screen or figure. The data
property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).
Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:
import matplotlib.pyplot as plt
import numpy
hl, = plt.plot([], [])
def update_line(hl, new_data):
hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
plt.draw()
Then when you receive data from the serial port just call update_line
.
As a follow-up to Adam Matan's answer, the /proc/<pid>
directory's time stamp as such is not necessarily directly useful, but you can use
awk -v RS=')' 'END{print $20}' /proc/12345/stat
to get the start time in clock ticks since system boot.1
This is a slightly tricky unit to use; see also convert jiffies to seconds for details.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat
This should give you seconds, which you can pass to strftime()
to get a (human-readable, or otherwise) timestamp.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat
Updated with some fixes from Stephane Chazelas in the comments; thanks as always!
If you only have Mawk, maybe try
awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
NR==1 { now=$1; next }
END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}
1 man proc; search for starttime.
Since JDK 1.7, the canonical way to have an application be notified of changes to a file is using the WatchService API. The WatchService is event-driven. The official tutorial provides an example:
/*
* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Oracle nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;
/**
* Example to watch a directory (or tree) for changes to files.
*/
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey,Path> keys;
private final boolean recursive;
private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>)event;
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException
{
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey,Path>();
this.recursive = recursive;
if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}
// enable trace after initial registration
this.trace = true;
}
/**
* Process all events for keys queued to the watcher
*/
void processEvents() {
for (;;) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event: key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
}
For individual files, various solutions exist, such as:
Note that Apache VFS uses a polling algorithm, although it may offer greater functionality. Also note that the API does not offer a way to determine whether a file has been closed.
%run YourNotebookfile.ipynb is working fine;
if you want to import a specific module then just add the import command after the ipynb i.e YourNotebookfile.ipynb having def Add()
then you can just use it
%run YourNotebookfile.ipynb import Add
Just run the following command:
ssh-add -K
It will never ask you to enter the password again.
This functions should help you...
bool isThereSpace(String s){
return s.Contains(" ");
}
Please find answer:
public class Customer {
public static void main(String[] args) {
Customer customer=new Customer();
customer.business();
}
public void business(){
System.out.println("Hi Harry");
}
}
in HQL you can use query parameter and set Collection with setParameterList method.
Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
q.setParameterList("names", names);
Here's a solution that uses more modern syntax and is less verbose than the ones already provided:
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.querySelector("video");
video.addEventListener('play', () => {
function step() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
requestAnimationFrame(step)
}
requestAnimationFrame(step);
})
Some useful links:
These days, socket.on('connect', ...) is not working for me. I use the below code to check at 1st connecting.
if (socket.connected)
console.log('socket.io is connected.')
and use this code when reconnected.
socket.on('reconnect', ()=>{
//Your Code Here
});
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
Just use for x in f: ...
, this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip
call because the trailing newline is already stipped.
The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline
will return an empty string, not None
. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue
makes the code ignore blank lines, which is propably a good thing anyway.
Here are a couple dplyr
options that keep non-duplicate rows based on columns id and id2:
library(dplyr)
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)
Try setting security to none in /etc/bluetooth/hcid.conf
http://linux.die.net/man/5/hcid.conf
This will probably only work for HCI devices (mouse, keyboard, spaceball, etc.). If you have a different kind of device, there's probably a different but similar setting to change.
One liner just set devMode true/false;
console.log = devMode ? console.log : () => { };
select v.SQL_TEXT,
v.PARSING_SCHEMA_NAME,
v.FIRST_LOAD_TIME,
v.DISK_READS,
v.ROWS_PROCESSED,
v.ELAPSED_TIME,
v.service
from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)
where
clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.
If you actually want your function to behave like the str()
built-in, but return an empty string when the argument is None, do this:
def xstr(s):
if s is None:
return ''
return str(s)
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer
RoboRealm vision software list mentions JHLabs and NeatVision among lots of other non-Java based libraries.
Change the return type of your GetResults to be List<Person>
.
Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically.
Using your definition for the Person class, this code works for me:
public List<Person> GetPlayers()
{
List<Person> players = new List<Person>();
players.Add(new Person { FirstName="Peyton", LastName="Manning", Age=35 } );
players.Add(new Person { FirstName="Drew", LastName="Brees", Age=31 } );
players.Add(new Person { FirstName="Brett", LastName="Favre", Age=58 } );
return players;
}
results:
[{"Age":35,"FirstName":"Peyton","LastName":"Manning"},
{"Age":31,"FirstName":"Drew","LastName":"Brees"},
{"Age":58,"FirstName":"Brett","LastName":"Favre"}]
(All on one line)
I also used this attribute on the method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "players")]
WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.
The UriTemplate sets the URL at which the method is available. So I can do a GET on
http://myserver/myvdir/JsonService.svc/players
and it just works.
Also check out IIRF or another URL rewriter to get rid of the .svc in the URI.
''Convert text to Number with ZERO Digits and Number convert ZERO Digits
Sub ZERO_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0"
Set rSelection = Nothing
End Sub
''Convert text to Number with TWO Digits and Number convert TWO Digits
Sub TWO_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0.00"
Set rSelection = Nothing
End Sub
''Convert text to Number with SIX Digits and Number convert SIX Digits
Sub SIX_DIGIT()
On Error Resume Next
Dim rSelection As Range
Set rSelection = rSelection
rSelection.Select
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
rSelection.Select
Selection.NumberFormat = "0.000000"
Set rSelection = Nothing
End Sub
This is the code I'm using. Also works for .NET Core
> 2.0 using System.Drawing.Common
NuGet.
https://www.nuget.org/packages/System.Drawing.Common/
using System;
using System.Drawing;
class Program
{
static void Main()
{
const string input = "C:\\background1.png";
const string output = "C:\\thumbnail.png";
// Load image.
Image image = Image.FromFile(input);
// Compute thumbnail size.
Size thumbnailSize = GetThumbnailSize(image);
// Get thumbnail.
Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
thumbnailSize.Height, null, IntPtr.Zero);
// Save thumbnail.
thumbnail.Save(output);
}
static Size GetThumbnailSize(Image original)
{
// Maximum size of any dimension.
const int maxPixels = 40;
// Width and height.
int originalWidth = original.Width;
int originalHeight = original.Height;
// Return original size if image is smaller than maxPixels
if (originalWidth <= maxPixels || originalHeight <= maxPixels)
{
return new Size(originalWidth, originalHeight);
}
// Compute best factor to scale entire image based on larger dimension.
double factor;
if (originalWidth > originalHeight)
{
factor = (double)maxPixels / originalWidth;
}
else
{
factor = (double)maxPixels / originalHeight;
}
// Return thumbnail size.
return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
}
}
Source:
use blow code for compute height + scroll
var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var height = dif + document.documentElement.scrollHeight +"px";
According to the Python 2 Glossary, iterables are
all sequence types (such as
list
,str
, andtuple
) and some non-sequence types likedict
andfile
and objects of any classes you define with an__iter__()
or__getitem__()
method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object.
Of course, given the general coding style for Python based on the fact that it's “Easier to ask for forgiveness than permission.”, the general expectation is to use
try:
for i in object_in_question:
do_something
except TypeError:
do_something_for_non_iterable
But if you need to check it explicitly, you can test for an iterable by hasattr(object_in_question, "__iter__") or hasattr(object_in_question, "__getitem__")
. You need to check for both, because str
s don't have an __iter__
method (at least not in Python 2, in Python 3 they do) and because generator
objects don't have a __getitem__
method.
Number of parameters is the amount of numbers that can be changed in the model. Mathematically this means number of dimensions of your optimization problem. For you as a programmer, each of this parameters is a floating point number, which typically takes 4 bytes of memory, allowing you to predict the size of this model once saved.
This formula for this number is different for each neural network layer type, but for Dense layer it is simple: each neuron has one bias parameter and one weight per input:
N = n_neurons * ( n_inputs + 1)
.
Mockito cannot capture static methods, but since Mockito 2.14.0 you can simulate it by creating invocation instances of static methods.
Example (extracted from their tests):
public class StaticMockingExperimentTest extends TestBase {
Foo mock = Mockito.mock(Foo.class);
MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();
Method staticMethod;
InvocationFactory.RealMethodBehavior realMethod = new InvocationFactory.RealMethodBehavior() {
@Override
public Object call() throws Throwable {
return null;
}
};
@Before
public void before() throws Throwable {
staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);
}
@Test
public void verify_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
handler.handle(invocation);
//verify staticMethod on mock
//Mockito cannot capture static methods so we will simulate this scenario in 3 steps:
//1. Call standard 'verify' method. Internally, it will add verificationMode to the thread local state.
// Effectively, we indicate to Mockito that right now we are about to verify a method call on this mock.
verify(mock);
//2. Create the invocation instance using the new public API
// Mockito cannot capture static methods but we can create an invocation instance of that static invocation
Invocation verification = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"some arg");
//3. Make Mockito handle the static method invocation
// Mockito will find verification mode in thread local state and will try verify the invocation
handler.handle(verification);
//verify zero times, method with different argument
verify(mock, times(0));
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
handler.handle(differentArg);
}
@Test
public void stubbing_static_method() throws Throwable {
//register staticMethod call on mock
Invocation invocation = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"foo");
handler.handle(invocation);
//register stubbing
when(null).thenReturn("hey");
//validate stubbed return value
assertEquals("hey", handler.handle(invocation));
assertEquals("hey", handler.handle(invocation));
//default null value is returned if invoked with different argument
Invocation differentArg = Mockito.framework().getInvocationFactory().createInvocation(mock, withSettings().build(Foo.class), staticMethod, realMethod,
"different arg");
assertEquals(null, handler.handle(differentArg));
}
static class Foo {
private final String arg;
public Foo(String arg) {
this.arg = arg;
}
public static String staticMethod(String arg) {
return "";
}
@Override
public String toString() {
return "foo:" + arg;
}
}
}
Their goal is not to directly support static mocking, but to improve its public APIs so that other libraries, like Powermockito, don't have to rely on internal APIs or directly have to duplicate some Mockito code. (source)
Disclaimer: Mockito team thinks that the road to hell is paved with static methods. However, Mockito's job is not to protect your code from static methods. If you don’t like your team doing static mocking, stop using Powermockito in your organization. Mockito needs to evolve as a toolkit with an opinionated vision on how Java tests should be written (e.g. don't mock statics!!!). However, Mockito is not dogmatic. We don't want to block unrecommended use cases like static mocking. It's just not our job.
Transient variables in Java are never serialized.
It shouldn't be your call to decide whether the link should open in a new tab or a new window, since ultimately this choice should be done by the settings of the user's browser. Some people like tabs; some like new windows.
Using _blank
will tell the browser to use a new tab/window, depending on the user's browser configuration and how they click on the link (e.g. middle click, Ctrl+click, or normal click).
This code will remove the indentation and list bullets.
ul {
padding: 0;
list-style-type: none;
}
My solution in Header parameters with example is user="test" is:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
System.out.println(headers.get("user"));
}
.html always for new files. .htm is a throwback to dos days.
Thanks for the replies, it works!
And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats
), and on UnicodeDecodeError
I try the next format:
from __future__ import with_statement
import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector
targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()
def get_encoding_type(current_file):
detector.reset()
for line in file(current_file):
detector.feed(line)
if detector.done: break
detector.close()
return detector.result['encoding']
def convertFileBestGuess(filename):
sourceFormats = ['ascii', 'iso-8859-1']
for format in sourceFormats:
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
def convertFileWithDetection(fileName):
print("Converting '" + fileName + "'...")
format=get_encoding_type(fileName)
try:
with codecs.open(fileName, 'rU', format) as sourceFile:
writeConversion(sourceFile)
print('Done.')
return
except UnicodeDecodeError:
pass
print("Error: failed to convert '" + fileName + "'.")
def writeConversion(file):
with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
for line in file:
targetFile.write(line)
# Off topic: get the file list and call convertFile on each file
# ...
(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)
by testing against a set of test patterns to make sure that is a valid syntax and does what you intend with a fully range of test URIs.
See regexpCheck.php below for a simple script that you can add to a private/test directory in your site to help you do this. I've kept this brief rather than pretty. Just past this into a file regexpCheck.php
in a test directory to use it on your website. This will help you build up any regexp and test it against a list of test cases as you do so. I am using the PHP PCRE engine here, but having had a look at the Apache source, this is basically identical to the one used in Apache. There are many HowTos and tutorials which provide templates and can help you build your regexp skills.
<html><head><title>Regexp checker</title></head><body>
<?php
$a_pattern= isset($_POST['pattern']) ? $_POST['pattern'] : "";
$a_ntests = isset($_POST['ntests']) ? $_POST['ntests'] : 1;
$a_test = isset($_POST['test']) ? $_POST['test'] : array();
$res = array(); $maxM=-1;
foreach($a_test as $t ){
$rtn = @preg_match('#'.$a_pattern.'#',$t,$m);
if($rtn == 1){
$maxM=max($maxM,count($m));
$res[]=array_merge( array('matched'), $m );
} else {
$res[]=array(($rtn === FALSE ? 'invalid' : 'non-matched'));
}
}
?> <p> </p>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'];?>">
<label for="pl">Regexp Pattern: </label>
<input id="p" name="pattern" size="50" value="<?php echo htmlentities($a_pattern,ENT_QUOTES,"UTF-8");;?>" />
<label for="n"> Number of test vectors: </label>
<input id="n" name="ntests" size="3" value="<?php echo $a_ntests;?>"/>
<input type="submit" name="go" value="OK"/><hr/><p> </p>
<table><thead><tr><td><b>Test Vector</b></td><td> <b>Result</b></td>
<?php
for ( $i=0; $i<$maxM; $i++ ) echo "<td> <b>\$$i</b></td>";
echo "</tr><tbody>\n";
for( $i=0; $i<$a_ntests; $i++ ){
echo '<tr><td> <input name="test[]" value="',
htmlentities($a_test[$i], ENT_QUOTES,"UTF-8"),'" /></td>';
foreach ($res[$i] as $v) { echo '<td> ',htmlentities($v, ENT_QUOTES,"UTF-8"),' </td>';}
echo "</tr>\n";
}
?> </table></form></body></html>
What about constructing the element using jQuery? e.g.
$("<div></div>")
creates a new div element, ready to be added to the page. Can be shortened further to
$("<div>")
then you can chain on commands that you need, set up event handlers and append it to the DOM. For example
$('<div id="myid">Div Content</div>')
.bind('click', function(e) { /* event handler here */ })
.appendTo('#myOtherDiv');
There is an underlying buffer/stream that getchar()
and friends read from. When you enter text, the text is stored in a buffer somewhere. getchar()
can stream through it one character at a time. Each read returns the next character until it reaches the end of the buffer. The reason it's not asking you for subsequent characters is that it can fetch the next one from the buffer.
If you run your script and type directly into it, it will continue to prompt you for input until you press CTRL+D (end of file). If you call it like ./program < myInput
where myInput
is a text file with some data, it will get the EOF
when it reaches the end of the input. EOF
isn't a character that exists in the stream, but a sentinel value to indicate when the end of the input has been reached.
As an extra warning, I believe getchar()
will also return EOF
if it encounters an error, so you'll want to check ferror()
. Example below (not tested, but you get the idea).
main() {
int c;
do {
c = getchar();
if (c == EOF && ferror()) {
perror("getchar");
}
else {
putchar(c);
}
}
while(c != EOF);
}
It does not make sense to put your business layer in the Model for an MVC project.
Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):
The h1:first-child
selector means
Select the first child of its parent
if and only if it's anh1
element.
The :first-child
of the container here is the ul
, and as such cannot satisfy h1:first-child
.
There is CSS3's :first-of-type
for your case:
.detail_container h1:first-of-type
{
color: blue;
}
But with browser compatibility woes and whatnot, you're better off giving the first h1
a class, then targeting that class:
.detail_container h1.first
{
color: blue;
}
If someone was looking for a way to remove all instances of repeated values, see "How can I efficiently extract repeated elements in a Ruby array?".
a = [1, 2, 2, 3]
counts = Hash.new(0)
a.each { |v| counts[v] += 1 }
p counts.select { |v, count| count == 1 }.keys # [1, 3]
This works:
myWindow = window.open('http://www.yahoo.com','myWindow', "width=200, height=200");
Never mind, I found the answer.
This will do the trick.
Dim colIndex As Long
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)
std::is_same()
is only available since C++11. For pre-C++11 you can use typeid()
:
template <typename T>
void foo()
{
if (typeid(T) == typeid(animal)) { /* ... */ }
}
This link is help in defining, * How to read password from use without echo-ing it back to terminal * How to replace each character with * -character.
https://www.tutorialkart.com/bash-shell-scripting/bash-read-username-and-password/
Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see PEP 8, the Python style guide.
I think a good approach to this problem would be to take advantage of Bootstrap's close.bs.alert
event type to hide the alert instead of removing it. The reason why Bootstrap exposes this event type is so that you can overwrite the default behavior of removing the alert from the DOM.
$('.alert').on('close.bs.alert', function (e) {
e.preventDefault();
$(this).addClass('hidden');
});
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
There are several techniques using of runOnUiThread(), lets see all
This is my main thread (UI thread) called AndroidBasicThreadActivity and I'm going to update it from a worker thread in various ways -
public class AndroidBasicThreadActivity extends AppCompatActivity
{
public static TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_basic_thread);
textView = (TextView) findViewById(R.id.textview);
MyAndroidThread myTask = new MyAndroidThread(AndroidBasicThreadActivity.this);
Thread t1 = new Thread(myTask, "Bajrang");
t1.start();
}
}
1.) By passing Activity's instance as an argument on worker thread
class MyAndroidThread implements Runnable
{
Activity activity;
public MyAndroidThread(Activity activity)
{
this.activity = activity;
}
@Override
public void run()
{
//perform heavy task here and finally update the UI with result this way -
activity.runOnUiThread(new Runnable()
{
@Override
public void run()
{
AndroidBasicThreadActivity.textView.setText("Hello!! Android Team :-) From child thread.");
}
});
}
}
2.) By using View's post(Runnable runnable) method in worker thread
class MyAndroidThread implements Runnable
{
Activity activity;
public MyAndroidThread(Activity activity)
{
this.activity = activity;
}
@Override
public void run()
{
//perform heavy task here and finally update the UI with result this way -
AndroidBasicThreadActivity.textView.post(new Runnable()
{
@Override
public void run()
{
AndroidBasicThreadActivity.textView.setText("Hello!! Android Team :-) From child thread.");
}
});
}
}
3.) By using Handler class from android.os package If we don't have the context (this/ getApplicationContext()) or Activity's instance (AndroidBasicThreadActivity.this) then we have to use Handler class as below -
class MyAndroidThread implements Runnable
{
Activity activity;
public MyAndroidThread(Activity activity)
{
this.activity = activity;
}
@Override
public void run()
{
//perform heavy task here and finally update the UI with result this way -
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
AndroidBasicThreadActivity.textView.setText("Hello!! Android Team :-) From child thread.");
}
});
}
}
A note on relative paths to complement the other answers.
When doing infrastructure as code I'm usually using roles and tasks that accept relative paths, specially for files defined in those roles.
Special variables like playbook_dir and role_path are very useful to create the absolute paths needed to test for existence.
In addition to the other answers, which I subscribe, you may consider using the /I
switch of the IF
command.
... the /I switch, if specified, says to do case insensitive string compares.
it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.
IF /I "%1"=="-b" GOTO SPECIFIC
The documentation says:
class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.
Example:
Remove the class 'blue' and 'under' from the matched elements.
$("p:odd").removeClass("blue under");
In for xml path
, if we define any value like [ for xml path('ENVLOPE') ]
then these tags will be added with each row:
<ENVLOPE>
</ENVLOPE>
log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.
Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.
Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
<Properties>
<Property name="filename">log/CelsiusConverter.log</Property>
</Properties>
<Appenders>
<Appender type="Console" name="Console">
<Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
</Appender>
<Appender type="Console" name="FLOW">
<Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
</Appender>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
</Appender>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="File" />
<AppenderRef ref="Console" />
<!-- Use FLOW to trace down exact method sending the msg -->
<!-- <AppenderRef ref="FLOW" /> -->
</Root>
</Loggers>
</Configuration>
Use <text>
:
<script type="text/javascript">
var data = [];
@foreach (var r in Model.rows)
{
<text>
data.push([ @r.UnixTime * 1000, @r.Value ]);
</text>
}
</script>
Yes, you need to close Connection
. Otherwise, the database client will typically keep the socket connection and other resources open.
When you print a string in console(Eclipse),\n,\r and \r\n have the same effect,all of them will give you a new line;but \n\r(also \n\n,\r\r) will give you two new lines;when you write a string to a file,only \r\n can give you a new line.
Here is a simple function to convert csv to html table using php:
function jj_readcsv($filename, $header=false) {
$handle = fopen($filename, "r");
echo '<table>';
//display header row if true
if ($header) {
$csvcontents = fgetcsv($handle);
echo '<tr>';
foreach ($csvcontents as $headercolumn) {
echo "<th>$headercolumn</th>";
}
echo '</tr>';
}
// displaying contents
while ($csvcontents = fgetcsv($handle)) {
echo '<tr>';
foreach ($csvcontents as $column) {
echo "<td>$column</td>";
}
echo '</tr>';
}
echo '</table>';
fclose($handle);
}
One can call this function like jj_readcsv('image_links.csv',true);
if second parameter is true then the first row of csv will be taken as header/title.
Hope this helps somebody. Please comment for any flaws in this code.
what worked for me is converting the props.data to an array using
data = Array.from(props.data);
then I could use the data.map()
function
select cast (as time(0))
would be a good clause. For example:
(select cast(start_date as time(0))) AS 'START TIME'
at least pip3 also works without "=", however, instead of "http" you might need "https"
Final command, which worked for me:
sudo pip3 install --proxy https://{proxy}:{port} {BINARY}
Note that utcfromtimestamp
is confusing and can lead to unexpected results due to the resulting naive datetime object. Better be explicit and set tz
argument in fromtimestamp
:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
print(dtobj.isoformat())
print(repr(dtobj))
# 2010-09-10T06:51:25+00:00
# datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Not specifying the time zone (tz) will lead to naive datetime, which Python treats as local time - while UNIX time refers to UTC.
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
It is not certain that any global ECMAScript variables have been exported and html/css does not necessarily indicate React. So look in the .js.
Method 1: Look in ECMAScript:
The version number is exported by both modules react-dom and react but those names are often removed by bundling and the version hidden inside an execution context that cannot be accessed. A clever break point may reveal the value directly, or you can search the ECMAScript:
Method 2: Use a DOM breakpoint:
Inspect Element
Elements
paneBreak On… - subtree modifications
Sources
paneCall Stack
sub-panerender
entry, this is ReactDOM.render
render
, ie. the code that invokes renderreact-dom
module exports object
version: "15.6.2"
, ie. all values exported by react-dom
The version is also injected into React dev tools, but as far as I know not displayed anywhere.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
TL;DR
git reset
resets Staging to the last commit. Use--hard
to also reset files in your Working directory to the last commit.
LONGER VERSION
But that's obviously simplistic hence the many rather verbose answers. It made more sense for me to read up on git reset
in the context of undoing changes. E.g. see this:
If git revert is a “safe” way to undo changes, you can think of git reset as the dangerous method. When you undo with git reset(and the commits are no longer referenced by any ref or the reflog), there is no way to retrieve the original copy—it is a permanent undo. Care must be taken when using this tool, as it’s one of the only Git commands that has the potential to lose your work.
From https://www.atlassian.com/git/tutorials/undoing-changes/git-reset
and this
On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
From https://www.atlassian.com/git/tutorials/resetting-checking-out-and-reverting/commit-level-operations
Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser
RSA Public Key
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
Encrypted Private Key
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----
CRL
-----BEGIN X509 CRL-----
-----END X509 CRL-----
CRT
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
CSR
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
NEW CSR
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
PEM
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
PKCS7
-----BEGIN PKCS7-----
-----END PKCS7-----
PRIVATE KEY
-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----
DSA KEY
-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----
Elliptic Curve
-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----
PGP Private Key
-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----
PGP Public Key
-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----
If your url in PHP like http://yourdomain.com/demo.php than comes like http://yourdomain.com/demo
This is all you need:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^([^\.]+)$ $1.html [NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]
From info gcc
(emphasis mine):
-ansi
In C mode, this is equivalent to
-std=c90
. In C++ mode, it is equivalent to-std=c++98
. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code), or of standard C++ (when compiling C++ code), such as theasm
andtypeof
keywords, and predefined macros such as 'unix' and 'vax' that identify the type of system you are using. It also enables the undesirable and rarely used ISO trigraph feature. For the C compiler, it disables recognition of C++ style//
comments as well as theinline
keyword.
(It uses vax in the example instead of linux because when it was written maybe it was more popular ;-).
The basic idea is that GCC only tries to fully comply with the ISO standards when it is invoked with the -ansi
option.
Incase you're using angular and an iframe inside, you'll need need to listen to the iframe to finish loading. You can do something like this:
document.getElementsByTagName("iframe")[0].addEventListener('load', () => {
document.getElementsByTagName("iframe")[0].contentWindow.postMessage(
{
call: 'sendValue',
value: 'data'
},
window.location.origin)
})
You will have to get the iframe one way or another (there are better ways to do it in angular) and then wait for it to load. Or else the listener won't be attached to it even if you do it inside lifecycle methods like ngAfterViewInit()
I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:
https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About
The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017
Temporarily show Menu Bar on ATOM:
Press ALT
Key to make the Menu bar appear but it is not permanent.
Always display the Menu Bar on ATOM:
To make the change permanent, press ALT + V
and then select Toggle Menu Bar
option from the "View" drop-down down.
[Tested on ATOM running on Ubuntu 16.04]
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
Use compareTo()
function that's built into the class.
build
and listener
objects are presenting during system groovy execution. You can do this:
def myVar = build.getEnvironment(listener).get('myVar')
keep the delimiter in single quotes it will work.
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
This will work
Lazy Loading? Well, it simply means that child records are not fetched immediately, but automatically as soon as you try to access them.
How are you compiling your app? What compiler flags?
In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.
My json file was formatted exactly as the one in the question but none of the solutions here worked out. Finally I found a workaround on another Stackoverflow thread. Since this post is the first link in Google search, I put the that answer here so that other people come to this post in the future will find it more easily.
As it's been said there the valid json file needs "[" in the beginning and "]" in the end of file. Moreover, after each json item instead of "}" there must be a "},". All brackets without quotations! This piece of code just modifies the malformed json file into its correct format.
You should use the optional argument indent
.
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
twitterDataFile = open("twitterData.json", "w")
# magic happens here to make it pretty-printed
twitterDataFile.write(simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True))
twitterDataFile.close()
Try this one:
Color color = new Color (10,10,10)
myPaint.setColor(color.getRGB());
Since C++11, you may want to use either snake_case
or camelCase
for function names.
This is because to make a class work as the range-expression in a range-based for-loop, you have to define functions called begin
and end
(case-sensitive) for that class.
Consequently, using e.g. PascalCase
for function names means you have to break the naming consistency in your project if you ever need to make a class work with the range-based for.
Rather than manually looping, prefer using the appropriate C++ algorithm, in this case std::generate_n
, with a proper random number generator:
auto generate_random_alphanumeric_string(std::size_t len) -> std::string {
static constexpr auto chars =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
thread_local auto rng = random_generator<>();
auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1};
auto result = std::string(len, '\0');
std::generate_n(begin(result), len, [&]() { return chars[dist(rng)]; });
return result;
}
This is close to something I would call the “canonical” solution for this problem.
Unfortunately, correctly seeding a generic C++ random number generator (e.g. MT19937) is really hard. The above code therefore uses a helper function template, random_generator
:
template <typename T = std::mt19937>
auto random_generator() -> T {
auto constexpr seed_bytes = sizeof(typename T::result_type) * T::state_size;
auto constexpr seed_len = seed_bytes / sizeof(std::seed_seq::result_type);
auto seed = std::array<std::seed_seq::result_type, seed_len>();
auto dev = std::random_device();
std::generate_n(begin(seed), seed_len, std::ref(dev));
auto seed_seq = std::seed_seq(begin(seed), end(seed));
return T{seed_seq};
}
This is complex and relatively inefficient. Luckily it’s used to initialise a thread_local
variable and is therefore only invoked once per thread.
Finally, the necessary includes for the above are:
#include <algorithm>
#include <array>
#include <cstring>
#include <functional>
#include <random>
#include <string>
The above code uses class template argument deduction and thus requires C++17. It can be trivially adapted for earlier versions by adding the required template arguments.
I believe labels are inline, and so they don't take a width. Maybe try using "display: block" and going from there.
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('id', 'id'))
->setMaxResults(1)
->orderBy(array("id" => $criteria::DESC));
$results = $articlesRepo->matching($criteria);
Assuming you got it from https://curl.haxx.se/download.html, just unzip it wherever you want. No need to install. If you are going to use SSL, you need to download the OpenSSL DLLs, available from curl's website.
These links explain it with examples
http://dotnetperls.com/openfiledialog
http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
You can try Java Webcam SDK library also. SDK demo applet is available at link.
You also can use itemgetter operator:
from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)
From the Java Language Specification:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
- For type byte, the default value is zero, that is, the value of
(byte)0
.- For type short, the default value is zero, that is, the value of
(short)0
.- For type int, the default value is zero, that is,
0
.- For type long, the default value is zero, that is,
0L
.- For type float, the default value is positive zero, that is,
0.0f
.- For type double, the default value is positive zero, that is,
0.0d
.- For type char, the default value is the null character, that is,
'\u0000'
.- For type boolean, the default value is
false
.- For all reference types (§4.3), the default value is
null
.
The NavigationBar height varies for some devices, but as well for some orientations. First you have to check if the device has a navbar, then if the device is a tablet or a not-tablet (phone) and finally you have to look at the orientation of the device in order to get the correct height.
public int getNavBarHeight(Context c) {
int result = 0;
boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if(!hasMenuKey && !hasBackKey) {
//The device has a navigation bar
Resources resources = c.getResources();
int orientation = resources.getConfiguration().orientation;
int resourceId;
if (isTablet(c)){
resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
} else {
resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");
}
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
}
return result;
}
private boolean isTablet(Context c) {
return (c.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);
Use jquery change event
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
An example
$("input[type='text']").change( function() {
// your code
});
The advantage that .change
has over .keypress
, .focus
, .blur
is that .change
event will fire only when input has changed
This works:
sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"
Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)
Just keep in mind that:
obj= "foo"
is correct; obj="foo"
is not.Maybe too late, but I'd cast 0/1 as bit to make the datatype eventually becomes True/False when consumed by .NET framework:
SELECT EntityId,
EntityName,
CASE
WHEN EntityProfileIs IS NULL
THEN CAST(0 as bit)
ELSE CAST(1 as bit) END AS HasProfile
FROM Entities
LEFT JOIN EntityProfiles ON EntityProfiles.EntityId = Entities.EntityId`
If you want the lookup to be case insensitive you can loop through the values making it a little more friendly:
public enum MyEnum {
A, B, C, D;
public static MyEnum lookup(String id) {
boolean found = false;
for(MyEnum enum: values()){
if(enum.toString().equalsIgnoreCase(id)) found = true;
}
if(!found) throw new RuntimeException("Invalid value for my enum: " +id);
}
}
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
Also make sure the div is currently appended to the DOM and visible.
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
Here is what i have done to find the version:
just write SELECT @@version
and it will give you the version.
This is possible if the browser supports the download
property in anchor elements.
var sampleBytes = new Int8Array(4096);
var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());
saveByteArray([sampleBytes], 'example.txt');
JSFiddle: http://jsfiddle.net/VB59f/2
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
I usually use information_Schema.columns
and information_schema.tables
, although like @yuck said, sys.tables
and sys.columns
are shorter to type.
In a loop, concatenate these
@sql = @sql + 'select' + column_name +
' from ' + table_name +
' where ' + column_name ' like ''%''+value+''%' UNION
Then execute the resulting sql.
Adding this just for the sake of completeness of this question (some questions may get closed as duplicate of this one).
I usually use user mode for pip ie. pip install --user
even if instructions assume root mode. That way, my tensorboard installation was in ~/.local/bin/tensorboard
, and it was not in my path (which shouldn't be ideal either). So I was not able to access it.
In this case, running
sudo ln -s ~/.local/bin/tensorboard /usr/bin
should fix it.
Depending on what you want to do you could do this:
template<typename Base, typename T>
inline bool instanceof(const T*) {
return std::is_base_of<Base, T>::value;
}
Use:
if (instanceof<BaseClass>(ptr)) { ... }
However, this purely operates on the types as known by the compiler.
Edit:
This code should work for polymorphic pointers:
template<typename Base, typename T>
inline bool instanceof(const T *ptr) {
return dynamic_cast<const Base*>(ptr) != nullptr;
}
Example: http://cpp.sh/6qir
List comprehensions are exactly made for that:
smaller_list = [x for x in range(100001) if x % 10 == 0]
You can get more info about them in the python official documentation: http://docs.python.org/tutorial/datastructures.html#list-comprehensions
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName()
or classInstanceName.methodName()
, i.e. static methods and variables can be accessed using class name as well as instances of the class.
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
In [14]: b = np.reshape(a, (np.product(a.shape),))
In [15]: b
Out[15]: array([1, 2, 3, 4, 5, 6])
or, simply:
In [16]: a.flatten()
Out[16]: array([1, 2, 3, 4, 5, 6])
Simplest of them all is to use the "Flash Fill" option under the "Data" tab.
Keep the original input column on the left (say column A) and just add a blank column on the right of it (say column B, this new column will be treated as output).
Just fill in a couple of cells of Column B with actual expected output. In this case:
[email protected],
[email protected],
Then select the column range where you want the output along with the first couple of cells you filled manually ... then do the magic...click on "Flash Fill".
It basically understands the output pattern corresponding to the input and fills the empty cells.
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
Swift 5 and above:
let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
let savedInteger = defaults.integer(forKey: "Age")
defaults.set(true, forKey: "UseFaceID")
let savedBoolean = defaults.bool(forKey: "UseFaceID")
defaults.set(CGFloat.pi, forKey: "Pi")
defaults.set("Your Name", forKey: "Name")
defaults.set(Date(), forKey: "LastRun")
let array = ["Hello", "World"]
defaults.set(array, forKey: "SavedArray")
let savedArray = defaults.object(forKey: "SavedArray") as? [String] ?? [String()
let dict = ["Name": "Your", "Country": "YourCountry"]
defaults.set(dict, forKey: "SavedDict")
let savedDictionary = defaults.object(forKey: "SavedDictionary") as? [String: String] ?? [String: String]()
:)
You may follow the script which is developed using PHP.
Where you can download any google fonts by using the script.
It will download the fonts and create a CSS file and archive to zip.
You can download the source code from the GitHub https://github.com/sourav101/google-fonts-downloader
$obj = new GoogleFontsDownloader;
if(isset($_GET['url']) && !empty($_GET['url']))
{
$obj->generate($_GET['url']);
}
if(isset($_GET['download']) && !empty($_GET['download']) && $_GET['download']=='true')
{
$obj->download();
}
/**
* GoogleFontsDownloader
* Easy way to download any google fonts.
* @author Shohrab Hossain
* @version 1.0.0
*/
class GoogleFontsDownloader
{
private $url = '';
private $dir = 'dist/';
private $fontsDir = 'fonts/';
private $cssDir = 'css/';
private $fileName = 'fonts.css';
private $content = '';
private $errors = '';
private $success = '';
public $is_downloadable = false;
public function __construct()
{
ini_set('allow_url_fopen', 'on');
ini_set('allow_url_include', 'on');
}
public function generate($url = null)
{
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE)
{
$this->errors .= "<li><strong>Invalid url!</strong> $url</li>";
}
else
{
$this->url = $url;
// delete previous files
$this->_destroy();
// write font.css
$this->_css();
// write fonts
$this->_fonts();
// archive files
$this->_archive();
}
// show all messages
$this->_message();
}
public function download()
{
// Download the created zip file
$zipFileName = trim($this->dir, '/').'.zip';
if (file_exists($zipFileName))
{
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename = $zipFileName");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$zipFileName");
// delete file
unlink($zipFileName);
array_map('unlink', glob("$this->dir/*.*"));
rmdir($this->dir);
}
}
private function _archive()
{
if (is_dir($this->dir))
{
$zipFileName = trim($this->dir, '/').'.zip';
$zip = new \ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE)
{
$zip->addGlob($this->dir. "*.*");
$zip->addGlob($this->dir. "*/*.*");
if ($zip->status == ZIPARCHIVE::ER_OK)
{
$this->success .= '<li>Zip create successful!</li>';
$this->is_downloadable = true;
}
else
{
$this->errors .= '<li>Failed to create to zip</li>';
}
}
else
{
$this->errors .= '<li>ZipArchive not found!</li>';
}
$zip->close();
}
else
{
$this->errors .= "<li><strong>File</strong> not exists!</li>";
}
}
private function _css()
{
$filePath = $this->dir.$this->cssDir.$this->fileName;
$content = $this->_request($this->url);
if (!empty($content))
{
if (file_put_contents($filePath, $content))
{
$this->success .= "<li>$this->fileName generated successful!</li>";
$this->content = $content;
}
else
{
$this->errors .= '<li>Permission errro in $this->fileName! Unable to write $filePath.</li>';
}
}
else
{
$this->errors .= '<li>Unable to create fonts.css file!</li>';
}
}
private function _fonts()
{
if (!empty($this->content))
{
preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $this->content, $match);
$gFontPaths = $match[0];
if (!empty($gFontPaths) && is_array($gFontPaths) && sizeof($gFontPaths)>0)
{
$count = 0;
foreach ($gFontPaths as $url)
{
$name = basename($url);
$filePath = $this->dir.$this->fontsDir.$name;
$this->content = str_replace($url, '../'.$this->fontsDir.$name, $this->content);
$fontContent = $this->_request($url);
if (!empty($fontContent))
{
file_put_contents($filePath, $fontContent);
$count++;
$this->success .= "<li>The font $name downloaded!</li>";
}
else
{
$this->errors .= "<li>Unable to download the font $name!</li>";
}
}
file_put_contents($this->dir.$this->cssDir.$this->fileName, $this->content);
$this->success .= "<li>Total $count font(s) downloaded!</li>";
}
}
}
private function _request($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HEADER => FALSE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_URL => $url,
CURLOPT_REFERER => $url,
CURLOPT_RETURNTRANSFER => TRUE,
));
$result = curl_exec($ch);
curl_close($ch);
if (!empty($result))
{
return $result;
}
return false;
}
private function _destroy()
{
$cssPath = $this->dir.$this->cssDir.$this->fileName;
if (file_exists($cssPath) && is_file($cssPath))
{
unlink($cssPath);
}
else
{
mkdir($this->dir.$this->cssDir, 0777, true);
}
$fontsPath = $this->dir.$this->fontsDir;
if (!is_dir($fontsPath))
{
mkdir($fontsPath, 0777, true);
}
else
{
array_map(function($font) use($fontsPath) {
if (file_exists($fontsPath.$font) && is_file($fontsPath.$font))
{
unlink($fontsPath.$font);
}
}, glob($fontsPath.'*.*'));
}
}
private function _message()
{
if (strlen($this->errors)>0)
{
echo "<div class='alert alert-danger'><ul>$this->errors</ul></div>";
}
if (strlen($this->success)>0)
{
echo "<div class='alert alert-success'><ul>$this->success</ul></div>";
}
}
}
window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it
$("<a href='your url'></a>").click();
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
Floating will result in wrapping if space is not available.
You can use display:inline
and white-space:nowrap
to achieve this. Fiddle
<div id="container" style="white-space:nowrap">
<div id="image" style="display:inline;">
<img src="tree.png"/>
</div>
<div id="texts" style="display:inline; white-space:nowrap;">
A very long text(about 300 words)
</div>
</div>?
If an existing (non-bare) checkout begins giving this error, check your .git/config file; if core.bare
is true, remove that config line
Try to consolidate the syntax in a single line. this will clear the error
for Remote Debugging on Android with Chrome: try this https://developer.chrome.com/devtools/docs/remote-debugging
You can place .; in classpath in environmental variables to overcome this problem.
For AWS importing an existing public key,
Export from the .pem doing this... (on linux)
openssl rsa -in ./AWSGeneratedKey.pem -pubout -out PublicKey.pub
This will produce a file which if you open in a text editor looking something like this...
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/8y3uYCQxSXZ58OYceG
A4uPdGHZXDYOQR11xcHTrH13jJEzdkYZG8irtyG+m3Jb6f9F8WkmTZxl+4YtkJdN
9WyrKhxq4Vbt42BthadX3Ty/pKkJ81Qn8KjxWoL+SMaCGFzRlfWsFju9Q5C7+aTj
eEKyFujH5bUTGX87nULRfg67tmtxBlT8WWWtFe2O/wedBTGGQxXMpwh4ObjLl3Qh
bfwxlBbh2N4471TyrErv04lbNecGaQqYxGrY8Ot3l2V2fXCzghAQg26Hc4dR2wyA
PPgWq78db+gU3QsePeo2Ki5sonkcyQQQlCkL35Asbv8khvk90gist4kijPnVBCuv
cwIDAQAB
-----END PUBLIC KEY-----
However AWS will NOT accept this file.
You have to strip off the -----BEGIN PUBLIC KEY-----
and -----END PUBLIC KEY-----
from the file. Save it and import and it should work in AWS.
I was having the same problem while developing my own website. While it was resident locally, resources opened as file//
. For pages from the internet, including my own loaded as http://
, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.
After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".
That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.
So if you are referring to using F12 for locally hosted files, this may help.
Here I have a CSS-selector based on bobince's answer to select any focusable HTML element:
a[href]:not([tabindex='-1']),
area[href]:not([tabindex='-1']),
input:not([disabled]):not([tabindex='-1']),
select:not([disabled]):not([tabindex='-1']),
textarea:not([disabled]):not([tabindex='-1']),
button:not([disabled]):not([tabindex='-1']),
iframe:not([tabindex='-1']),
[tabindex]:not([tabindex='-1']),
[contentEditable=true]:not([tabindex='-1'])
{
/* your CSS for focusable elements goes here */
}
or a little more beautiful in SASS:
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
&:not([tabindex='-1'])
{
/* your SCSS for focusable elements goes here */
}
}
I've added it as an answer, because that was, what I was looking for, when Google redirected me to this Stackoverflow question.
EDIT: There is one more selector, which is focusable:
[contentEditable=true]
However, this is used very rarely.
I think structuring the project by functionalities is a practical method. It makes the project scalable and maintainable easily. And it makes each part of the project working in a total autonomy. Let me know what you think about this structure below: ANGULAR TYPESCRIPT PROJECT STRUCTURE – ANGULAR 2
source : http://www.angulartypescript.com/angular-typescript-project-structure/
Works with Express 4.x :
The Correct way to include partials in the template according to this you should use:
<%- include('partials/youFileName.ejs') %>
.
You are using:
<% include partials/yourFileName.ejs %>
which is deprecated.
It depends on which Ruby version you use:
Ruby 2.4 and higher:
It just works, as since Ruby v2.4.0 supports Unicode case mapping:
"?????".capitalize #=> ?????
Ruby 2.3 and lower:
"maria".capitalize #=> "Maria"
"?????".capitalize #=> ?????
The problem is, it just doesn't do what you want it to, it outputs ?????
instead of ?????
.
If you're using Rails there's an easy workaround:
"?????".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte
Otherwise, you'll have to install the unicode gem and use it like this:
require 'unicode'
Unicode::capitalize("?????") #=> ?????
Ruby 1.8:
Be sure to use the coding magic comment:
#!/usr/bin/env ruby
puts "?????".capitalize
gives invalid multibyte char (US-ASCII)
, while:
#!/usr/bin/env ruby
#coding: utf-8
puts "?????".capitalize
works without errors, but also see the "Ruby 2.3 and lower" section for real capitalization.
Npm now provides unlimited private hosted modules for $7/user/month used like so
cd private-project
npm login
in your package json set "name": " @username/private-project"
npm publish
then to require your project:
cd ../new-project
npm install --save @username/private-project
you can use this simple way
<select onchange="location = this.value;">
<option value="/finished">Finished</option>
<option value="/break">Break</option>
<option value="/issue">Issues</option>
<option value="/downtime">Downtime</option>
</select>
will redirect to route url you can direct to .html page or direct to some link just change value
in option.
You can create an AppleScript file to open Eclipse with a given workspace. You can even save the AppleScript file as an Application, which is equivalent to creating an alias with arguments in Windows OS.
Open Script Editor and type the following:
do shell script "open '/path/to/your/Eclipse/installation' -n --args -data /path/to/your/workspace"
For instance:
do shell script "open '/Applications/Eclipse.app' -n --args -data /MyWorkspaces/Personal"
Press the Run button to check it's working.
This script can be saved as such, but I prefer to save it as an Application. That way I can customize the icon by copying the *.icns icon from the original Eclipse.app bundle to the script application bundle.
To open an App folder, use the "see contents" contextual menu option. It should look like this:
Where "main.scpt" is the AppleScript file and "applet.icns" is the icon from the original Eclipse bundle.
Alternate solution of the values check
//Duplicate Title Entry
$.each(ar , function (i, val) {
if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
});
This happened to me yesterday and in my case was because I was following a PDF manual to develop some module to communicate with an API and while copying the link directly from the manual, for some odd reason, the hyphen
from the copied link was in a different encoding and hence the curl_exec()
was always returning false
because it was unable to communicate with the server.
It took me a couple hours to finally understand the diference in the characters bellow:
https://www.e-example.com/api
https://www.e-example.com/api
Every time I tried to access the link directly from a browser it converted to something likehttps://www.xn--eexample-0m3d.com/api
.
It may seem to you that they are equal but if you check the encoding of the hyphens
here you'll see that the first hyphen
is a unicode characters U+2010 and the other is a U+002D.
Hope this helps someone.
which may be useful
Update
A INNER JOIN B ON A.COL1=B.COL3
SET
A.COL2='CHANGED', A.COL4=B.COL4,......
WHERE ....;
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
You can use "find" for remove all files in the /objects
directory with 0 in size with the command:
find .git/objects/ -size 0 -delete
Backup is recommended.
I know this is an old thread but I thought this might help someone:
Mobile devices have greater height than width, in contrary, computers have greater width than height. For example:
@media all and (max-width: 320px) and (min-height: 320px)
so that would have to be done for every width i guess.
<audio id="audio" style="display:none;" src="mp3/Fans-Mi-tooXclusive_com.mp3" controls autoplay loop onloadeddata="setHalfVolume()">
This auto-plays, hides the music and reduces the music even if system volume is high to avoid noise. Place this in script:
<script>
function setHalfVolume() {
var myAudio = document.getElementById("audio");
myAudio.volume = 0.2;
}
</script>
In summary: React.js for Web Development while React-Native for Mobile App Development
I would like to quote an answer given by Microsoft support engineer at here:-
Hi Henny, MSVCR110.dll is the Microsoft Visual C++ Redistributable dll that is needed for projects built with Visual Studio 2011. The dll letters spell this out. MS = Microsoft, V = Visual, C = C++, R = Redistributable For Winroy to get started, this file is probably needed. This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. The redistributable can easily be downloaded on the Microsoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Refer the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679# Please let us know if the issue persists. We will be happy to assist you further. Thanks, Yaqub Khan - Microsoft Support Engineer
Just use the below piece of code to get the response from restful web service url, I use social mention url.
$response = get_web_page("http://socialmention.com/search?q=iphone+apps&f=json&t=microblogs&lang=fr");
$resArr = array();
$resArr = json_decode($response);
echo "<pre>"; print_r($resArr); echo "</pre>";
function get_web_page($url) {
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // name of client
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
action=""
will resolve to the page's address. action="#"
will resolve to the page's address + #
, which will mean an empty fragment identifier.
Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.
Usually, authors just put #
in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action=""
(or omit it if validation allows).
Python itself can help you with this, in interactive mode:
>>> help(file.read)
Help on method_descriptor:
read(...)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.
First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}>
in the render function, and have to think around the problem.
Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body
, so even if it did work, your event handler would never trigger.
Instead, inside componentDidMount
somewhere in your application, you can listen to nv-enter by adding
document.body.addEventListener('nv-enter', function (event) {
// logic
});
Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.
The following code works for me:
var data = [{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]_x000D_
_x000D_
var data_filter = data.filter( element => element.website =="yahoo")_x000D_
console.log(data_filter)
_x000D_
for counting:
$('.yourClass').length;
should work fine.
storing in a variable is as easy as:
var count = $('.yourClass').length;
from urllib2 import Request, urlopen, HTTPError, URLError
user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
page_open = urlopen(req)
except HTTPError, e:
print e.code
except URLError, e:
print e.reason
else:
print 'ok'
To answer the comment of unutbu:
Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source
Two examples with expat and libxml2. The second one is, IMHO, much easier to use since it creates a tree in memory, a data structure which is easy to work with. expat, on the other hand, does not build anything (you have to do it yourself), it just allows you to call handlers at specific events during the parsing. But expat may be faster (I didn't measure).
With expat, reading a XML file and displaying the elements indented:
/*
A simple test program to parse XML documents with expat
<http://expat.sourceforge.net/>. It just displays the element
names.
On Debian, compile with:
gcc -Wall -o expat-test -lexpat expat-test.c
Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html>
*/
#include <expat.h>
#include <stdio.h>
#include <string.h>
/* Keep track of the current level in the XML tree */
int Depth;
#define MAXCHARS 1000000
void
start(void *data, const char *el, const char **attr)
{
int i;
for (i = 0; i < Depth; i++)
printf(" ");
printf("%s", el);
for (i = 0; attr[i]; i += 2) {
printf(" %s='%s'", attr[i], attr[i + 1]);
}
printf("\n");
Depth++;
} /* End of start handler */
void
end(void *data, const char *el)
{
Depth--;
} /* End of end handler */
int
main(int argc, char **argv)
{
char *filename;
FILE *f;
size_t size;
char *xmltext;
XML_Parser parser;
if (argc != 2) {
fprintf(stderr, "Usage: %s filename\n", argv[0]);
return (1);
}
filename = argv[1];
parser = XML_ParserCreate(NULL);
if (parser == NULL) {
fprintf(stderr, "Parser not created\n");
return (1);
}
/* Tell expat to use functions start() and end() each times it encounters
* the start or end of an element. */
XML_SetElementHandler(parser, start, end);
f = fopen(filename, "r");
xmltext = malloc(MAXCHARS);
/* Slurp the XML file in the buffer xmltext */
size = fread(xmltext, sizeof(char), MAXCHARS, f);
if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
XML_STATUS_ERROR) {
fprintf(stderr,
"Cannot parse %s, file may be too large or not well-formed XML\n",
filename);
return (1);
}
fclose(f);
XML_ParserFree(parser);
fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
filename);
return (0);
}
With libxml2, a program which displays the name of the root element and the names of its children:
/*
Simple test with libxml2 <http://xmlsoft.org>. It displays the name
of the root element and the names of all its children (not
descendents, just children).
On Debian, compiles with:
gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
read-xml2.c
*/
#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>
int
main(int argc, char **argv)
{
xmlDoc *document;
xmlNode *root, *first_child, *node;
char *filename;
if (argc < 2) {
fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
return 1;
}
filename = argv[1];
document = xmlReadFile(filename, NULL, 0);
root = xmlDocGetRootElement(document);
fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
first_child = root->children;
for (node = first_child; node; node = node->next) {
fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
}
fprintf(stdout, "...\n");
return 0;
}
LEFT(colName, 1)
will also do this, also. It's equivalent to SUBSTRING(colName, 1, 1)
.
I like LEFT
, since I find it a bit cleaner, but really, there's no difference either way.
Edited and fixed (thanks to Shredder)
If you mean you want to open a new tab, try the below:
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Target = "_blank";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Otherpage.aspx");
}
This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.
-J
The MySQL documentation has information on mapping MySQL types to Java types. In general, for MySQL datetime and timestamps you should use java.sql.Timestamp
. A few resources include:
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
How to store Java Date to Mysql datetime...?
EDIT:
As others have indicated, the suggestion of using strings may lead to issues.
I have deal with this problem, I have been solved it by MVC design pattern, I created Card class:
@interface Card : NSObject
@property (strong,nonatomic) UIImage* img;
@property (strong,nonatomic) NSString* url;
@end
//then in the UIViewController
in the DidLoad
Method to Do :
// init Cards
Card* card10= [[Card alloc]init];
card10.url=@"image.jpg";
card10.img = [UIImage imageNamed:[card10 url]];
// for Example
UIImageView * myImageView = [[UIImageView alloc]initWithImage:card10.img];
[self.view addSubview:myImageView];
//may you want to check the image name , so you can do this:
//for example
NSString * str = @"image.jpg";
if([str isEqualToString: [card10 url]]){
// your code here
}
I ran into this and it was caused by the entity's ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity's ID has been set.
From Paul Bellora's comment
I had this exact issue, caused by forgetting to include the hidden ID input in the .cshtml edit page
The most Pythonic way to check the type of an object is... not to check it.
Since Python encourages Duck Typing, you should just try...except
to use the object's methods the way you want to use them. So if your function is looking for a writable file object, don't check that it's a subclass of file
, just try to use its .write()
method!
Of course, sometimes these nice abstractions break down and isinstance(obj, cls)
is what you need. But use sparingly.
use the CKEditor.editor.getData() call on the instance. That is to say:
HTML
<textarea id="my-editor">
<input id="send" type="button" value="Send">
JS for CKEditor 4.0.x
$('#send').click(function() {
var value = CKEDITOR.instances['DOM-ID-HERE'].getData()
// send your ajax request with value
// profit!
});
JS for CKEditor 3.6.x
var editor = CKEDITOR.editor.replace('my-editor');
$('#send').click(function() {
var value = editor.getData();
// send your ajax request with value
// profit!
});
Use .prop()
instead and if we go with your code then compare like this:
Look at the example jsbin:
$("#news_list tr").click(function () {
var ele = $(this).find(':checkbox');
if ($(':checked').length) {
ele.prop('checked', false);
$(this).removeClass('admin_checked');
} else {
ele.prop('checked', true);
$(this).addClass('admin_checked');
}
});
Changes:
input
to :checkbox
.the length
of the checked checkboxes
.in Jquery "data" doesn't refresh by default :
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());
You'd use "attr" instead for live update:
alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());
If it is a "NMake Makefile", that is to say the syntax and command is compatible with NMake, it will work natively on Windows. Usually Makefile.win
(the .win
suffix) indicates it's a makefile compatible with Windows NMake. So you could try nmake -f Makefile.win
.
Often standard Linux Makefiles are provided and NMake
looks promising. However, the following link takes a simple Linux Makefile and explains some fundamental issues that one may encounter. It also suggests a few alternatives to handling Linux Makefiles on Windows.
In my case, I had this in my code which did not work:
@Override
protected void onCreate(Bundle savedInstanceState) {
context = getApplicationContext();
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then I played with the order of the code:
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
}
And it worked!
Conclusion: requestWindowFeature should be the first thing you call in the onCreate method.
How about this?
function stringToArray(string) {
let length = string.length;
let array = new Array(length);
while (length--) {
array[length] = string[length];
}
return array;
}
I know this question is pretty old but just want to share my findings.
My laptop is able to handle program which spawns 25,000
threads and all those threads write some data in MySql database at regular interval of 2 seconds.
I ran this program with 10,000 threads
for 30 minutes continuously
then also my system was stable and I was able to do other normal operations like browsing, opening, closing other programs, etc.
With 25,000 threads
system slows down
but it remains responsive.
With 50,000 threads
system stopped responding
instantly and I had to restart my system manually.
My system details are as follows :
Processor : Intel core 2 duo 2.13 GHz
RAM : 4GB
OS : Windows 7 Home Premium
JDK Version : 1.6
Before running I set jvm argument -Xmx2048m
.
Hope it helps.
For me, the trick was extraData and drilling down into the item component one more time
state = {
uniqueValue: 0
}
<FlatList
keyExtractor={(item, index) => item + index}
data={this.props.photos}
renderItem={this.renderItem}
ItemSeparatorComponent={this.renderSeparator}
/>
renderItem = (item) => {
if(item.item.selected) {
return ( <Button onPress={this.itemPressed.bind(this, item)}>Selected</Button> );
}
return ( <Button onPress={this.itemPressed.bind(this, item)}>Not selected</Button>);
}
itemPressed (item) {
this.props.photos.map((img, i) => {
if(i === item.index) {
if(img['selected') {
delete img.selected;
} else {
img['selected'] = true;
}
this.setState({ uniqueValue: this.state.uniqueValue +1 });
}
}
}
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
You can use clone() method to create a copy..
$('#foo1').html( $('#foo2 > div').clone())?;
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:
$('div#id').click(function (e) {
// Do whatever you want
});
This solution has the distinct advantage of keeping the logic not in your markup.
Catastrophically bad:
int main(void){
char *s;
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
Better:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
int ln;
puts("Enter String");
// scanf("%s", s);
gets(s);
ln = strlen(s); // remove this line to end seg fault
char *dyn_s = (char*) malloc (strlen(s)+1); //strlen(s) is used here as well but doesn't change outcome
dyn_s = s;
dyn_s[strlen(s)] = '\0';
puts(dyn_s);
return 0;
}
Best:
#include <stdio.h>
#define BUF_SIZE 80
int
main(int argc, char *argv[])
{
char s[BUF_SIZE];
int ln;
puts("Enter String");
fgets(s, BUF_SIZE, stdin); // Use fgets (our "cin"): NEVER "gets()"
int ln = strlen(s);
char *dyn_s = (char*) malloc (ln+1);
strcpy (dyn_s, s);
puts(dyn_s);
return 0;
}
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
The others did not work in my case (Bootstrap 4). Here is the solution I used.
html .form-control::-webkit-input-placeholder { color:white; }
html .form-control:-moz-placeholder { color:white; }
html .form-control::-moz-placeholder { color:white; }
html .form-control:-ms-input-placeholder { color:white; }
If we use a stronger selector (html
first), we don't need to use the hacky value !important
.
This overrides bootstraps CSS as we use a higher level of specificity to target .form-control elements (html
first instead of .form-control
first).
The server directive has to be in the http directive. It should not be outside of it.
Incase if you need detailed information, refer this.
String and NSString are toll free bridge so you can use all methods available to NSString with swift String
let x = "test" as NSString
let y : NSString = "string 2"
let lenx = x.count
let leny = y.count
There was a time when adding strings into an array and finalising the string by using join
was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that +
and +=
methods are fastest/best
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
You can also try this:
ini_set("max_execution_time", "-1");
ini_set("memory_limit", "-1");
ignore_user_abort(true);
set_time_limit(0);
Here is the one through AWK:
$ foo="Hello"
$ foo=$(awk -v var=$foo 'BEGIN{print var" World"}')
$ echo $foo
Hello World
You have to catch the error just as you're already doing for your save()
call and since you're handling multiple errors here, you can try
multiple calls sequentially in a single do-catch block, like so:
func deleteAccountDetail() {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
do {
let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
} catch {
print(error)
}
}
Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws
then try
to call the method. For example:
func deleteAccountDetail() throws {
let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
let request = NSFetchRequest()
request.entity = entityDescription
let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]
for entity in fetchedEntities {
self.Context!.deleteObject(entity)
}
try self.Context!.save()
}
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
myString.substring(str.length,str.length-1)
You should be able to do something like the above - which will get the last character
Since you are always initialising self.listMyData
to an empty list in clkFindMost
your code will always lead to this error* because after that both unique_names
and frequencies
are empty iterables, so fix this.
Another thing is that since you're iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.
Lastly dict.get
is a method not a list or dictionary so you can't use []
with it:
Correct way is:
if frequencies.get(name):
And Pythonic way is:
if name in frequencies:
The Pythonic way to get the frequency of items is to use collections.Counter
:
from collections import Counter #Add this at the top of file.
def clkFindMost(self, parent):
#self.listMyData = []
if self.listMyData:
frequencies = Counter(self.listMyData)
self.txtResults.Value = max(frequencies, key=frequencies.get)
else:
self.txtResults.Value = ''
max()
and min()
throw such error when an empty iterable is passed to them. You can check the length of v
before calling max()
on it.
>>> lst = []
>>> max(lst)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
mx = max(lst)
else:
#Handle this here
If you are using it with an iterator then you need to consume the iterator first before calling max()
on it because boolean value of iterator is always True
, so we can't use if
on them directly:
>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
mx = max(lst)
else:
#Handle this here
Good news is starting from Python 3.4 you will be able to specify an optional return value for min()
and max()
in case of empty iterable.
My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.
To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.
To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:
ciphertext = ( plaintext^e ) mod n
To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:
plaintext = ( ciphertext^d ) mod n
To generate private (d,n) key using openssl you can use the following command:
openssl genrsa -out private.pem 1024
To generate public (e,n) key from the private key using openssl you can use the following command:
openssl rsa -in private.pem -out public.pem -pubout
To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):
openssl rsa -in private.pem -text -noout | less
modulus - n
privateExponent - d
publicExponent - e
prime1 - p
prime2 - q
exponent1 - d mod (p-1)
exponent2 - d mod (q-1)
coefficient - (q^-1) mod p
Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.
Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:
# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der
# Print private.der private key contents as binary stream
xxd -p private.der
# Now compare the output of the above command with output
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less
This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.
To see the contents of the public.pem public RSA key run the following (output truncated to labels here):
openssl rsa -in public.pem -text -pubin -noout
Modulus - n
Exponent (public) - e
No surprises here. It's just (n, e) pair, as promised.
Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.
I had the same issue in MIUI. Enabling OEM unlocking worked for me without disabling MIUI optimization.
Below is a screenshot of my Redmi 3s prime developer options setting:
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).