text:
Q: React Automatic TrafficLight I'm trying to build a traffic light that changes every 5 seconds using react and states.
So it works perfectly the first run through, but then starts overlapping and spazzing out after that. I know why, my setInterval is being called multiple times.
My question is, how can I get it to loop through just one at a time, forever?
Code in question:
import { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles(() => ({
  greenBg: {
    backgroundColor: "#acffa1",
    height: "1000px",
    color: "green",
    display: "flex",
    alignItems: "center",
    flexDirection: "column"
  },
  yellowBg: {
    backgroundColor: "#fbff82",
    height: "1000px",
    color: "#b6c700",
    display: "flex",
    alignItems: "center",
    flexDirection: "column"
  },
  redBg: {
    backgroundColor: "#ff5757",
    height: "1000px",
    color: "#a30000",
    display: "flex",
    alignItems: "center",
    flexDirection: "column"
  },
  trafficlight: {
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "white",
    position: "absolute",
    top: "25%",
    border: "1px solid black",
    width: "180px",
    height: "350px",
    borderRadius: "10px"
  },
  text: {
    fontSize: "50px",
    position: "absolute",
    top: "85%",
  },
  lights: {
    marginTop: "20%"
  },
  light: {
    border: "1px solid lightgrey",
    borderRadius: "50px",
    width: "50px",
    height: "50px",
    marginBottom: "40px",
    backgroundColor: "lightgrey"
  },
  greenLight: {
    border: "1px solid lightgrey",
    borderRadius: "50px",
    width: "50px",
    height: "50px",
    marginBottom: "40px",
    backgroundColor: "green",
  },
  yellowLight: {
    border: "1px solid lightgrey",
    borderRadius: "50px",
    width: "50px",
    height: "50px",
    marginBottom: "40px",
    backgroundColor: "yellow"
  },
  redLight: {
    border: "1px solid lightgrey",
    borderRadius: "50px",
    width: "50px",
    height: "50px",
    marginBottom: "40px",
    backgroundColor: "red"
  },
}));

function TrafficLight() {
  const classes = useStyles();
  const [green, setGreen] = useState(classes.greenLight)
  const [yellow, setYellow] = useState(classes.light)
  const [red, setRed] = useState(classes.light)

  const [bgColor, setBgColor] = useState(classes.greenBg)
  const [color, setColor] = useState("green")

  setInterval(function () {
    if (green === classes.greenLight) {
      setYellow(classes.yellowLight)
      setBgColor(classes.yellowBg)
      setColor("yellow")
      setGreen(classes.light)
      setRed(classes.light)
      return
    }

    if (yellow === classes.yellowLight) {
      setRed(classes.redLight)
      setBgColor(classes.redBg)
      setColor("red")
      setYellow(classes.light)
      setGreen(classes.light)
      return
    }

    if (red === classes.redLight) {
      setGreen(classes.greenLight)
      setBgColor(classes.greenBg)
      setColor("green")
      setYellow(classes.light)
      setRed(classes.light)
      return
    }
  }, 1000);

  return (

        The light is {color}.

  );
}

export default TrafficLight;

A: The problem is, every time your app renders TrafficLight(), it registers a new periodic timer, so the more times your component is re-rendered, the more timers are running simultaneously, all modifying the component state.
EDIT:
Actually, I've realized a zero-dependency effect hook will not work in your case, because the callback to setInterval does depend on the state of the component. So you do need to pass its dependencies to the effect hook. This way, each time the state is updated, your callback will also be updated so that it performs the proper behavior. With this solution, it is also vital to have a cleanup for the effect - this is what will prevent multiple timers from running at the same time.
Updated Code
function TrafficLight() {
  // ... Your code

  useEffect(() => {
    const intervalHandle = setInterval( /** Your callback code */ )

    // This will cancel the previous timer each time the component is re-rendered due to changing any of
    // the passed dependencies.
    return function cleanup() {
      clearInterval(intervalHandle)
    }
  }, [red, green, yellow])

  // Your code
}

Previous Answer: The solution is to use a zero-dependency effect hook. Such a hook will run the code given to it only when your component is initially set. It's also a good idea to cancel the timer when the component is unmounted, which is done by returning a callback from the effect hook. The result should look something like this:
function TrafficLight() {
  // ... Your code

  useEffect(() => {
    const intervalHandle = setInterval( /** Your callback code */ )

    // This will cancel the timer after the component unmounts.
    return function cleanup() {
      clearInterval(intervalHandle)
    }
  }, [])

  // Your code
}

A: You should set the interval function inside of a useEffect method with an empty dependency array, so it only runs once when the component mounts.
As it is now, I believe that the setInterval is being called every time the state changes and the component re-renders.


text:
Q: Why does shift+click open up new tab in firefox for D3 images but not HTML images I have an example of my code here :
http://jsfiddle.net/rxzyLsbg/
The image on the left is created in simple html image tag :

The one on the right made with d3 :
<svg id="svg"  /> </svg>

d3.select("#svg").append("image")
    .attr("xlink:href", "http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg")
    .attr("x", -12)
    .attr("y", -12)
    .attr("width", 50)
    .attr("height", 50)
    ;

When opening this in Firefox and shift+clicking on the images the HTML tag doesn't open in a new tab however the one created in D3 does.
Is there a reason for this ?
I asked another question about this and the code here was suppose to help but doesnt with the D3 :
jQuery(document).keydown(function(e){
  if(e.which === 16) {
      console.log('keydown');
      e.preventDefault();
    return;
  }
});

A: It is because check second below. It has href link so it will in new tab.
<image href="http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2014/4/11/1397210130748/Spring-Lamb.-Image-shot-2-011.jpg" x="-12" y="-12" width="50" height="50"/>

Where as first image contains source(src) link of image.

So it will not open in new tab.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FileProvider path creation and BitmapFactory.decodefile problems in Android I am trying to use BitmapFactory.decodefile() in order to create a scaled down
version of a camera photo and set it to an imageview in my framelayout.
Am following the following instructions from Android Developers:
https://developer.android.com/training/camera/photobasics.html
In these instructions, files are created and stored inside a fileprovider which holds some meta-data file formatted in xml. Somehow, BitmapFactory.decodefile() can't seem to access this file which stores a picture whose content uri resides inside the fileprovider.
The fileprovider is created inside the androidmanifest file as follows:
<provider
android:authorities="mypackagename.fileprovider"
android:name="android.support.v4.content.FileProvider"
android:exported="false" android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"  >
</meta-data>
</provider>

the file_paths xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images"            path="Android/data/mypackagename/files/Pictures/" />
</paths>

The file name for where the picture will reside is generated via this method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName,".jpg",storageDir);

// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.d("absolute",""+image.getAbsolutePath());
return image;
}

The code starts an intent in order to take a picture with startactivityforresult() like this:
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (i.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File

}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile  (this,"mypackagename.fileprovider",photoFile);

i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(i,TAKE_PICTURE);
}
}

Now, onActivityForResult() method starts, but if I set my if statement like this
    if(requestCode == TAKE_PICTURE && resultCode == RESULT_OK)
it doesn't work. I don't know why.
From reading the android reference documents on fileprovider class, I see that
I must open the photoUri which is passed as an extra in my intent.
According to the docs, I must open It with ContentResolver.openFileDescriptor which will return a ParcelFileDescriptor. Somehow, this is where the picture the camera just took resides. Somehow I need to access the file name from this ParcelFileDescriptor object and pass it to BitmapFactory.decodefile in order to scale down the picture-bitmap and set it on my imageview. I don't know how to go about this
When trying to scale the picture-bitmap I have the following code that returns -1, meaning that "according to the android reference docs for BitmapFactory class" "there was a problem decoding the file". I don't know why there would be a problem. Here's the code that returns -1:
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);

int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

Both photoW and photoH return -1. Remember that the variable mCurrentPhotoPath was initialized inside the method CreateImageFile() , all the way at the top of this question.
I've also tried,
BitmapFactory.decodeFile(photoFile.getAbsolutePath(), bmOptions);

But still the same result, actually mCurrentPhotoPath and photoFile.getAbsolutePath() are equal strings.
I think that somehow the fileprovider with its meta-data xml file are somehow hiding the file path from BitmapFactory.decodefile().
The picture is taken when I test the app and is also stored inside my phone picture gallery.
Please provide any advice or suggestions since I need to proceed with the tess-two library and perform OCR with the pictures from the camera.
Thanks for your suggestions

A: I ended here, because I was looking for a way to get Bitmap from an Uri of an image in internal storage, written with FileProvider.
(Followed this answer to write image to internal storage: https://stackoverflow.com/a/30172792/529663)
I was able to get back a readable Bitmap image using GrAndroidDeveloper's answer. Here's how:
ContentResolver cr = getApplicationContext().getContentResolver();
InputStream is = cr.openInputStream(uri);
Bitmap image = BitmapFactory.decodeStream(is);
if (is != null) is.close();

This is useful for the official facebook share, which needs a Bitmap.

A: I have faced exactly the same problem and this is how I dealed with it: first of all set i.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);  as suggested above, before launching the camera. Then, DO NOT use the BitmapFactory.decodeFile() method as it only works with the file:/// type of Uris retrieved using Uri.fromFile(), but not with the content:// type of Uris retrieved using FileProvider.getUriForFile() which is the required way for APIs >= 24.
Instead, use a ContentResolver to open an InputStream and decode the image as follows:
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
ContentResolver cr = getActivity().getContentResolver();
InputStream input = null;
InputStream input1 = null;
try {
    input = cr.openInputStream(photoUri);
    BitmapFactory.decodeStream(input, null, bmOptions);
    if (input != null) {
        input.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}

int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
try {
    input1 = cr.openInputStream(photoUri);
    Bitmap takenImage = BitmapFactory.decodeStream(input1);
    if (input1 != null) {
        input1.close();
    }
} catch (Exception e) {
    e.printStackTrace();
}

Note, that in order to obtain the Bitmap, you have to open a 2nd input stream, since the first one cannot be reused.


text:
Q: GeoServer WFS 2.0 CSV output multiple features/typeNames I'm setting up an export function so that users may download data from a GeoServer WFS 2.0 service in a variety of the supported formats.
The service has multiple FeatureTypes which should be available for export in a single query (along with BBOX and attribute filtering).
For simplicity we are using a get request at this stage (more due to applications requirements).
I have a query like this:
http://www.myurl.com/wfs?
service=WFS&
request=GetFeature&
version=2.0.0&
count=9999999999&
typeName=a_prefix_here:feature_type_one,a_prefix_here:feature_type_two&
outputFormat=csv&

The problem is: the data from feature_type_two is not included in the exported CSV file (only exports the first feature)?
Confusingly though; feature_type_two's data is included when exporting to other formats, e.g. JSON, KML, XML?
Has anybody else had this issue?


text:
Q: Why is "long" interpretation of kCFPositiveInfinity different on various iDevices? I have been tinkering with NSNumber for a little while when searching for infinity value and I have come across one interesting fact. When I do this:
long infinity = [((NSNumber *)kCFNumberPositiveInfinity) longValue];

32bit simulator interprets it as 0, while 64bit simulator interprets it as -9223372036854775808.
Now I remember my Computer Architecture 101 and they used to tell us - 32bit = smaller range, 64bit = wider range. But obviously, on 64bit simulator's interpretation of positive infinity there is an overflow(since my research tells me that positive infinity will most likely be a positive number).
The question is - is this a feature(if so, then why?), or a bug?

A: With the 32 bit simulator,
If you make an object from (NSNumber *)kCFNumberPositiveInfinity like this:
NSObject *dummy = (NSNumber *)kCFNumberPositiveInfinity;

and inspect it, you will see it is this:
dummy = (__NSCFNumber *)(double)inf

and when you convert it to an long value like this:
long longDummy = [(NSNumber *)dummy longValue];

it gets set to 0
if you just set a long to that value like this:
long testDummy = kCFNumberPositiveInfinity;

it gets set to 53994368
The problem (whether it be a bug, or just an unexpected implementation) is in the format of this call
[((NSNumber *)kCFNumberPositiveInfinity) longValue];

where you force it to an NSNumber, which defaults to a double, because it doesn't know better, and then get a longValue from a double.


text:
Q: ReactJS, react-router and socket.io I'm learning ReactJS, Express and socket.io by making a small application where users can join rooms, and interact with each other inside the room (content NYI). Currently, the idea is to have a RoomList view, and an individual Room view. The number of current users in a room should be visible in the RoomList (Room 1: 2 users, for example).
My router config looks like this:
<Router history={hashHistory}>
    <Route path="/" component={App}>
        <Route path="rooms" component={RoomList}></Route>
        <Route path="rooms/:roomId" component={Room}></Route>
    </Route>
</Router>

And the App component:
export default React.createClass({
  componentDidMount() {
    var socket = io.connect('/')
    socket.on('connect', function(data) {
      socket.emit('message', "Dududu")
      socket.on('message', function(data) {
        console.log("Message:", data);
      })
    })
  },

  render() {
    return (

        {this.props.children}

    )
  }
})

The problem is, how can I access the socket instance created here in another component? For example, I'd like to add socket events for joining/leaving a room and other room-specific events in the Room component, updating the RoomList's user count in the RoomList component etc. How can I share the socket object globally, or what is the recommended practice for dealing with sockets and multiple components?

A: Found out what to do through vigorous googling and github issue searching, in the App component do this.setState({socket: socket}) and then for the view, use React.cloneElement, passing the socket as a prop. Then you can access the socket from child components through this.props.socket.
export default React.createClass({
  componentWillMount() {
    var socket = io.connect('/');
    this.setState({socket: socket});
  },

  render() {
    return (

        {
          React.cloneElement(this.props.children, {socket: this.state.socket})
        }

    )
  }
})

A: Another solution that I just did on my chat app where I could send realtime communication without any rendering.
I just used uuid in the parent components state to create an id that I could pass from the parent to context then access in any child component. At that point I just created a room between whatever components that I wanted to share info with and named it using that uuid.
The reason I went this route rather than Fissio's is because I didn't want to store that huge socket in state.
Now you can have multiple users who each have a unique socket just for them!


text:
Q: ui-grid use only editable cellTemplate I want a ui-grid where you can edit directly without changing the template.
I tried to override the cellTemplate with the standard of the editable celltemplate, but it isnt getting dirty now.

<form name="inputForm"><input type="INPUT_TYPE" ng-class="'colt' + col.uid" ui-grid-editor ng-model="MODEL_COL_FIELD"></form>

So i dont want to show the cellTemplate instead i want to show the editable cellTemplate only.

A: It looks totally possible to me, just make sure your field attribute contains no unusual symbols (dash or dots mainly, use only letters to be on the safe side).
Look at this plunkr.


text:
Q: Escape newline character while encoding in base64 I have a situation where in my BASH script, I need to encode an environment variable to base64 and write it to a json file, which is then picked up by docker.
I have the below code for this:
USER64=$(echo $USER | base64)
echo '{"auths": {"auth": "'"$USER64"'}}' > ~/.docker/config.json

This works, but the problem is the encoded value of $USER contains a \n so the echo writes it into the config file as 2 lines. How can I escape all the \n while encoding the $USER and write it to the config file?

A: As added incentive to use jq, it can do the base64 encoding for you:
jq -n --arg u "$USER" '{auths: {auth: ($u | @base64)}}' > ~/.docker/config.json

(And as far as I can tell, @base64 is working on the original value, not the JSON-encode value, of $USER.)

A: You can use the substitution operator in shell parameter expansion.
echo '{"auths": {"auth": "'"${USER64/$'\n'/\\\n}"'}}' > ~/.docker/config.json

But you can also use an option to base64 to prevent it from putting newlines into the encoding in the first place.
USER64=$(echo $USER | base64 --wrap=0)


text:
Q: how to use instantiateItem() in viewpager to update pages
Possible Duplicate:
how can i update view when fragment change?

have a activity that have 2 fragment in this The first two pages display fragments with custom list views which are built from xml from server using AsyncTask. However, when the app runs, only one list view is displayed, the other page is just blank
what can i use this method to update this pager
public Object instantiateItem(View container, int position) {

and my adapter code is
public class VpiAbsTestActivity extends SherlockFragmentActivity {

private static final String[] CONTENT = new String[] { "1","2"};

TestFragmentAdapter mAdapter;
 ViewPager mPager;
 PageIndicator mIndicator;

protected void onCreate(Bundle savedInstanceState) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);

mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);

mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
mIndicator.notifyDataSetChanged();
}

class TestFragmentAdapter extends FragmentPagerAdapter {
private int mCount = CONTENT.length;

public TestFragmentAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    switch(position) {

    case 0:
        return new customlist();

    case 1:
        return new customlistnotuser();

    default:
        return null;

    }
}

@Override
public int getCount() {
    return mCount;
}

public CharSequence getPageTitle(int position) {
    return VpiAbsTestActivity.CONTENT[position %             VpiAbsTestActivity.CONTENT.length].toUpperCase();
}

 @Override
    public void destroyItem(View collection, int position, Object view) {
         ((ViewPager) collection).removeView((View) view);
    }

 }


text:
Q: Is $a \sin x + b \sin y \leq \sin(ax + by)$ true? Studying math essay exam, I saw the following strange formula
$$ a \sin x + b \sin y \leq \sin(ax + by), $$
where $x, y$ are arbitrary angles and $a + b = 1.$
Is the above inequality true, and can it be proved?

A: False if $x$ and $y$ are really arbitrary. Consider $a=b=\frac12$ and $x=0$ and $y=3\pi$:
\begin{align}
a\sin x+b\sin y&=\frac12 \sin(3\pi) = 0 \\
\sin(ax+by) &= \sin\left(\frac{3\pi}2\right)  = -1
\end{align}
It is true if you restrict to the concave region of sine (e.g. $0\le x,y\le\pi$) and $a,b\ge0$, which it is a special case of Jensen's inequality.


text:
Q: Accessing scratch pad memory from C That might be a little bit an exotic problem, but I hope somebody can
  still help me out a bit ;). I would like to execute a standard C program,
  however, at some point during program execution I would like that a certain
  number of instructions, which are stored in a local scratch pad RAM, are
  executed. The scratchpad memory is accessable for all processes. Lets assume
  this local memory starts at address 0x80000000 and I would integrate this
  in the following C code fragement
int main {
int a=1;
int b=2;
int c=3;

c = a + b;

%goto address 0x80000000 and execute three instructions before continuing
%program execution here

return(0);

}
The program counter would go through the following stages, assuming
  main is loaded at 0x40000000
0x40000000    a=5;
0x40000004    b=2;
0x40000008    c=1;
0x4000000C    c=a+b;
0x80000000    first instruction in the local scratch pad
0x80000004    second instruction in the local scratch pad
0x80000008    third instruction in the local scratch pad
0x40000010    return(0);

Anyone an idea how to do this? Do I need to use assembler jump
 instructions or is there something more elegant.
Many thanks,
 Andi

A: Assuming that the instructions behave like a normal function, you can do:
#include <stdio.h>

void (*scratchpad_func)(void) = (void(*)(void))0x80000000;

int main()
{
    printf("before\n");
    scratchpad_func();
    printf("after\n");
    return 0;
}

Obviously, you'll have to be using a real mode operating system, or jump through whatever hoops your OS/processor combination requires to have direct access to that address space.
(On some architectures "behave like a normal function" is as simple as a "jump $ra" at the end if you don't touch callee-saved registers. E.g. MIPS.)

A: Neither casting the address to a function pointer nor inline assembler is normalized, so nothing of that would be portable ;-)
Mapping the fixed address as Carl mentions is possible with POSIX, but then again to get it executed, there is no simple way.
What none of the previous post answers either, is how to jump back after exactly three instructions...
The only way I can think of would really be to copy just the three instructions somewhere and place an unconditional jump immediately after it. Then use an inline assembler instruction to jump to that location.

A: To jump to a fixed location, you can declare a type that's a pointer to a function, then cast your address to that type and call it as a function.
If you want this memory area to be accessible to processes other than your program, you'll have to use your operating system's (Windows/Linux/OS X) shared memory primitives to map a chunk of memory to your chosen address.
Sounds like a crazy idea, but it could be made to work. Good luck!

A: Well a couple of hints.

*

*You need to ensure that the memory in the "scratch pad" is addressable and executable.

*Make sure that the sequence of instructions in the memory location ends with a ret instruction

*call the code rather than jumping to it.


text:
Q: Obj-C IBAction (id)sender I have an IBAction like:
- (IBAction)thisThing:(id)sender {

  [self doSomething];
}

I would like do this (manually call the IBAction):
[self thisThing];

However I obviously need to do [self thisThing:...];. <- (what the heck goes after the colon?)
I'm not sure what (id)sender is supposed to be. How do call it manually without needing to click the button that it's tied to? I searched for anything about IBAction (id)sender and the results came up completely empty.

A:
what the heck goes after the colon?

Well it depends on how you have written code inside the IBAction. Say for a calculator app, if all buttons are hooked up with the same IBAction then you would need sender (in this case NSButton) to identify which button got touched/clicked.
-(IBAction) buttonClicked:(id) sender {
    // sender's identifier or Tag will let us know the number clicked here
    [self doSomeThing];
}

But if you had IBActions for each and every button you would not need to be dependent on sender.
-(IBAction) firstButtonClicked:(id)sender;
-(IBAction) secondButtonClicked:(id)sender;

and so on ...
So in the first case if I want to programatically invoke the action I would pass the sender with appropriate attributes set to make sure the correct button got clicked. In second case just pass nil as it does not depend upon sender's value.

A: If you have the IBOutlet of the button, you can pass that like [self thisThing:btn];
Or simply pass nil, [self thisThing:nil]; (if you are not using sender inside the IBAction)

A: While popeye's comment answers your question, here's another perspective.
You have complete control over the action method. If you aren't using the sender parameter for anything in that method, then you do not have to supply it when calling it manually. By not supply it I mean pass nil as the value of the parameter.
Normally, it will contain a pointer to the control that is wired up to the action. If you did want to use if for something, they you would simply cast sender to the type of the control and do whatever with it.

A: - (IBAction)thisThing:(id)sender
In here,
- denotes the start of a instance method, whereas + means class(static) method.
( .. ) indicate return type. IBAction is actually void. Using IBAction instead of void tells that this method will be associated with UI(.nib) events.
thisThing is the name of the method, followed by parameter list.
In C view point, actual function names is something like thisThing:. That is, number of parameter modifies function name (external linkage).
If you meant to call thisThing: but write [self thisThing], you are calling different (not existing) method.
So, you must write :. What actual value to pass? One can decide this by looking at the method implementation.

A: - (IBAction)thisThing:(id)sender {
}

Is an event handler. That means that it is called when an event is sent by someone. A typical example of an event is a click on a button, it that case, the button sends the event (that means the button, a NSButton instance, is the sender).
Having the sender as a parameter is useful when you use the same event handler for events coming from different sources, e.g.
- (IBAction)buttonTapped:(id)sender {
    if (sender == self.myButton1) {
       //button 1 was tapped
    }
    else if (sender == self.myButton2) {
       //button 2 was tapped
    }
}

If this case, if you want to call the event handler manually, you just call
[self buttonTapped:self.myButton1];

If you don't use the sender parameter, then you can simply call
[self buttonTapped:nil];

However, the parameter is completely optional, so you can eliminate it:
- (IBAction)buttonTapped {
    // ...
}

[self buttonTapped];

On a separate note, it's never good to call event handlers manually. Event handlers serve to handle events. If you need to perform the same action manually, separate it from the event handler, e.g.
- (IBAction)buttonTapped {
    [self doSomething];
}

instead of calling [self buttonTapped], call [self doSomething]


text:
Q: How to Get Last 10 Completed Runs of a Windows Scheduled Task I've been asked to get a certain amount of completed tasks from the windows task scheduler using Python.
I'm a bit of a novice when it comes to Python (I mostly code with NodeJS stacks), but I've figured out (with a lot of googling) how to pull arguments from the command line and pull tasks out of specific folders in the task scheduler.
I'm using win32com, I've seen others use pywin, but I have found little to no documentation on either. I've tried printing vars and attributes of the scheduler object to get an idea of what options I have to interact with it, but this has not given me an idea of what properties exist that I can pull to get the information that I want. I've also checked the Microsoft documentation for the task scheduler, but I couldn't figure out where the data I was looking for is, nor did I understand most of what I saw.
If anyone could tell me if I am on the right track and how to pull completed tasks instead of just the last run, I'd greatly appreciate it. I imagine there is a property of the task object in the scheduler that has an array of completed runs, but I might be wrong.
CODE
# !/usr/bin/python
import sys
import win32com.client
import pprint

# Sample Command
# python getTasks.py \ASUS\ACPowerNotification 10

# Desired Arguments
ARGCOUNT = 3
# Start index for arguments
ARGINDEX = 1

# Validate Args
if len(sys.argv) < ARGCOUNT:
    print('Not enough args')

elif len(sys.argv) > ARGCOUNT:
    print('Too many args')

# correct argument number
else:
    # set arguments
    taskName = sys.argv[ARGINDEX]
    lastXEvents = sys.argv[ARGINDEX + 1]

    # check if event count arg is a number
    if not lastXEvents.isnumeric():
        print('Arg 2 is not a number:', str(lastXEvents))

    # Connect to task scheduler
    scheduler = win32com.client.Dispatch('Schedule.Service')
    scheduler.Connect()

    # use n to determine how many events were printed,
    # stop when event count arg is reached
    count = 0

    # iterate through folders to print task details
    # check if folders tasks are part of task argument string along the way
    folders = [scheduler.GetFolder('\\')]
    while folders:
        folder = folders.pop(0)
        if taskName.find(str(folder)) != -1:            # If folder is not part of task arg path, skip
            print(str(folder))
            folders += list(folder.GetFolders(0))       # Collects subFolder names
            tasks = list(folder.GetTasks(1))            # Gets hidden tasks (1)
            for task in tasks:                          # loop through task array
                if taskName.find(task.Path) != -1:      # If task matches task arg, print details
                    count += 1                          # Iterate task print count
                    settings = task.Definition.Settings
                    # print task details
                    print('Path       : %s' % task.Path)
                    print('Last Run   : %s' % task.LastRunTime)

SAMPLE OUTPUT
\
\ASUS
Path       : \ASUS\AcPowerNotification
Last Run   : 2022-08-07 13:56:00+00:00


text:
Q: Get form parameter in EJS template Hello I'm learning to use Nodejs on my own, and I'm struggling on something that looks really really simple but with fatigue I can't seem to make it work even with an embarassing number of google searches. I tried to unstuck myself but I need help.
Here is part of my code.
I use EJS for the template.
var express = require('express');
var request = require('request');
var bodyParser = require("body-parser");
const querystring = require('querystring');
const url = require('url');

var app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
const fetch = require("node-fetch");

// URL par défaut
 app.get('/', function (req, res) {
    res.render('index');
 });
//------------------------------------------------------
// Client
 app.get('/client', function (req, res) {
    res.render('client');
 });
 // Edit Client
 app.get('/Eclient, function (req, res) {
    res.render('eclient', {query : req.query});
 });

// set port
 app.listen(3001, function () {
     console.log('Node app is running on port 3001');
 });
 module.exports = app;

On my Client page there is a form that is sending to Eclient a parameter called pIDC, with an URL like this :
http://localhost:3001/Eclient?pIDC=1
I want to get the value of pIDC on my EJS page with something like <%= req.query.pIDC%>; so I can in a second time query the data of the client from my API. But I can't seem to make it work, everytime the data is undefined.
I'm sure it's trivial, but I can't seem to make it work even with all the searches I did. What am I missing ?

A: That's right, you pass to the template through the  variable "query"
like  {query:  req.query} and in template  EJS you get the variable "query" and show it. I include "if" for don't show the variable "query" if we don't have query variable from url.
You can learn more in documentation on EJS
<% if (query && query.pIDC) { %>
<%= query.pIDC %>
<% } %>


text:
Q: Lists.asmx and List Item Attachments How would the lists.asmx service be used to add an attachment to a list item with JavaScript File API?
I cannot find an example of anything other than copy.asmx for adding documents.
Update:
Here is the code I am using. I have tried the FQDN of the server and the short form as in the code. I'm not sure what is going on but the error is:
<?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <soap:Body>
            <soap:Fault>
                <faultcode>soap:Server</faultcode>
                <faultstring>Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.</faultstring>
                <detail>
                    <errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.</errorstring>
                    <errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x8102006d</errorcode>
                </detail>
            </soap:Fault>
        </soap:Body>
    </soap:Envelope>

Code sample:
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/">
            <listName>MarketNeed</listName>
            <listItemID>1</listItemID>
            <fileName>test.txt</fileName>
            <attachment>dGVzdA==</attachment>
        </AddAttachment>
    </soap:Body>
</soap:Envelope>

var soapPayload = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><AddAttachment xmlns="http://schemas.microsoft.com/sharepoint/soap/"><listName>MarketNeed</listName><listItemID>1</listItemID><fileName>test.txt</fileName><attachment>dGVzdA==</attachment></AddAttachment></soap:Body></soap:Envelope>';

$.ajax({
    url: "http://dev/sites/plm/_vti_bin/lists.asmx",
    type: "POST",
    dataType: "xml",
    data: soapPayload,
    complete: function(){ console.log("Done"); },
    contentType: "text/xml; charset=\"utf-8\""
});

A: You'd have to use the AddAttachment method of the Lists.asmx web service I believe. SO you'd first create the list item and in the response from that, it should tell you the list item ID which you can then pass into the AddAttachemnt method.
Edit from OP:
Here is the code I developed using PirateEric's suggestion. I needed to use SPServices, as I could not seem to get the service to accept my POST. If you look at their code I am sure the single method could be implemented so as to avoid the weight of the entire library.
<img src="attachment-icon.png" id="SECRET-000234-attachment" class=".attachment-target" />

$('.attachment-target').each(function(){
    this.ondragover = function () { return false; };
    this.ondragend = function () { return false; };
    this.ondrop = function (e) {
        e.preventDefault();
        var itemInfo = this.id.split("-");
        var listName = plm.lists.byConfidentiality(itemInfo[0]).getMarketneedList();
        //The above code is a custom object that returns
        //the list name based on the "confidentiality"
        //of the item. We use 4 different lists to easily
        //manage the permissions. All perms are at teh list
        //level only.
        var itemId = parseInt(itemInfo[1]);

      var file = e.dataTransfer.files[0],
          reader = new FileReader();
      //In prod this would be in a for loop, of course.
      reader.onload = function (event) {
        $().SPServices({
            operation: "AddAttachment",
            listName: listName,
            listItemID: itemId,
            fileName: file.name,
            attachment: event.target.result.split(",")[1],
            completefunc: function (xData, Status) {
                                     //Do stuff
            }
          });
      };
          return false;

};
});

A: Add the soap action parameter and its value, it will resolve your error.


text:
Q: How to match open and stat mode_t? I'm creating a file with open and setting its permissions, then I get the file permissions using stat....the permissions don't match.
The result of the program below is:

mode from open (600) and stat (100600) are different

How can I compare the mode(permissions) set by open(2) and retrieved with stat(2)?
#include <sys/types.h>
#include <sys/stat.h>

#include <fcntl.h>
#include <stdio.h>

int
main(int argc, char **argv, char **env) {

        const char *path = "/tmp/test";
        const mode_t mode = S_IRUSR | S_IWUSR;

        if (open(path, O_RDWR |  O_CREAT | O_EXCL, mode) == -1)
                err(1, "open for '%s' failed", path);

        struct stat sb;
        if (stat(path, &sb) != 0)
                err(2, "stat failed");

        if (mode != sb.st_mode)
                printf("mode from open (%o) and stat (%o) are different\n",
                        mode, sb.st_mode);

        return 0;
}

Thanks

A: This is because the st_mode member not only contains the access permissions, but a number of other flags as well (e. g. you can check whether the file is a symlink). Docs here.

A: After upvoting user3477950's answer and comment which lead me to the answer; I'm answering my own question with code.
The key part is sb.st_mode & RWX_UGO
So, I ended up with something like:
#define RWX_UGO (S_IRWXU | S_IRWXG | S_IRWXO)
//....
const mode_t file_mode = sb.st_mode & RWX_UGO;
if (mode == file_mode)
        printf("file_mode (%o) & RWX_UGO(%o) equals to(%o) which is "
                    "equal to mode(%o)\n", sb.st_mode, RWX_UGO,
                    file_mode, file_mode);
else
        printf("mode from open (%o) and stat (%o) are different\n",
                    mode, file_mode);

which now prints

file_mode (100600) & RWX_UGO(777) equals to(600) which is equal to
  mode(600)


text:
Q: Creating multiple windows I'm using Github Electron and Angular 1.x to build a desktop application. I need to first create a Login window and once login is successful, wanted to show/instantiate the main/actual application window.
How can we destroy current Electron window instance and create a new window instance from AngularJS JavaScript Controller ?

A: The first suggestion I would make would be to not have multiple windows but to instead have multiple routes. To do routes in angular 1.x checkout out the angular-ui-router.
Using routes you would use the same window and change the state of the application running inside of that same window.
However you can also have multiple windows by simply creating multiple BrowserWindow objects or by calling loadURL on the same window multiple times.
You can communicate back to the main process when login is complete using the ipc module, to trigger the desired behavior.
// main.js (main process)
const {app, BrowserWindow, ipcMain} = require('electron')

app.on('activate', () => {
  var win = new BrowserWindow()
  win.loadURL(`file://${__dirname}/login.html`)

  ipcMain.on('login-success', () => {
    win.loadURL(`file://${__dirname}/index.html`)
  })

})

Then in your render process just send the login-success message back.
// login.js (render process)
var {ipcRenderer} = require('electron')

ipcRenderer.send('login-success') // call this after the user logs in


text:
Q: Why are elementary row operation linear transformation? I just started to learn linear algebra and found out that elementary operations could be written in form of matrix so it means that elementary row operations are linear transformation but couldn't justify it. I understand how swap and scale elementary row operations are linear transformation but couldn't understand why sRi + Rj --> Rj is a linear transformation.

A: Let's concentrate on a $3\times 3$ matrix for now. The general theory will become clear. The core idea is that row operations correspond to multiplying by a particular matrix.
Given a matrix
$$
M \equiv \begin{bmatrix}
v_1^1 &  v_1^2 &  v_1^3 \\
v_2^1 &  v_2^2 &  v_2^3 \\
v_3^1 &  v_3^2 &  v_3^3 \\
\end{bmatrix}
$$
We can write our matrix
$M \equiv \begin{bmatrix} r_1 \\ r_2 \\ r_3 \end{bmatrix}$ where each $r_i$ are the rows, defined as $r_i \equiv  \begin{bmatrix} v_i^1  & v_i^2 &  v_i^3 \end{bmatrix}$.
Now, we can look at the row transformation $R_1 \rightarrow \alpha R_1 + \beta R_2+ \gamma R_3$ on matrix $M$ to yield matrix $M'$ as:
$$
\begin{align*}
M' &\equiv
\begin{bmatrix}
\alpha & \beta & \gamma \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
M \\
&=
\begin{bmatrix}
\alpha & \beta & \gamma \\
0 & 1 & 0 \\
0 & 0 & 1
\end{bmatrix}
\begin{bmatrix} r_1 \\ r_2 \\ r_3 \end{bmatrix} \\
&=
\begin{bmatrix} \alpha r_1 + \beta r_2 + \gamma r_3 \\ r_2 \\ r_3 \end{bmatrix}
\end{align*}
$$
So, the matrix $M'$ (obtained after a row transformation) is a linear transform applied onto the original matrix $M$.
For a general transformation, we can create the transformation matrix appropriately, generalising from this example.
This explains why row transformations cannot change the span of the rows: all these transformations can do is to take combinations of existing rows, which does not allow one to access vectors outside the subspace spanned by $\{ r_1, r_2, r_3 \}$.
(note: you might want to check that it's indeed legal to collapse a matrix into the rows $r_i$, and that the composition rules do work out. They do, but it's a good exercise to check that writing the matrix as $r_i$ and performing transformations is the same as writing the entire $v_i^j$.)


text:
Q: How to get java singleton object manager to return any type of object? I'm writing an interactive fiction game in java from scratch.  I'm currently storing all of my game object references in a hashmap in a singleton called ObjectManager.  ObjectManager has a function called get which takes an integer ID and returns the appropriate reference.  The problem is that it returns a BaseObject when I need to return subclasses of BaseObject with more functionality.
So, what I've done so far is I've added a getEntity function which returns BaseEntity (which is a subclass of BaseObject).  However, when I need the function to return to an object that is a subclass of BaseEntity that has added, required functionality, I will need to make another function.  I know there is a better way, but I don't know what it is.  I know very little of design patterns, and I'm not sure which one to use here.  I tried passing 'class' as a parameter, but that didn't get me anywhere.
public BaseObject get(int ID){
    return (BaseObject)refMap.get(ID);
}

public BaseEntity getEntity(int ID){
    return (BaseEntity)refMap.get(ID);
}

Thanks, java ninjas!

A: I would discourage you from proceeding with this design.
Google is eradicating singletons from their Java code base; maybe it's a good idea for you, too.
It sounds like you're trying to do something that's been done well by Spring's ApplicationContext.  You're trying to write a configurable, flexible object factory.  It's been done.  I'd look into dependency injection engines like Spring and Guice.  Even if you decide not to use them, perhaps they can offer some design inspiration.
The best you can do is return an Object and cast.

A: Use a generic return type if you have a Java 5 runtime:
public <Entity extends BaseEntity> Entity getEntity(int ID){
    return (Entity)refMap.get(ID);
}

A: These two methods do the same thing; the second just saves the caller from making a cast. If you don't want to make a function for every subclass, then one answer is simply: don't. The caller has to cast but it works just as fine as what you're doing now, functionally.
You can dress up this same approach in generics:
<U> U get(int id, Class<U> clazz) {
  return (U) refMap.get(id);
}

But it doesn't save the caller much, since it just passes a Class object instead of casting.
If you're not wiling to make the caller do this work, you need to write those specialized methods then.


text:
Q: unable to use external javascript in GWT I want to use goJS with GWT. I downloaded GOJS javascript and put it in the sampleproject folder under war where sampleproject.nocache.js and sampleproject.devmode.js is present. In sampleproject.html i added
<script type="text/javascript" language="javascript" src="sampleproject/go.js">
</script>

In one of the view i used
public static native void initGo() /*-{
    var $$ = go.GraphObject.make;
}-*/;

when i call this function , exception is thrown:
com.google.gwt.event.shared.UmbrellaException: Exception caught: (ReferenceError) @com.amazon.ops.client.OpsMenuView::initGo()([]): go is not defined.
Can anyone please help me with this?

A: Try prefixing the js call with $wnd., e.g.:
var $$ = $wnd.go.GraphObject.make;

As explained here, GWT runs in a nested frame and you must use $wnd to refer to the top level window.

A: Make sure that you put this statement:
<script type="text/javascript" language="javascript" src="sampleproject/go.js">
</script>

before <script src="sampleproject.nocache.js"> statement.


text:
Q: I am trying to get in productname insted of productid in URL's parameter I have links with two varialbes in it:
www.mysite.com/temporary/products.php?catid=1&productid=1

Which I am trying to make it:
www.mysite.com/temporary/products.php/category-name/product-name

A: Dude, why don't you work and think a little bit.
Follow these steps (Only applicable for you)
In your .htaccess do something like this
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ /temporary/products.php?category-name=$1&product-name=$2 [L]
// In above $1 = the Category Name and $2 = Product Name that you want to show

If you need the product id, then you can use pho GET metod to grab the category-name and product-name and make a function to grab ids from names like
public function getIdFromName($name)
{
 $id = // your PDO SELECT
 return $id;
}


text:
Q: Powershell Regex: Match on entire string if it contains a period that is not at the beginning nor the end I've been stuck on this for about 2 days now. Unfortunately I may only use powershell (which I'm not good at). I want to match the following criteria using regex:
hxxp://www[.]website[.]org
google.com
www.google[.]com
foob://geller.xyz
hxxps://website[.]net/tree/branch/etc
I'm looking at urls & domains (for IOCs) that are fanged and defanged. The url/domain are of all different formats except they always include a anycharacter.anycharacter . I thought the best way to match would be if the string has a period with characters on both sides to then match with the beginning and end of the string. The closest I have come is:
^.*\b[^.]+$\b

However, I'm not getting positive results with anything I've tried. I would appreciate if anyone has any ideas. To show that I'm not lazy here's what I've got for the other IOCs (I'm just stuck on this one):
#Select a file with a dialog. TXT only

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = [Environment]::GetFolderPath('Desktop')
    Filter = 'TXT (*.txt)|*.txt'
}
[void]$FileBrowser.ShowDialog()
$FileBrowser.FileNames

#Sets file & applies set string while creating first ouput file

#First regex matches IPV4 <-- works well!
$input_path = $FileBrowser.FileNames
$output_file = 'C:\Users\output.csv'
$regex = '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $output_file

#Second regex2 matches  domains  <- is a problem
$regex2 = '\b^.*[^.]+$\b'
select-string $input_path -Pattern $regex2 -AllMatches | % { $_.Matches } | % { $_.Value } | Out-File -FilePath C:\Users\01100\Desktop\Folder\output.csv -Append

#Third matches any file extension <--- works well!
$regex3 = '^\.[a-zA-Z0-9]+$'
select-string $input_path -Pattern $regex3 -AllMatches | % { $_.Matches } | % { $_.Value } | Out-File -FilePath C:\Users\01100\Desktop\Folder\output.csv -Append

#Fourth matches any hash  <--- works well!
$regex4 = '[A-Fa-f0-9]{15,}'
select-string $input_path -Pattern $regex4 -AllMatches | % { $_.Matches } | % { $_.Value } | Out-File -FilePath C:\Users\01100\Desktop\Folder\output.csv -Append

#Fifth matches defanged IPs  <---works well!
$regex5 = '\b\d{1,3}[^b]\.[^b]\d{1,3}[^b]\.[^b]\d{1,3}[^b]\.[^b]\d{1,3}\b'
select-string $input_path -Pattern $regex5 -AllMatches | % { $_.Matches } | % { $_.Value } | Out-File -FilePath C:\Users\01100\Desktop\Folder\output.csv -Append

A: If I understand correctly, you want to match all lines that represent a domain name or url? You will find out, that is not a trivial matter. There exist various examples of regular expressions to validate domain names or urls (look for example here or here). But the more accurate they are required to be, the more complex they will become.
In your case, it will be even more difficult, because you have different formats (sometimes with or without scheme, or query string).
How accurate your regex needs to be depends on your use case and how much work you are willing to put into it. Based on your example and your question title, I suppose you want a very basic version.
I suggest this one, it should work for the most common cases:
'^([a-z0–9-]+://)?([a-z0–9-]+\.)+[a-z0–9-]+(/.*)?$'

Short explanation:
([a-z0–9-]+://)? check for optional schema at the start (no particular one)
([a-z0–9-]+\.)+[a-z0–9]+ domain incl. optional subdomains, followed by top-level-domain
(/.*)? match optional query string (without validation)
If you need more accuracy, you can use this regex as a first step to filter the input, and then perform further tests on the input strings. You could validate if it's a valid url, or check if the domain name exists.

A: If you are using brackets as a standard for defanged URL/URI, then just look for those. If they are not there, then of course the URL/URL is still hot.
Clear-Host
(@'
hxxp://www[.]website[.]org

google.com

www.google[.]com

foob://geller.xyz

hxxps://website[.]net/tree/branch/etc

.foob://geller.xyz
foob://geller.xyz.
'@) -split "`n" |
ForEach-Object {
    $Url = $PSitem
    Try {Write-Warning -Message "Defanged URL $(([regex]::Matches($Url, '.*\[\.\].*').Value))"}
    Catch {Write-Verbose "Fanged URL : $Url" -Verbose}
}
# Results
<#
WARNING: Defanged URL hxxp://www[.]website[.]org
VERBOSE: Fanged URL :
VERBOSE: Fanged URL : google.com
VERBOSE: Fanged URL :
WARNING: Defanged URL www.google[.]com
VERBOSE: Fanged URL :
VERBOSE: Fanged URL : foob://geller.xyz
VERBOSE: Fanged URL :
WARNING: Defanged URL hxxps://website[.]net/tree/branch/etc
VERBOSE: Fanged URL :
VERBOSE: Fanged URL : .foob://geller.xyz
VERBOSE: Fanged URL : foob://geller.xyz.
#>

If you are just trying to exclude the strings with a 'period' at the beginning or end of a string, regardless of what the string is, then this is a working example of that, utilizing RegEx 'not' expression.
Clear-Host
(@'
hxxp://www[.]website[.]org

google.com

www.google[.]com

foob://geller.xyz

hxxps://website[.]net/tree/branch/etc

.foob://geller.xyz
foob://geller.xyz.
'@) -split "`n" |
ForEach-Object {
Try{([regex]::Matches($PSitem, '^((?!(((^\..*)|(.*\.$)))).)*$')).Value}
Catch{}
}
# Results
<#
hxxp://www.website.org
google.com
www.google.com
foob://geller.xyz
hxxps://website.net/tree/branch/etc
#>

...or doing the reverse, then:
Clear-Host
(@'
hxxp://www[.]website[.]org

google.com

www.google[.]com

foob://geller.xyz

hxxps://website[.]net/tree/branch/etc

.foob://geller.xyz
foob://geller.xyz.
'@) -split "`n" |
ForEach-Object {
Try{([regex]::Matches($PSitem, '^((^\..*|(.*\.$)))')).Value}
Catch{}
}
# Results
<#
.foob://geller.xyz
foob://geller.xyz.
#>

Or skip all the RegEx altogether and say this..
Clear-Host
(@'
hxxp://www[.]website[.]org

google.com

www.google[.]com

foob://geller.xyz

hxxps://website[.]net/tree/branch/etc

.foob://geller.xyz
foob://geller.xyz.
'@) -split "`n" |
ForEach-Object {
    If($PSItem[0] -eq '.' -or $PSItem[-1] -eq '.'){}
    Else {$PSItem}
}
# Results
<#
hxxp://www[.]website[.]org

google.com

www.google[.]com

foob://geller.xyz

hxxps://website[.]net/tree/branch/etc

#>

You could also look to using the .Net namespace to see what is being returned and use the properties to make your decision.
Clear-Host
@'
hxxp://www[.]website[.]org
google.com
www.google[.]com
foob://geller.xyz
hxxps://website[.]net/tree/branch/etc
'@ -split "`n" |
ForEach {
    Try {($PSItem.trim() -as [System.URI])}
    Catch {$PSItem.Exception.Message}
}
# Results
<#
AbsolutePath   :
AbsoluteUri    :
LocalPath      :
Authority      :
HostNameType   :
IsDefaultPort  :
IsFile         :
IsLoopback     :
PathAndQuery   :
Segments       :
IsUnc          :
Host           :
Port           :
Query          :
Fragment       :
Scheme         :
OriginalString : google.com
DnsSafeHost    :
IdnHost        :
IsAbsoluteUri  : False
UserEscaped    : False
UserInfo       :

AbsolutePath   :
AbsoluteUri    :
LocalPath      :
Authority      :
HostNameType   :
IsDefaultPort  :
IsFile         :
IsLoopback     :
PathAndQuery   :
Segments       :
IsUnc          :
Host           :
Port           :
Query          :
Fragment       :
Scheme         :
OriginalString : www.google[.]com
DnsSafeHost    :
IdnHost        :
IsAbsoluteUri  : False
UserEscaped    : False
UserInfo       :

AbsolutePath   : /
AbsoluteUri    : foob://geller.xyz/
LocalPath      : /
Authority      : geller.xyz
HostNameType   : Dns
IsDefaultPort  : True
IsFile         : False
IsLoopback     : False
PathAndQuery   : /
Segments       : {/}
IsUnc          : False
Host           : geller.xyz
Port           : -1
Query          :
Fragment       :
Scheme         : foob
OriginalString : foob://geller.xyz
DnsSafeHost    : geller.xyz
IdnHost        : geller.xyz
IsAbsoluteUri  : True
UserEscaped    : False
UserInfo       :
#>


text:
Q: How to get & set global .class level css values in JQuery What I want to do is something like this.
Get the global css value for a class.
Where .myclass references the actual static class rather then an instance that implements the class.
var currentmargin = $('.myclass').css('margin');

Then display global class css value for user to modify
and then set the changes
$('.myclass').css('margin',newValue);

from a css like below
.myclass {
  margin:10px;
}

Is there a right way to do this in JQuery that I am missing or do I need to extend things with a plugin like http://plugins.jquery.com/project/changecss in order to get the job done?
Thanks in advance.

A: I think you confusing the use of Jquery selectors. The following:
var currentmargin = $('.myclass').css('margin');

Mean: select all elements within HTML document which marked with class named "myclass" and then read from attribute 'style' value of css property "margin". And I'm afraid there is no way using client side JS to read the global definition for css property value unless you have some element on page which marked with this class.
So I guess the reason why always got undefined is because you do not have any element marked with class "myclass".

A: jQuery itself doesn't really help in any way here, everything you want to do centers around document.styleSheets, a basic DOM collection, one jQuery provides no wrappers, etc. around.  The plugin you linked is a good approach (since it's that lightweight), or just loop through the collections in document.styleSheets just like it does.


text:
Q: JPA em java web estou com um projeto em JAVA WEB e estou com problemas com o hibernate. O erro é o seguinte:
Informações:   HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Informações:   HHH000412: Hibernate Core {4.2.2.Final}
Informações:   HHH000206: hibernate.properties not found
Informações:   HHH000021: Bytecode provider name : javassist
Grave:   Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver
Advertência:   StandardWrapperValve[ServeletLogin]: Servlet.service() for servlet ServeletLogin threw exception
java.lang.NullPointerException
at DAOs.LoginDBDAO.selectUsuario(LoginDBDAO.java:35)
at Controllers.ControllerLogin.validaUsuario(ControllerLogin.java:21)
at Servlets.ServeletLogin.doPost(ServeletLogin.java:42)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)....

Procurando pelo google não achei nada. Mas vi pessoas com problemas parecidos E sempre elas colocam imagens da estrutura das paginas então ai vai:
Páginas Web

Bibliotecas

persistence.xml
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="test" >
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbyclient</artifactId>
            <version>10.4.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>tck-utils-api</artifactId>
            <version>0.9.1</version>
        </dependency>

    <class>Entidades.Usuario</class>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/MackEstagios" />
        <property name="javax.persistence.jdbc.user" value="adm" />
        <property name="javax.persistence.jdbc.password" value="adm" />

                    <property name="hibernate.dialect"  value = "org.hibernate.dialect.DerbyDialect"/>

                    <property name="hibernate.hbm2ddl.auto" value = "update"/>
        <property name="hibernate.show_sql"  value = "true"/>
    </properties>
</persistence-unit>

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
 <session-factory>
    <property name="connection.driver_class">
        org.apache.derby.jdbc.ClientDriver
    </property>
    <property name="connection.url">
        jdbc:derby://localhost:1527/MackEstagios
    </property>
    <property name="connection.username">
        adm
    </property>
    <property name="connection.password">
        adm
    </property>
        <property name="dialect">
        org.hibernate.dialect.DerbyDialect
    </property>
</session-factory>

Creio que o erro esteja na configuração do hibernate e não em sua implementação.
Obrigado!

A: Olá,
Você tem dois problemas:

*

*Relacionar o item Grave:   Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/hibernate/util/DTDEntityResolver

*java.lang.NullPointerException
at DAOs.LoginDBDAO.selectUsuario(LoginDBDAO.java:35)
Com relação ao problema do item 1, veja esse link com uma dúvida semelhante a sua. Porém, nesse link há uma diferença de projetos, projeto do link referenciado está utilizando um projeto com arquetipo maven.
Com relação ao problema do item 2, você está tentando utilizar um método com uma instancia de objeto null. Entretanto, esse erro também pode ser proveniente do item 1. Então aconselho verifica-lo primeirom antes de ir adiante no seu desenvolvimento.
Aqui você pode ver que há a classe que seu projeto está necessitando, mas esta versão de biblioteca hibernate-core versão 3.6.0.final não esta sendo utilizada no seu proejto o qual é a versão hibernate-core-4.2.2.Final.jar.


text:
Q: How to connect asterisk to skype using siptosis? I've been trying to do this for weeks and still have not yet figured out how to connect to skype. The best progress I've found out was from this tutorial
http://translate.google.com/translate?hl=en&sl=it&u=http://www.voipandhack.it/archives/linux/asterisk-failover-e-registrazioni-sip&ei=nqJRTNTPB8OfrAfDovGDAw&sa=X&oi=translate&ct=result&resnum=2&ved=0CBoQ7gEwAQ&prev=/search%3Fq%3Dasterisk%2Bauto%2Bfallthrough%2Bsiptosis%26hl%3Den
But whenever I tried to make an echo123 call, my asterisk would show
== Using SIP RTP CoS mark 5
    -- Executing [*123@phones:1] Dial("SIP/1004-00000030", "SIP/siptosisuser/echo123") in new stack
  == Using SIP RTP CoS mark 5
    -- Called siptosisuser/echo123
    -- SIP/siptosisuser-00000031 is ringing
    -- SIP/siptosisuser-00000031 is circuit-busy
  == Everyone is busy/congested at this time (1:0/1/0)
    -- Auto fallthrough, channel 'SIP/1004-00000030' status is 'CONGESTION'
and my siptosis will show:
2010-07-30 10:48:21,596 Failed to select RTP format
2010-07-30 10:48:21,597 ### local descriptor=v=0
o=skypests 1280512101 0 IN IP4 192.168..
s=Session SIP/SDP
c=IN IP4 192.168..
t=0 0
m=audio 63202 RTP/AVP 0 8 98 101
a=rtpmap:0 PCMU/8000
a=rtpmap:8 PCMA/8000
a=rtpmap:98 iLBC/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
a=sendrecv
a=silenceSupp:off
2010-07-30 10:48:21,597 ### remote descriptor=v=0
o=root 1729829715 1729829715 IN IP4 127.0.0.1
s=Asterisk PBX 1.6.2.8
c=IN IP4 127.0.0.1
t=0 0
m=audio 18104 RTP/AVP 3 101
a=rtpmap:3 GSM/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-16
a=silenceSupp:off - - - -
a=ptime:20
a=sendrecv
I've changed my IP address to 192.168.. just for security reasons. It seems to be connecting one way or another but I'm assuming I'm doing something wrong somewhere in the code? I also haven't touched the siptosis.cfg because the tutorial I specified didn't do it. The cfg file also didn't come with the siptosis package I downloaded but I was able to find a copy from another tutorial on the nerdvittle website
This is suppose to be the tutorial that makes it easy to setup but it doesn't seem to work on mine. I just want to have some call to echo123 and it seemed to be not working. I'm working on ubuntu and most tutorials are on CentOS so there's not much to solve my problem. I also am not using static skype, will that be a problem?
Any hints/tip/answers would be very much appreciated!
Thank you for your time and thank you in advance!

A: I'm not familiar with SipToSis but you may want to look at the Skype Connect (previously known as Skype for SIP) solution which allows you to make and receive calls direct to/from sip.skype.com using SIP. Unlike Skype for Asterisk, it's free.
Apologies if you already know this and are looking for specific features of SipToSis which are not provided by Skype Connect. Good luck.


text:
Q: When the mass flux is constant, why does $ v d\rho = - \rho dv$? I'm reading about mass fluxes and I came across when the mass flux is constant $$ j = \rho v$$ then the following equation is true $$ v d\rho = - \rho dv$$ What does that last equation even represent? I mean I understand that $\rho$ is density and $v$ is the velocity, but I don't understand it why it is true and what it is.

A: Since $j$ is constant, $dj=\rho dv+ vd\rho=0$.  Any change in the density must be compensated by a change in velocity to keep the mass flow constant.


text:
Q: Can Mongoose Materialized Path and Mongoose Restify be used together? I have implemented a schema/model for a recursive tree structure in Mongoose. The recursive tree structure uses today an array of children which are references to the same schema. I have also built some REST APIs for basic CRUD methods on the tree.
I would now like to refactor my implementation by using two packages that have been designed independently to do what I neeed in a more professional way:

*

*mongoose-mpath - to manage my mongoose tree through a materialized path pattern,
https://www.npmjs.com/package/mongoose-mpath

*express-restify-mongoose - to generate flexible REST interfaces for mongoose models, https://www.npmjs.com/package/express-restify-mongoose
Before I change all my code to these two new patterns, I would like to get some confirmation whether this is the right approach. In other words, a quick assessment whether I can expect that these two packages will work together flawlessly on my tree schema/model, and whether the express-restify-mongoose package will help me to expose the specific methods defined by the mongoose-mpath package as REST APIs:
The mongoose-mpath package:

*

*Adds and manages two fields to the schema for each node in the tree, parent and path, to manage the tree behavior. When parent is updated, it automatically updates the path field.

*This happens under the covers, through .pre hooks on the tree's schema and is called "materialized tree pattern".

*It adds specific get methods for the materialized tree, like getAncestors(), getAllChildren(), getImmediateChildren(), getChildrenTree(), getParent(), level.

Obviously, I would like those 6 get methods offered by mongoose-mpath also exposed as REST APIs!
Generating REST APIs is precisely the job of the other package, express-restify-mongoose:

*

*In its docs, I read that it generates REST APIs like GET, PUT, POST, DELETE, PATCH for a model

*So I assume, if I use it for my new (materialized) tree schema, it will give me such basic CRUD REST APIs.

*Under the covers, I see that it also sets up all kinds of .pre hooks etc.

My specific questions:

*

*Is there risk that those two packages added to my schema will interfere somehow, or can I trust that they will work gracefully together?

*Most important, is there a way to have express-restify generate REST APIs also for the 6 methods defined by the mongoose-mpath package (as listed above)?

*Will that happen automatically for all methods defined on the schema (in this case by MPath), or do I manually need to insert the code for such methods into the folders, files, and code generated by Mongoose Restify (if yes, where and how?)

*Are there other alternatives to achieve what I need? I know there are other REST generators around, but Mongoose Restify seems to be quite popular, probably for a reason.

A:  I used to maintain express-restify-mongoose

Is there risk that those two packages added to my schema will interfere somehow, or can I trust that they will work gracefully together?

They should not interfere, as far as I know, express-restify-mongoose doesn't patch mongoose schemas.

Most important, is there a way to have express-restify generate REST APIs also for the 6 methods defined by the mongoose-mpath package (as listed above)?

express-restify-mongoose only supports mongoose itself, perhaps some form of middleware or hooks could be helpful.

Will that happen automatically for all methods defined on the schema (in this case by MPath), or do I manually need to insert the code for such methods into the folders, files, and code generated by Mongoose Restify (if yes, where and how?)

You'll have to do it manually. serve returns the URI at which the endpoints were mounted so you could use that to defined additional routes.

Are there other alternatives to achieve what I need? I know there are other REST generators around, but Mongoose Restify seems to be quite popular, probably for a reason.

I'm not aware of any but perhaps someone else can chip in!


text:
Q: How to run exception Unit test for one function that calls another function inside of it I am trying to do exception unit test for check_name() function but create_list() is also called. Is there any way I can mock the output of create_list() instead of executing it?
def create_list(token):
   return service_list

def check_name(token, name):

   response = create_list(token)
   existed_list = [app.name for app in response.details]

   if name in existed_list:
      raise NameExists()

I tried this but it still called create_list()
def test_exception_existed_name(self):
    existed_list = [ "p", "r", "g", "x"]
    with pytest.raises(NameExists):
        check_name(token,  "g")

check_name() and create_list() in sp.py
project
│
└───src
│   └───sp_api
│           └───api
│               sp.py
│
└───tests
       test_sp.py

A: You didn't mock create_list; you just created a variable named existed_list in a scope that check_name wouldn't look in even if existed_list weren't defined. You need to use something like unittest.mock.patch
def test_exception_existed_name(self):
    with pytest.raises(NameExists):
        with unittest.mock.patch('create_list', return_value=["p", "r", "g", "x"]):
             check_name(token, "g")

(Depending on where your test is actually defined, you may need to adjust the name you are patching; see https://docs.python.org/3/library/unittest.mock.html#where-to-patch)
(I believe pytest itself also provides facilities for patching things without using unittest.mock.patch directly, but I am not familiar with them.)


text:
Q: How to get all the child text from a xml file I need to get all the values from child node
            <fields>
            <field1>Name</field1>
            <csv1>field1</csv1>
            </fields>

But i am not able to get then at a single loop i need to loop 2 times to get the values my code
 for(Dom.XMLNode subchild : child.getChildElements())
            {
                system.debug('Sub child ' + subchild.getText() );
                for(Dom.XMLNode subchildfield : subchild.getChildren())
                {
                    system.debug('Sub child Field ' + subchildfield.getText() );
                    fName  = subchildfield.getText();
                    fieldName.add(fName);
                    //fileValuesXML.add(fieldName);
                    //system.debug('Filed Name in XML field  ' + fieldName);
                }

                system.debug('Filed Name before affing to filevalueXML  ' + fieldName);
                fileValuesXML.add(fieldName);
                fieldName.clear();
                system.debug('Filed Name after affing to filevalueXML  ' + fileValuesXML);
            }

is it possible to get all the child node values at a single loop so that i can have it in a map. Please guide me

A: These links will help you:
Using APEX DOM parser:
http://developer.force.com/cookbook/recipe/parsing-xml-using-the-apex-dom-parser
Using XMLStreamReader class
http://www.sundoginteractive.com/sunblog/posts/parsing-xml-in-salesforce-apex


text:
Q: how to check for the "backspace" character in C I'd like to know how to check if a user types the "backspace" character.
I'm using the getch() function i.e. "key = getch()" in my C program and i'd like to check when backspace is pressed.  the line:
 if(key = '\b') { ....

doesn't work.

A: The problem with reading Backspace is that most terminals are 'cooked' in that keys like backspace are handled by the terminal driver.  However, the curses function getch() can read the backspace as it's not tied to the terminal.
Edit
I just noticed your code is using getch() for input.  I ran a little test program and getch() returns 127 when you hit backspace.  Therefore try:
if (key == 127 || key == 8) { ... /* Checks for both Delete or Backspace */

Also note that your sample code uses the assignment operator = when it should be using the equality operator ==

A: The type of i/o stream may helps. Standard input stream is a kind of line buffered stream, which do not flush until you write a '\n' char into it. Full buffered stream never flush until the buffer is full. If you write a backspace in full buff stream, the '\b' may be captured.
Reference the unix environment advantage program.

A: You didn't say which library the getch() function comes from (it isn't part of the C standard), but if it's the one from ncurses you can check the value of key against KEY_BACKSPACE.

A: Try this:
#include <stdio.h>      /* printf   */
#include <ctype.h>      /* isalpha isdigit isspace etc      */

#define FALSE 0
#define TRUE  1

/* function declarations */
int char_type(char);

main()
{
 char ch;

 ch = 127;
 char_type(ch);

 ch = '\b';
 char_type(ch);

 return 0;
}

int char_type(char ch)
{
 if ( iscntrl(ch) != FALSE)
   printf("%c is a control character\n", ch);
}

This is a complete program but it only tests for control characters.
You could use principles of it, your choice. Just learning too!
See : http://www.tutorialspoint.com/c_standard_library/ctype_h.htm or lookup the functions for the ctype.h header file of the C Standard Library.
It's good that you're getting input.
Thanks all for the info. I was just looking up backspace code and found this question.
BTW try '\0' before any char. Not sure what that does but it stops all code after it. Is that like the return 0; line?

A: I believe the system input driver is line buffered. So its not possible in standard C.


text:
Q: Surjectivity of the Kodaira-Spencer map Let $X$ be a complex projective manifold. Let $B$ be the closed subscheme of $H^1(X,T_X)$ defined by $\mathfrak{m}^2$, where $\mathfrak{m}$ is the ideal defining the origin. In other words, $B$ is a fat point with tangent space equal to $H^1(X,T_X)$.
There should be a universal infinitesimal deformation $\mathcal{X}$ over $B$. This should correspond to the surjectivity of the Kodaira-Spencer map. Is there a canonical way to define it? Any reference?
ps: I know how to define a first order deformation out of an element $[\eta]\in H^1(X,T_X)$ using local charts and transition functions. I would like a similar result on the full $B$, possibly without using local charts and without choosing a basis of $H^1(X,T_X)$.

A: Edit. I corrected the second short exact sequence.
Here is a "global" description of the sheaf of algebras $\mathcal{O}_{\mathcal{X}}$.  For the affine space $\mathbb{A}$ associated to the vector space $\text{Ext}^1_{\mathcal{O}_X}(\Omega_{X/k},\mathcal{O}_X)$, on the product $\mathbb{A}\times_{\text{Spec}(k)} X$, there is a universal short exact sequence of locally free sheaves, $$ 0 \to \mathcal{O} \to \mathcal{E} \to \text{pr}_X^* \Omega_{X/k} \to 0.$$  If you restrict this to $B$, you get a short exact sequence of locally free $\mathcal{O}_X$-modules on the underlying topological space $X$, $$ 0 \to \mathcal{O}_X\otimes_k \mathcal{O}_B/\mathfrak{m}_B^2 \to \mathcal{F} \xrightarrow{p} \Omega_{X/k} \otimes_k \mathcal{O}_B/\mathfrak{m}_B^2 \to 0. $$  The inclusion of constants $k\to \mathcal{O}_B/\mathfrak{m}_B^2$ gives both a $\mathcal{O}_X$-homomorphism $\Omega_{X/k}\otimes_k k \to \Omega_{X/k}\otimes_k \mathcal{O}_B/\mathfrak{m}_B^2$ and a "quotient by constants" $\mathcal{O}_X$-homomorphism $\mathcal{O}_X\otimes_k \mathcal{O}_B/\mathfrak{m}_B^2 \to \mathcal{O}_X\otimes_k \mathfrak{m}_B/\mathfrak{m}_B^2$.  Taking the pullback of the short exact sequence by the first map and the pushout by the second gives a short exact sequence of $\mathcal{O}_X$-modules,  $$ 0 \to \mathcal{O}_X\otimes_k \mathfrak{m}_B/\mathfrak{m}_B^2 \to \mathcal{F} \xrightarrow{p} \Omega_{X/k} \otimes_k k \to 0. $$ Note that every local section $f$ of $\mathcal{F}$ comes from a local section $e$ of $\mathcal{E}$ such that $p(e)$ equals $\omega\otimes 1$ for some local section $\omega$ of $\Omega_{X/k}$.  Also, two such sections $e$ and $e'$ are considered equivalent if their difference is the image of some $b\otimes 1$ with $b$ a local section of $\mathcal{O}_X$.
There is a natural $k$-linear derivation, $$d_{X/k}: \mathcal{O}_X \to \Omega_{X/k}.$$  The pullback of the short exact sequence by this derivation is a short exact sequence, $$ 0 \to \mathcal{O}_X\otimes_k \mathfrak{m}_B/\mathfrak{m}_B^2 \to \mathcal{O}_{\mathcal{X}} \xrightarrow{q} \mathcal{O}_X \otimes_k k,$$ where $\mathcal{O}_{\mathcal{X}}$ consists of pairs $(a,f)$ of a section $a$ of $\mathcal{O}_X\otimes_k k$ and a section $f$ of $\mathcal{F}$ such that $d_{X/k}(a)$ equals $p(f)$.  Define the product of $(a,f)$ and $(a',f')$ by $(aa',af'+a'f)$.  This makes $\mathcal{O}_{\mathcal{X}}$ into a sheaf of algebras, and $q$ is a homomorphism of sheaves of algebras.  For every constant $c\in k$, there is an element $(a,f)=(c,0)$.  Similarly, for every element $t\in \mathfrak{m}_B/\mathfrak{m}_B^2$, there is an element $(a,f)=(0,1\otimes t)$.  Altogether, this defines a ring homomorphism from $\mathcal{O}_B/\mathfrak{m}_B^2$ to $\Gamma(X,\mathcal{O}_{\mathcal{X}})$ making $\mathcal{O}_{\mathcal{X}}$ into a sheaf of $\mathcal{O}_B/\mathfrak{m}_B^2$-algebras.  The homomorphism $q$ is the quotient by the ideal generated by $\mathfrak{m}_B/\mathfrak{m}_B^2$.  Thus, the natural $\mathcal{O}_B/\mathfrak{m}_B^2$-module homomorphism, $$\mathcal{O}_{\mathcal{X}}/\mathfrak{m}_B \otimes_k \mathfrak{m}_B/\mathfrak{m}_B^2 \to \mathfrak{m}_B\cdot \mathcal{O}_{\mathcal{X}},$$ is an isomorphism.  From the local flatness criterion, $\mathcal{O}_{\mathcal{X}}$ is flat as an $\mathcal{O}_B/\mathfrak{m}_B^2$-algebra.  Thus the sheaf of $\mathcal{O}_B/\mathfrak{m}_B^2$-algebras $\mathcal{O}_{\mathcal{X}}$ together with the algebra homomorphism $q$ defines a flat deformation $\mathcal{X}$ of $X$ over $B$.


text:
Q: How do binary numbers interact with the CPU and cause some action to take place? EDIT: Perhaps what I am misunderstanding is that when it is said that the code we type gets turned into machine code of 0s and 1s. If these 0s and 1s are the abstracted representation of their electric states, then I actually don't have a question (it is just amazing that a compiler can take English and turn it into a form that can impact the processor). If the compiler turns the code a file that contains literal 0s and 1s, then I don't understand the transformation steps steps that strictly occur between this file of literal 0s and 1s and the execution of the program (I understand how programs already in RAM are executed).
I have been researching for an answer to this question all day. I have read a lot about the computer's hardware and understand concepts like the clock, its different states that it "steps" through to execute a program, and (at a basic level) the compiler. I also know that the bits of each part of an instruction code are wired in a certain way so that it does what it is supposed to and the compiler takes the code we write and converts it to binary. But my question is this: how does the processor "understand" this binary (or machine readable) code.
In the computer there are no 0s and 1s obviously, and 0s and 1s are an abstraction themselves reprenting the presence or absence of electricity. So how does a 0 go in one end of the computer and a bit being off come out the other? I understand how this may work with input from the keyboard because I understand how computer peripherals work and get stored to some degree (the wiring underneath the keyboard accomplishes this as an extension of the wiring of the hardware that accomplishes everything that the computer does), but the compiler and the other (seemingly missing) piece of the puzzle that moves the computer to action seem to be a black box right now. Thanks so much in advance, always appreciate any responses.
One last time just to be super clear: I understand the compiler takes our code and converts it to 0s and 1s. That's great, but how does this 0 get interpreted, by a component and/or a process, that causes this abstraction (like the #0) cause one of the computer's bits to be in a different position.
Thanks so much once again. I have searched for hours about this question on this forum and other places and I can't seem to find an answer that moves past the: "yeah the compiler converts to 0s and 1s and those do some stuff". The how is what I am after.

A: CPUs have instruction sets, add two numbers, jump forward 3 instructions, if this is true run the next instruction, if not skip and instruction etc
https://en.wikipedia.org/wiki/Instruction_set_architecture
The 1s and 0s are stored in the memory of the computer and grouped together and read as instructions or data, ie run instruction number 3 or data ie take that bit of memory there and do some operations on it.
Essentially when you compile code you are turning it into combination of these very basic instructions which are stored on disc, loaded into memory and then run by the cpu.
Some of these instructions or areas of memory will map to pins on connectors to devices, such as a graphics card, or disc drive etc and their state, on or off will cause the device to do things.

A: A compiler operates at a logical level, not concerning itself with physical storage, but rather with groupings of 1's and 0's — several different kinds of groupings.  The first grouping is text files aka source code, and the second grouping is machine code.
Text is stored on disc, for example, as a sequence of bytes, where a byte is a group 8-bits that is ordered from most significant to least significant (or vice versa — that's up to the media;  each bit of course is physically encoded in the media as physically measurable values differentiating 1's from 0's).  Each byte represents a number: the number represents an ascii or UTF-8 value.  This is a logical encoding or mapping of logical characters into logical bytes — a layered encoding well above the physical encoding of bits in media.
Machine code is also a logical encoding of command operations to numbers — also well above the physical encodings of bits in media.  It can also be stored on disc as a sequence of bytes.
When the compiler recognizes a program's syntax according to the grammar of the programming language, it builds an internal object diagram of that program.  Later it traverses that object diagram in order to generate commands in machine code to instruct the processor to follow the steps of the program.
Machine code is designed to be easily decoded (at least by comparison to other encodings) — usually there's a first field that is an opcode field that tells the processor something about how to interpret additional fields of the instruction.  The compiler knows these encodings and generates them for the processor such that it will perform the given program.

A:
But my question is this: how does the processor "understand" this binary (or machine readable) code.

It doesn't. It's turns numbers into other numbers and puts them different places based on still other numbers.
What those numbers mean is someone else's problem. That someone sometimes thinks of them differently based on where they are. But they're still just numbers. The  processor doesn't need to know what they are. Just how to transform them and where to put them.

So how does a 0 go in one end of the computer and a bit being off come out the other?

From a microphone or analog joystick being sampled or a keystroke at the keyboard, zero finds its way in through many different ways.
If that joystick has a 100k potentiometer in it you might think 100,000 values can come out. But if I'm sticking the value in one byte then only 256 values can come out. Because a byte only has 8 bits. This is called analog to digital conversion.
Another way is someone just types in a zero at the keyboard because they want a zero. They can do it hex, octal, ascii, heck even binary if they want to be silly. They know where they want the zero and they know what it will mean. Doesn't mean the processor does. All it knows is what it's supposed to do with it.
What we programmers do is use the rules that the processor follows blindly to get some useful work done. That might be letting you see and edit what you've typed on the screen before you put it on paper. It might be hearing what that zero sounds like when a sound card plays it on the system speaker.
What gives that zero meaning in it's different places is often something called an encoding. If we're talking about ascii (or UTF-8) a zero often means this is the end of the string. (Pascal strings tell you how long they are in the first byte. For them zero means a zero length string).
But not everything is encoded text. Some stuff is just data and it doesn't follow any set pattern to tell you what it means. It will only be meaningful to whatever created it.
It is impossible to simply look at a zero and know what it means. You need to know it's context. The processor is no different.
The really magical thing the processor does is copy that zero around faithfully. It doesn't let it turn into a 0.3 when no one is looking like analog stuff does. That's the real reason we use 1 and 0. It's on or off. Anything in between is noise to filter out.
But it takes humans to make that zero into something humans care about. The processor don't care.


text:
Q: Macro defines for bit masks best practices I lately have been using these type of defines in my code:
#define FLAG_1 1U
#define FLAG_2 (1U << 1)
#define FLAG_3 (1U << 2)
...

To kind of improve readibilty instead of writing direct hex or decimal values, and I was wondering wether I am causing my program to actually have to compute bitwise operations on each FLAG_i read or if this is something a modern C compiler (gcc 9.4.0) takes care of and just precomputes the macro value when there are no variables involved.
Any suggestion, personal opinion or insight on the matter is appreciated.

A:
I was wondering wether I am causing my program to actually have to compute bitwise operations on each FLAG_i

No, these are so called integer constant expressions. They are always evaluated at compile-time. If you check the generated machine code you'll notice that they've been replaced with a fixed constant, in this case 0x01, 0x02 or 0x04.
Writing bit masks as named constants through macros like you do is fine and common practice.


text:
Q: How to add a fallback font for a non supported character in font-face? I am using a custom font face for the Hebrew language on a site and I am missing the whole set of English characters a-b, A-Z.
Right now I use the font (reformaregular) on the body tag:
body { font-family: 'reformaregular', Arial, Halvetica, sans-serif; }

English characters come up in the system default of a serif font Times New Roman on windows:

Notice the English serif at the bottom and custom hebrew font at the top.
Aside from tagging everything with a custom .en class;
My question is how do I add a fallback for the English font?

A: Actually if I understand your question right you can by using css unicode-range
see @font-face/unicode-range at: https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range
and a quick example:
@font-face {
    font-family: Almoni;
    src: url(Almoni.ttf);
    unicode-range: U+0590-05FF;
}
@font-face {
    font-family: CoolOtherLanguageFont;
    src: url(CoolOtherLanguageFont.ttf);
    unicode-range: U+0370-03FF, U+1F00-1FFF;
}
body {
    font-family: Almoni, CoolOtherLanguageFont, Helvetica;
}

A: You can't have different font for different languages. If your Hebrew font does not have English character set (or digits for example) than you are out of luck. The only way we found was to run a javascript that detects non-Hebrew charset and adds an .english or lang attribute to the text with the correct English font.


text:
Q: How can I distinguish a swipe from an automatic slide on mobile device in a slider (in this case lory.js) I'm trying to figure out when a slide is swiped via touch by the user rather than sliding automatically (carousel style). I'm really struggling to come up with a solution that lets me detect it. My main problem is that if I do the action in the touch events provided by lory.js, the action is also fired when the user touches the element while scrolling the site rather than when swiping.
I thought about using the after slide event but that fires every time a slide slides both automatically and when a user swipes.
Is there maybe a way to combine the after.slide and touch events? Or does anyone have an idea/concept that could help me solve this?
Much Thanks!


text:
Q: Migrando de Firebird para MySQL Estou migrando um projeto em Firebird para MySQL, estou com uma
dificuldade na conversão de uma procedure, gostaria de qualquer dica em
como proceder, segue abaixo a procedure em FIREBIRD.
CREATE PROCEDURE EXECUTA_INATIVA_TABELAS (
    OPERADOR VARCHAR(20),
    ALTERACAO TIMESTAMP)
AS
   DECLARE CGC VARCHAR(18);
   DECLARE VIGENCIA TIMESTAMP;
BEGIN
   FOR
      SELECT CGC, VIG_TAB
      FROM PARM_CALCULO
      WHERE ( VIG_TAB IS NOT NULL )
      INTO :CGC, :VIGENCIA
   DO
   BEGIN
      EXECUTE PROCEDURE INATIVA_TABELAS(:CGC, :VIGENCIA, :OPERADOR,
:ALTERACAO);
   END

   SUSPEND;
END^

A: FIZ UM EXEMPLO E FUNCIONOU SHOW.
CREATE DEFINER=`sistema`@`localhost` PROCEDURE `ADDMESAS`()
BEGIN
declare  i integer;
delete from mesas ;
 SET i = 1;

 while  i <= 160  do
   insert into mesas (num, status) values (i, 'F');
   SET i = i + 1;
 END WHILE;

    update mesas set status = 'A'
    where num in (select codigo from r000001 );

END


text:
Q: Relatório no IREPORT - STATUS Bom dia , preciso alterar um relatório no IREPORT que hoje funciona asim:
Atualmente o campo funciona assim:
    (Boolean)
    $F{documentoVigente} ? "VIGENTE" : "VENCIDO"

Tenho um text chamado  $F{documentoVigente} passando uma expression class (java String)
Preciso que meu relatorio seja gerado assim hoje:
        if $F{dataVencimento} = $F{CurrentDate} : "VIGENTE"
        if else $F{dataVencimento} < $F{CurrentDate} : "VENCIDO"
        else : "VENCENDO" > a data do dia

Tenho uma classe que faz referencia a esse relatorio:
public  class  RepDtoReport  implement Serizable {

private String nomeRepresentante;
private Integer cartaoAssinatura;
private String descricaoGrupo;
private String codigoPessoa;
private String descricaoCargo;
private String descricaoDocumento;
private Date dataAtualizacao;

private  Date   dataVencimento;

private boolean documentoVigente;

}getts e setters}

public boolean is documentoVigente() {
return documentoVigente;
}

public void setDocumentoVigente (final boolean documentoVigente){
this.documentoVigente = documentoVigente;
}

public  Date getDataVencimento() {
return dataVencimento;
}

public void setDocumentoVigente (final Date dataVencimento ){
this.dataVencimento = dataVencimento;
}

Hoje ele esta assim:

Consigo fazer apenas no ireport ?

A: Eu tenho uma prática que gosto muito de usar. Na geração de relatórios, gosto de separar processamento de dados para o banco e IO para a aplicação.
Pensando nesse sentido, quando você faz uma consulta no banco e traz uma N de registros, ao oferecer isso para a camada de aplicação a mesma precisa iterar em cada um dos registros para aplicar a regra.
Exemplo: Uma consulta que retorna 100 registros acaba processando estes mesmo 100 para chegar ao resultado desejado aplicando as regras do relatório.
Minha dica pra você é analisar a viabilidade de utilizar uma VIEW já com todas as regras necessárias ao seu relatório. Óbvio que desatrela regras da aplicação tem seus ônus e bônus, porém há um ganho enorme em processamento que pode ser uma vantagem, sem contar a facilidade de implementar em qualquer ferramenta de Report.


text:
Q: how to show a "window/subactivity/dialog" on top of an Activity but keeping the focus in the Activity My activity A is a game and it does some background operations. When I press a button in the contextual menu, I want to pop up a "small window/dialog/subactivity" (lets call it B) that appears on top of activity A and displays some data about those background operations. But I need to keep the focus on the activity A in order to continue interacting with it (playing the game).
In essence, I want to be able to see the data display by B while playing the game.
I'm not really sure how to implement this. After reading the documentation I have the next conclusions:

*

*I know that I can't use Dialogs because the have the focus. Is it possible to avoid this?

*Using a subactivity with a Dialog theme it's another option that looks tempting...but I believe that the subactivity has the focus. Ditto.

*My last option is to try to add a LinearLayout with my data to the main Layout, "sharing/splitting" the screen. It's not pretty, but at least I know that this is possible. What I don't like about this approach is that I use the  width and height of the screen.

Any suggestions? Solutions?
PS: I found some this thread here that are very related to my question:

*

*Android ==> Sub Activity?

A: Create an Activity with style Theme.Dialog. This is a normal activity which looks like a dialog, while being modeless and accepting events.
Additional catch is in setting WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL and resetting WindowManager.LayoutParams.FLAG_DIM_BEHIND.
See this answer for complete example: timed modeless dialog

A: Why not use a FrameLayout that is apart of your Activity? Just ensure that this View has a higher z index (make sure you declare it last in your XML layout or create it at runtime). That way you never leave your Activity.